blob: 0d35b3a0a4fc2b7b15e0b2e8a0bede1dc9a78a84 [file]
/*
* Copyright (C) 2026 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.binarytransparency
import android.net.Uri
import android.os.SystemProperties
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.android.settings.binarytransparency.AttestationUtils.AttestedBuildInformation
import com.google.gson.Gson
import java.security.SecureRandom
import java.security.cert.X509Certificate
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/** Exposes the visual state of the Binary Transparency settings screen. */
sealed interface BinaryTransparencyUiState {
object Loading : BinaryTransparencyUiState
data class Success(
val buildInformation: Map<AttestedBuildInformation, String?>,
val expandableInformation: Map<String, OptionData>,
) : BinaryTransparencyUiState
data class Error(val errorType: ErrorType) : BinaryTransparencyUiState
}
enum class ErrorType {
DEVICE_FAILURE,
NETWORK_ERROR,
}
class BinaryTransparencyViewModel(
private val repository: BinaryTransparencyRepository = BinaryTransparencyRepository()
) : ViewModel() {
private val _uiState =
MutableStateFlow<BinaryTransparencyUiState>(BinaryTransparencyUiState.Loading)
val uiState: StateFlow<BinaryTransparencyUiState> = _uiState.asStateFlow()
fun generateAndValidateKeyAttestationCertificate() {
Log.i(TAG, "generateAndValidateKeyAttestationCertificate")
viewModelScope.launch {
_uiState.value = BinaryTransparencyUiState.Loading
try {
val challenge = ByteArray(CHALLENGE_LENGTH)
SecureRandom().nextBytes(challenge)
val buildInformation = repository.getBuildInformation(challenge)
val vbmetaDigest = buildInformation[AttestedBuildInformation.VERIFIED_BOOT_HASH_KEY]
if (vbmetaDigest.isNullOrEmpty()) {
Log.e(TAG, "could not get verified boot hash")
_uiState.value = BinaryTransparencyUiState.Error(ErrorType.DEVICE_FAILURE)
return@launch
}
val networkResponse = repository.getBuildInformationFromNetwork(vbmetaDigest)
if (networkResponse.isEmpty()) {
Log.e(TAG, "Server returned empty response")
_uiState.value = BinaryTransparencyUiState.Error(ErrorType.NETWORK_ERROR)
return@launch
}
val expandableInformation = mutableMapOf<String, OptionData>()
parseServerResponse(networkResponse, expandableInformation)
extractBootloaderAndBootState(buildInformation, expandableInformation)
_uiState.value =
BinaryTransparencyUiState.Success(buildInformation, expandableInformation)
} catch (e: AttestationException) {
Log.e(TAG, "Attestation certificate failure", e)
_uiState.value = BinaryTransparencyUiState.Error(ErrorType.DEVICE_FAILURE)
} catch (e: TrustAnchorException) {
Log.e(TAG, "Trust anchor download failure", e)
_uiState.value = BinaryTransparencyUiState.Error(ErrorType.NETWORK_ERROR)
} catch (e: ValidationException) {
Log.e(TAG, "Attestation validation failure", e)
_uiState.value = BinaryTransparencyUiState.Error(ErrorType.DEVICE_FAILURE)
} catch (e: NetworkException) {
Log.e(TAG, "Network dynamic query failure", e)
_uiState.value = BinaryTransparencyUiState.Error(ErrorType.NETWORK_ERROR)
} catch (e: Exception) {
Log.e(TAG, "Generic load failure", e)
_uiState.value = BinaryTransparencyUiState.Error(ErrorType.DEVICE_FAILURE)
}
}
}
private fun parseServerResponse(
info: String,
expandableInformation: MutableMap<String, OptionData>,
) {
val mutableMap = mutableMapOf<String, String>()
val mapping: Map<String, String> =
try {
Gson().fromJson(info, mutableMap::class.java)
} catch (e: Exception) {
Log.e(TAG, "Failed to parse server response", e)
mutableMap
}
if (mapping.containsKey("certifiedBuild")) {
expandableInformation[BinaryTransparencyFragment.CERTIFIED_BUILD_KEY] =
OptionData.PlayProtectData(mapping["certifiedBuild"] == "APPROVED_BUILD")
}
}
private fun extractBootloaderAndBootState(
buildInformation: Map<AttestedBuildInformation, String?>,
expandableInformation: MutableMap<String, OptionData>,
) {
val bootloaderLocked = buildInformation[AttestedBuildInformation.BOOTLOADER_LOCKED_KEY]
if (bootloaderLocked != null) {
expandableInformation[BinaryTransparencyFragment.BOOTLOADER_LOCKED_KEY] =
OptionData.BootloaderData(bootloaderLocked.toBoolean())
}
val verifiedBootState = buildInformation[AttestedBuildInformation.VERIFIED_BOOT_STATE_KEY]
if (verifiedBootState != null) {
val bootStatus =
when (verifiedBootState) {
"VERIFIED" -> BootStatus.VERIFIED
"SELF_SIGNED" -> BootStatus.SELF_SIGNED
"UNVERIFIED" -> BootStatus.UNVERIFIED
"FAILED" -> BootStatus.FAILED
else -> BootStatus.UNVERIFIED
}
expandableInformation[BinaryTransparencyFragment.BOOT_STATE_KEY] =
OptionData.BootData(bootStatus)
}
}
companion object {
private const val TAG = "BinaryTransparencyViewModel"
private const val CHALLENGE_LENGTH = 32
}
}
class BinaryTransparencyRepository {
private val binaryTransparencyApiUrl =
SystemProperties.get("android.transparency.prevalence_url")
suspend fun getBuildInformation(challenge: ByteArray): Map<AttestedBuildInformation, String?> =
withContext(ioDispatcher) {
val certs: List<X509Certificate>
try {
certs = AttestationUtils.generateAttestationCertificate(challenge)
} catch (e: Exception) {
throw AttestationException(e)
}
if (AttestationUtils.getProdAnchors().isEmpty()) {
throw TrustAnchorException("Could not download trust anchors")
}
if (!AttestationUtils.validateCertificateChain(certs, challenge)) {
throw ValidationException("Failed to validate attestation certificate")
}
AttestationUtils.extractBuildInformation(certs)
}
suspend fun getBuildInformationFromNetwork(vbmetaDigest: String): String =
withContext(ioDispatcher) {
try {
val url =
Uri.parse(binaryTransparencyApiUrl)
.buildUpon()
.scheme("https")
.appendEncodedPath(BINARY_TRANSPARENCY_API_PATH)
.appendPath(vbmetaDigest)
.build()
NetworkUtils.readFromNetwork(url.toString())
} catch (e: Exception) {
throw NetworkException(e)
}
}
companion object {
private const val BINARY_TRANSPARENCY_API_PATH = "v1:fetchBuildInformation/vbmeta"
var ioDispatcher: CoroutineDispatcher = Dispatchers.IO
}
}
class AttestationException(cause: Exception) : Exception(cause)
class TrustAnchorException(message: String) : Exception(message)
class ValidationException(message: String) : Exception(message)
class NetworkException(cause: Exception) : Exception(cause)
class BinaryTransparencyViewModelFactory(
private val repository: BinaryTransparencyRepository = BinaryTransparencyRepository()
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(BinaryTransparencyViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return BinaryTransparencyViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}