205 lines · 8.0 KB · KotlinRaw
package com.cottondb.android.platformimport android.security.keystore.KeyGenParameterSpecimport android.security.keystore.KeyInfoimport android.security.keystore.KeyPropertiesimport android.os.Buildimport android.util.Base64import androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistryimport java.io.Fileimport java.security.KeyFactoryimport java.security.KeyPairGeneratorimport java.security.KeyStoreimport java.security.spec.MGF1ParameterSpecimport java.util.UUIDimport javax.crypto.Cipherimport javax.crypto.spec.OAEPParameterSpecimport javax.crypto.spec.PSourceimport org.junit.Afterimport org.junit.Assert.assertArrayEqualsimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertTrueimport org.junit.Assert.failimport org.junit.Assume.assumeTrueimport org.junit.Testimport org.junit.runner.RunWith/** Android Keystore coverage using unique aliases and slots, never the production vault. */@RunWith(AndroidJUnit4::class)class VaultKeyringTest { private val context = InstrumentationRegistry.getInstrumentation().targetContext private val id = UUID.randomUUID().toString() private val alias = "com.cottondb.cotton.test.vault-key.$id" private val directory = File(context.noBackupFilesDir, "vault-key-test-$id") private val privateSlot = File(directory, "vault-key.v1") private val publicSlot = File(directory, "vault-public-key.v1") @After fun cleanUp() { directory.deleteRecursively() KeyStore.getInstance("AndroidKeyStore").also { it.load(null) it.deleteEntry(alias) it.deleteEntry("$alias.other") } } @Test fun forgetDeletesOnlyMatchingSlotsAndWrappingAliasAndIsRetrySafe() { directory.mkdirs() privateSlot.writeBytes(ByteArray(257) { 7 }) publicSlot.writeText(encodedKey(4)) createTestWrappingKey(alias) val otherPrivate = File(directory, "other-vault-key.v1").also { it.writeBytes(byteArrayOf(1)) } val otherPublic = File(directory, "other-vault-public-key.v1").also { it.writeText("keep") } createTestWrappingKey("$alias.other") val store = KeyStore.getInstance("AndroidKeyStore").also { it.load(null) } val keyring = VaultKeyring(alias, privateSlot, publicSlot) keyring.forget() keyring.forget() assertFalse(privateSlot.exists()) assertFalse(publicSlot.exists()) assertFalse(store.containsAlias(alias)) assertTrue(otherPrivate.exists()) assertTrue(otherPublic.exists()) assertTrue(store.containsAlias("$alias.other")) } @Test fun cachedPublicKeyNamesAnIncompleteCacheWithoutAPrivateSlot() { directory.mkdirs() publicSlot.writeText(encodedKey(8)) val keyring = VaultKeyring(alias, privateSlot, publicSlot) assertVaultFailure { keyring.cachedPublicKey() } } @Test fun incompleteVaultArtifactsRefuseAReplacementKey() { directory.mkdirs() publicSlot.writeText(encodedKey(8)) createTestWrappingKey(alias) val keyring = VaultKeyring(alias, privateSlot, publicSlot) assertVaultFailure { keyring.publicKey() } assertVaultFailure { keyring.cachedPublicKey() } assertFalse(privateSlot.exists()) } @Test fun cachedPublicKeyRejectsANoncanonicalBase64urlSpelling() { directory.mkdirs() privateSlot.writeBytes(ByteArray(257) { 7 }) publicSlot.writeText(encodedKey(0).dropLast(1) + "B") createTestWrappingKey(alias) assertVaultFailure { VaultKeyring(alias, privateSlot, publicSlot).cachedPublicKey() } } @Test fun AndroidKeystoreEncryptsAndDecryptsWithTheExplicitPortableOAEPParameters() { createTestWrappingKey(alias) val store = KeyStore.getInstance("AndroidKeyStore").also { it.load(null) } val certificate = checkNotNull(store.getCertificate(alias)) val private = checkNotNull(store.getKey(alias, null)) val plaintext = ByteArray(32) { it.toByte() } val encrypt = Cipher.getInstance(RSA_TRANSFORMATION).apply { init(Cipher.ENCRYPT_MODE, certificate.publicKey, OAEP_SPEC) } val ciphertext = encrypt.doFinal(plaintext) val decrypt = Cipher.getInstance(RSA_TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, private, OAEP_SPEC) } assertEquals(256, ciphertext.size) assertArrayEquals(plaintext, decrypt.doFinal(ciphertext)) } @Test fun productionVaultWrappingKeyRequiresEveryUseAndSurvivesBiometricEnrollment() { requireVaultAuthenticationSetup() val keyring = VaultKeyring(alias, privateSlot, publicSlot) checkNotNull(keyring.publicKey()) val store = KeyStore.getInstance("AndroidKeyStore").also { it.load(null) } val privateKey = checkNotNull(store.getKey(alias, null)) val info = KeyFactory.getInstance(privateKey.algorithm, "AndroidKeyStore") .getKeySpec(privateKey, KeyInfo::class.java) assertTrue(info.isUserAuthenticationRequired) // The API 30 authenticator-union API reports its per-operation timeout as 0; // the older biometric-only setter reports the equivalent per-use policy as -1. assertEquals(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) 0 else -1, info.userAuthenticationValidityDurationSeconds) assertFalse(info.isInvalidatedByBiometricEnrollment) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { assertEquals( KeyProperties.AUTH_BIOMETRIC_STRONG or KeyProperties.AUTH_DEVICE_CREDENTIAL, info.userAuthenticationType, ) } } private fun requireVaultAuthenticationSetup() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val keyguard = checkNotNull(context.getSystemService(android.app.KeyguardManager::class.java)) val biometric = androidx.biometric.BiometricManager.from(context) .canAuthenticate( androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG or androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL, ) assumeTrue( "Run with a secure lock screen or enrolled strong biometric.", keyguard.isDeviceSecure || biometric == androidx.biometric.BiometricManager.BIOMETRIC_SUCCESS, ) } else { assumeTrue( "Run with -e cotton.realBiometric true after enrolling an emulator fingerprint.", InstrumentationRegistry.getArguments().getString("cotton.realBiometric") == "true", ) } } private fun createTestWrappingKey(alias: String) { KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore").apply { initialize( KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) .setKeySize(2048) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) .setDigests(KeyProperties.DIGEST_SHA256) .setUserAuthenticationRequired(false) .build(), ) generateKeyPair() } } private fun encodedKey(value: Int): String = Base64.encodeToString( ByteArray(32) { value.toByte() }, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP, ) private fun assertVaultFailure(block: () -> Unit) { try { block() fail("Expected VaultKeyException") } catch (_: VaultKeyException) { // The state is visible to the caller and no replacement was minted. } } private companion object { const val RSA_TRANSFORMATION = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" val OAEP_SPEC = OAEPParameterSpec( "SHA-256", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT, ) }}