Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PI: Fix Failed to generate key pair and related crashes #2740

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,11 @@ import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.MessageDigest
import java.security.ProviderException
import java.security.spec.ECGenParameterSpec
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
Expand Down Expand Up @@ -182,21 +184,44 @@ fun fetchCertificateChain(context: Context, attestationChallenge: ByteArray?): L
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
val devicePropertiesAttestationIncluded = context.packageManager.hasSystemFeature("android.software.device_id_attestation")
val keyGenParameterSpecBuilder =
KeyGenParameterSpec.Builder("integrity.api.key.alias", KeyProperties.PURPOSE_SIGN).setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1")).setDigests(KeyProperties.DIGEST_SHA512)
.setAttestationChallenge(attestationChallenge)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
keyGenParameterSpecBuilder.setDevicePropertiesAttestationIncluded(devicePropertiesAttestationIncluded)
}
val keyGenParameterSpec = keyGenParameterSpecBuilder.build()
val keyPairGenerator = KeyPairGenerator.getInstance("EC", "AndroidKeyStore").apply {
initialize(keyGenParameterSpec)
KeyGenParameterSpec.Builder("integrity.api.key.alias", KeyProperties.PURPOSE_SIGN).apply {
this.setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
this.setDigests(KeyProperties.DIGEST_SHA512)
if (devicePropertiesAttestationIncluded) {
this.setAttestationChallenge(attestationChallenge)
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
this.setDevicePropertiesAttestationIncluded(devicePropertiesAttestationIncluded)
}
}
val generator = KeyPairGenerator.getInstance("EC", "AndroidKeyStore")
var generateKeyPair = false
var keyPair: KeyPair? = null
val exceptionClassesCaught = HashSet<Class<Exception>>()
while (!generateKeyPair) {
try {
generator.initialize(keyGenParameterSpecBuilder.build())
keyPair = generator.generateKeyPair()
generateKeyPair = true
} catch (e: Exception) {
// Catch each exception class at most once.
// If we've caught the exception before, tried to correct it, and still catch the
// same exception, then we can't fix it and the exception should be thrown further
if (exceptionClassesCaught.contains(e.javaClass)) {
break
}
exceptionClassesCaught.add(e.javaClass)
if (e is ProviderException) {
keyGenParameterSpecBuilder.setAttestationChallenge(null)
}
}
}
if (keyPairGenerator.generateKeyPair() == null) {
if (keyPair == null) {
Log.w(TAG, "Failed to create the key pair.")
return emptyList()
}
val keyStore: KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val certificateChainList = keyStore.getCertificateChain(keyGenParameterSpec.keystoreAlias)?.let { chain ->
val certificateChainList = keyStore.getCertificateChain("integrity.api.key.alias")?.let { chain ->
chain.map { it.encoded.toByteString() }
}
if (certificateChainList.isNullOrEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,52 +229,52 @@ private class ExpressIntegrityServiceImpl(private val context: Context, override
override fun requestExpressIntegrityToken(bundle: Bundle, callback: IExpressIntegrityServiceCallback?) {
Log.d(TAG, "requestExpressIntegrityToken bundle:$bundle")
lifecycleScope.launchWhenCreated {
val expressIntegritySession = ExpressIntegritySession(
packageName = bundle.getString(KEY_PACKAGE_NAME) ?: "",
cloudProjectVersion = bundle.getLong(KEY_CLOUD_PROJECT, 0L),
sessionId = Random.nextLong(),
requestHash = bundle.getString(KEY_NONCE),
originatingWarmUpSessionId = bundle.getLong(KEY_WARM_UP_SID, 0),
verdictOptOut = bundle.getIntegerArrayList(KEY_REQUEST_VERDICT_OPT_OUT),
webViewRequestMode = bundle.getInt(KEY_REQUEST_MODE, 0)
)

if (TextUtils.isEmpty(expressIntegritySession.packageName)) {
Log.w(TAG, "packageName is empty.")
callback?.onRequestResult(bundleOf(KEY_ERROR to IntegrityErrorCode.INTERNAL_ERROR))
return@launchWhenCreated
}

if (expressIntegritySession.cloudProjectVersion <= 0L) {
Log.w(TAG, "cloudProjectVersion error")
callback?.onRequestResult(bundleOf(KEY_ERROR to IntegrityErrorCode.CLOUD_PROJECT_NUMBER_IS_INVALID))
return@launchWhenCreated
}
runCatching {
val expressIntegritySession = ExpressIntegritySession(
packageName = bundle.getString(KEY_PACKAGE_NAME) ?: "",
cloudProjectVersion = bundle.getLong(KEY_CLOUD_PROJECT, 0L),
sessionId = Random.nextLong(),
requestHash = bundle.getString(KEY_NONCE),
originatingWarmUpSessionId = bundle.getLong(KEY_WARM_UP_SID, 0),
verdictOptOut = bundle.getIntegerArrayList(KEY_REQUEST_VERDICT_OPT_OUT),
webViewRequestMode = bundle.getInt(KEY_REQUEST_MODE, 0)
)

if (expressIntegritySession.requestHash?.length!! > 500) {
Log.w(TAG, "requestHash error")
callback?.onRequestResult(bundleOf(KEY_ERROR to IntegrityErrorCode.REQUEST_HASH_TOO_LONG))
return@launchWhenCreated
}
if (TextUtils.isEmpty(expressIntegritySession.packageName)) {
Log.w(TAG, "packageName is empty.")
callback?.onRequestResult(bundleOf(KEY_ERROR to IntegrityErrorCode.INTERNAL_ERROR))
return@launchWhenCreated
}

updateExpressSessionTime(context, expressIntegritySession, refreshWarmUpMethodTime = false, refreshRequestMethodTime = true)
if (expressIntegritySession.cloudProjectVersion <= 0L) {
Log.w(TAG, "cloudProjectVersion error")
callback?.onRequestResult(bundleOf(KEY_ERROR to IntegrityErrorCode.CLOUD_PROJECT_NUMBER_IS_INVALID))
return@launchWhenCreated
}

val defaultAccountName: String = runCatching {
if (expressIntegritySession.webViewRequestMode != 0) {
RESULT_UN_AUTH
} else {
AccountManager.get(context).getAccountsByType(DEFAULT_ACCOUNT_TYPE).firstOrNull()?.name ?: RESULT_UN_AUTH
if (expressIntegritySession.requestHash?.length!! > 500) {
Log.w(TAG, "requestHash error")
callback?.onRequestResult(bundleOf(KEY_ERROR to IntegrityErrorCode.REQUEST_HASH_TOO_LONG))
return@launchWhenCreated
}
}.getOrDefault(RESULT_UN_AUTH)

val integrityRequestWrapper = getIntegrityRequestWrapper(context, expressIntegritySession, defaultAccountName)
if (integrityRequestWrapper == null) {
Log.w(TAG, "integrityRequestWrapper is null")
callback?.onRequestResult(bundleOf(KEY_ERROR to IntegrityErrorCode.INTEGRITY_TOKEN_PROVIDER_INVALID))
return@launchWhenCreated
}
updateExpressSessionTime(context, expressIntegritySession, refreshWarmUpMethodTime = false, refreshRequestMethodTime = true)

val defaultAccountName: String = runCatching {
if (expressIntegritySession.webViewRequestMode != 0) {
RESULT_UN_AUTH
} else {
AccountManager.get(context).getAccountsByType(DEFAULT_ACCOUNT_TYPE).firstOrNull()?.name ?: RESULT_UN_AUTH
}
}.getOrDefault(RESULT_UN_AUTH)

val integrityRequestWrapper = getIntegrityRequestWrapper(context, expressIntegritySession, defaultAccountName)
if (integrityRequestWrapper == null) {
Log.w(TAG, "integrityRequestWrapper is null")
callback?.onRequestResult(bundleOf(KEY_ERROR to IntegrityErrorCode.INTEGRITY_TOKEN_PROVIDER_INVALID))
return@launchWhenCreated
}

try {
val integritySession = IntermediateIntegritySession.Builder().creationTime(makeTimestamp(System.currentTimeMillis())).requestHash(expressIntegritySession.requestHash)
.sessionId(Random.nextBytes(8).toByteString()).timestampMillis(0).build()

Expand All @@ -297,8 +297,8 @@ private class ExpressIntegrityServiceImpl(private val context: Context, override
)
)
Log.d(TAG, "requestExpressIntegrityToken token: $token, sid: ${expressIntegritySession.sessionId}, mode: ${expressIntegritySession.webViewRequestMode}")
} catch (exception: RemoteException) {
Log.e(TAG, "requesting token has failed for ${expressIntegritySession.packageName}.")
}.onFailure {
Log.e(TAG, "requesting token has failed for ${bundle.getString(KEY_PACKAGE_NAME)}.")
callback?.onRequestResult(bundleOf(KEY_ERROR to IntegrityErrorCode.INTEGRITY_TOKEN_PROVIDER_INVALID))
}
}
Expand Down
Loading