diff --git a/app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt b/app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt index d627c64590..fe7594ed7b 100644 --- a/app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt +++ b/app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt @@ -1,6 +1,10 @@ package to.bitkit.data.keychain import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringPreferencesKey import androidx.room.Room import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 @@ -8,16 +12,21 @@ import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.junit.After +import org.junit.Assume.assumeTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import to.bitkit.data.AppDb import to.bitkit.data.entities.ConfigEntity +import to.bitkit.ext.fromBase64 +import to.bitkit.ext.toBase64 import to.bitkit.test.BaseAndroidTest import to.bitkit.test.annotations.DeviceIntegration import to.bitkit.test.annotations.DeviceStorageIntegration +import javax.crypto.KeyGenerator import kotlin.test.assertEquals import kotlin.test.assertFailsWith +import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue @@ -112,6 +121,147 @@ class KeychainTest : BaseAndroidTest() { assertEquals(attemptsRemaining, result.toString()) } + @Test + fun upsertString_largeValueKey_loadString() = test { + val key = Keychain.Key.PAYKIT_RECOVERY_BACKUP.name + val value = "a".repeat(1_000_000) + + try { + sut.upsertString(key, value) + + assertEquals(value, sut.loadString(key)) + val stored = requireNotNull(appContext.keychainDataStore.data.first()[stringPreferencesKey("${key}_0")]) + assertTrue(stored.startsWith(Keychain.LARGE_VALUE_PREFIX)) + val decrypted = largeValueKeyStore() + .decrypt(stored.removePrefix(Keychain.LARGE_VALUE_PREFIX).fromBase64()) + assertEquals(value, decrypted.decodeToString()) + } finally { + sut.delete(key) + } + } + + @Test + fun loadString_largeValueKeyWrittenWithMainKey_shouldDecrypt() = test { + val key = Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name + val value = "retained backup" + try { + val encrypted = AndroidKeyStore(alias = "keychain").encrypt(value.toByteArray()) + appContext.keychainDataStore.edit { it[stringPreferencesKey("${key}_0")] = encrypted.toBase64() } + + assertEquals(value, sut.loadString(key)) + } finally { + sut.delete(key) + } + } + + @Test + fun wipe_shouldResetLargeValueKey() = test { + val key = Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name + val storedKey = stringPreferencesKey("${key}_0") + try { + sut.upsertString(key, "before") + val before = requireNotNull(appContext.keychainDataStore.data.first()[storedKey]) + assertTrue(before.startsWith(Keychain.LARGE_VALUE_PREFIX)) + + sut.wipe() + + assertFalse(AndroidKeyStore.containsAlias(Keychain.LARGE_VALUE_ALIAS)) + sut.upsertString(key, "after") + assertEquals("after", sut.loadString(key)) + val after = requireNotNull(appContext.keychainDataStore.data.first()[storedKey]) + assertTrue(after.startsWith(Keychain.LARGE_VALUE_PREFIX)) + assertFailsWith { + largeValueKeyStore() + .decrypt(before.removePrefix(Keychain.LARGE_VALUE_PREFIX).fromBase64()) + } + } finally { + sut.delete(key) + } + } + + @Test + fun upsertString_largeValueKeyUnusable_shouldUseMainKey() = test { + assumeTrue(largeValueKeys.none(sut::exists)) + val key = Keychain.Key.USDT_PENDING_BACKUP_RESTORE.name + val value = "backup" + try { + KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore").apply { + init(KeyGenParameterSpec.Builder(Keychain.LARGE_VALUE_ALIAS, KeyProperties.PURPOSE_SIGN).build()) + }.generateKey() + + sut.upsertString(key, value) + + val stored = requireNotNull(appContext.keychainDataStore.data.first()[stringPreferencesKey("${key}_0")]) + assertFalse(stored.startsWith(Keychain.LARGE_VALUE_PREFIX)) + assertEquals(value, sut.loadString(key)) + } finally { + deleteLargeValueEntries() + largeValueKeyStore().deleteKey() + } + } + + @Test + fun loadString_largeValueKeyMissing_shouldFailWithoutCreatingKey() = test { + assumeTrue(largeValueKeys.none(sut::exists)) + val key = Keychain.Key.PAYKIT_RECOVERY_BACKUP.name + try { + sut.upsertString(key, "backup") + largeValueKeyStore().deleteKey() + + assertFailsWith { sut.loadString(key) } + assertFalse(AndroidKeyStore.containsAlias(Keychain.LARGE_VALUE_ALIAS)) + } finally { + deleteLargeValueEntries() + } + } + + @Test + fun upsertString_largeValueKeyMissingWithTaggedEntries_shouldUseMainKeyWithoutCreatingKey() = test { + assumeTrue(largeValueKeys.none(sut::exists)) + val key = Keychain.Key.USDT_PENDING_BACKUP_RESTORE.name + try { + sut.upsertString(Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name, "tagged") + largeValueKeyStore().deleteKey() + + sut.upsertString(key, "backup") + + val stored = requireNotNull(appContext.keychainDataStore.data.first()[stringPreferencesKey("${key}_0")]) + assertFalse(stored.startsWith(Keychain.LARGE_VALUE_PREFIX)) + assertEquals("backup", sut.loadString(key)) + assertFalse(AndroidKeyStore.containsAlias(Keychain.LARGE_VALUE_ALIAS)) + } finally { + deleteLargeValueEntries() + } + } + + @Test + fun loadString_largeValueEntryInOtherSlot_shouldFail() = test { + val key = "keyTaggedElsewhere" + val encrypted = largeValueKeyStore().apply { createKeyIfMissing() }.encrypt("".toByteArray()) + try { + appContext.keychainDataStore.edit { + it[stringPreferencesKey("${key}_0")] = Keychain.LARGE_VALUE_PREFIX + encrypted.toBase64() + } + + assertFailsWith { sut.loadString(key) } + } finally { + sut.delete(key) + } + } + + private val largeValueKeys = listOf( + Keychain.Key.PAYKIT_RECOVERY_BACKUP.name, + Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name, + Keychain.Key.USDT_PENDING_BACKUP_RESTORE.name, + ) + + private fun largeValueKeyStore() = + AndroidKeyStore(alias = Keychain.LARGE_VALUE_ALIAS, isStrongBoxPreferred = false, createsKeyOnInit = false) + + private suspend fun deleteLargeValueEntries() { + largeValueKeys.filter(sut::exists).forEach { sut.delete(it) } + } + @After fun tearDown() { db.close() diff --git a/app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt b/app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt index 46ee2deb97..2a920e52f5 100644 --- a/app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt +++ b/app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt @@ -12,8 +12,16 @@ import javax.crypto.spec.GCMParameterSpec class AndroidKeyStore( private val alias: String, private val password: CharArray? = null, + private val isStrongBoxPreferred: Boolean = true, + createsKeyOnInit: Boolean = true, ) { - private val type = "AndroidKeyStore" + companion object { + private const val TYPE = "AndroidKeyStore" + + private fun load() = KeyStore.getInstance(TYPE).apply { load(null) } + + fun containsAlias(alias: String): Boolean = load().containsAlias(alias) + } private val algorithm = KeyProperties.KEY_ALGORITHM_AES private val blockMode = KeyProperties.BLOCK_MODE_GCM @@ -22,26 +30,26 @@ class AndroidKeyStore( private val ivLength = 12 // GCM typically uses a 12-byte IV - private val keyStore by lazy { KeyStore.getInstance(type).apply { load(null) } } + private val keyStore get() = load() init { - generateKey() + if (createsKeyOnInit && !keyStore.containsAlias(alias)) generateKey() } - private fun generateKey(alias: String = this.alias) { - if (!keyStore.containsAlias(alias)) { - try { - val generator = KeyGenerator.getInstance(algorithm, type) - generator.init(buildSpec(isStrongboxBacked = true)) - generator.generateKey() - } catch (_: StrongBoxUnavailableException) { - val generator = KeyGenerator.getInstance(algorithm, type) - generator.init(buildSpec(isStrongboxBacked = false)) - generator.generateKey() - } + private fun generateKey() { + try { + generate(isStrongboxBacked = isStrongBoxPreferred) + } catch (_: StrongBoxUnavailableException) { + generate(isStrongboxBacked = false) } } + private fun generate(isStrongboxBacked: Boolean) { + val generator = KeyGenerator.getInstance(algorithm, TYPE) + generator.init(buildSpec(isStrongboxBacked)) + generator.generateKey() + } + private fun buildSpec(isStrongboxBacked: Boolean): KeyGenParameterSpec { val spec = KeyGenParameterSpec .Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) @@ -56,7 +64,7 @@ class AndroidKeyStore( @Synchronized fun encrypt(data: ByteArray): ByteArray { - val secretKey = keyStore.getKey(alias, password) as SecretKey + val secretKey = checkNotNull(keyStore.getKey(alias, password) as SecretKey?) { "Missing key '$alias'" } val cipher = Cipher.getInstance(transformation).apply { init(Cipher.ENCRYPT_MODE, secretKey) } val ciphertext = cipher.doFinal(data) @@ -70,7 +78,7 @@ class AndroidKeyStore( @Synchronized fun decrypt(data: ByteArray): ByteArray { - val secretKey = keyStore.getKey(alias, password) as SecretKey + val secretKey = checkNotNull(keyStore.getKey(alias, password) as SecretKey?) { "Missing key '$alias'" } // Extract the IV from the beginning of the blob val iv = data.sliceArray(0 until ivLength) @@ -85,12 +93,21 @@ class AndroidKeyStore( @Synchronized fun resetEncryptionKey() { - if (keyStore.containsAlias(alias)) { - keyStore.deleteEntry(alias) - } + keyStore.deleteEntry(alias) generateKey() } + /** Replaces the key if a lookup error reads it as missing, so call it only where no stored value needs the key. */ + @Synchronized + fun createKeyIfMissing() { + if (keyStore.getKey(alias, password) == null) generateKey() + } + + @Synchronized + fun deleteKey() { + keyStore.deleteEntry(alias) + } + @Synchronized fun containsAlias(): Boolean = keyStore.containsAlias(alias) } diff --git a/app/src/main/java/to/bitkit/data/keychain/Keychain.kt b/app/src/main/java/to/bitkit/data/keychain/Keychain.kt index b84d76390e..5f4c057578 100644 --- a/app/src/main/java/to/bitkit/data/keychain/Keychain.kt +++ b/app/src/main/java/to/bitkit/data/keychain/Keychain.kt @@ -1,6 +1,7 @@ package to.bitkit.data.keychain import android.content.Context +import androidx.annotation.VisibleForTesting import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit @@ -25,7 +26,8 @@ import javax.inject.Inject import javax.inject.Singleton import kotlin.coroutines.cancellation.CancellationException -private val Context.keychainDataStore: DataStore by preferencesDataStore( +@VisibleForTesting +internal val Context.keychainDataStore: DataStore by preferencesDataStore( name = "keychain" ) @@ -38,10 +40,46 @@ class Keychain @Inject constructor( companion object { private const val TAG = "Keychain" private const val CAUSE_CHAIN_DEPTH = 4 + + /** Marks values encrypted with the large-value key; base64 never contains ':'. */ + internal const val LARGE_VALUE_PREFIX = "tee:" + internal const val LARGE_VALUE_ALIAS = "keychain_large_values" } private val keyStore by lazy { AndroidKeyStore(alias = "keychain") } + private val largeValueKeyStore by lazy { + AndroidKeyStore(alias = LARGE_VALUE_ALIAS, isStrongBoxPreferred = false, createsKeyOnInit = false) + } + + private val largeValueKeys = setOf( + Key.PAYKIT_RECOVERY_BACKUP.name, + Key.PAYKIT_PENDING_BACKUP_RESTORE.name, + Key.USDT_PENDING_BACKUP_RESTORE.name, + ) + + private fun encrypt(key: String, value: ByteArray, prefs: Preferences): String { + if (key !in largeValueKeys) return keyStore.encrypt(value).toBase64() + val canCreateKey = !hasLargeValueEntries(prefs) + return runCatching { + if (canCreateKey) largeValueKeyStore.createKeyIfMissing() + LARGE_VALUE_PREFIX + largeValueKeyStore.encrypt(value).toBase64() + }.getOrElse { + if (it !is Exception || it is CancellationException) throw it + Logger.warn("Failed to encrypt '$key' with the large-value key, using the main key", it, context = TAG) + keyStore.encrypt(value).toBase64() + } + } + + private fun hasLargeValueEntries(prefs: Preferences): Boolean = + prefs.asMap().values.any { it is String && it.startsWith(LARGE_VALUE_PREFIX) } + + private fun decrypt(key: String, stored: String): ByteArray { + if (!stored.startsWith(LARGE_VALUE_PREFIX)) return keyStore.decrypt(stored.fromBase64()) + check(key in largeValueKeys) { "Unexpected large-value entry for '$key'" } + return largeValueKeyStore.decrypt(stored.removePrefix(LARGE_VALUE_PREFIX).fromBase64()) + } + @Suppress("MemberNameEqualsClassName") private val keychain = context.keychainDataStore @@ -63,9 +101,7 @@ class Keychain @Inject constructor( private fun loadIndexed(key: String, indexedKey: Preferences.Key): ByteArray? { try { - return snapshot[indexedKey]?.fromBase64()?.let { - keyStore.decrypt(it) - } + return snapshot[indexedKey]?.let { decrypt(key, it) } } catch (c: CancellationException) { throw c } catch (t: Throwable) { @@ -80,9 +116,7 @@ class Keychain @Inject constructor( internal inner class BlockingAccess { fun load(key: String): ByteArray? { try { - return blockingSnapshot[key.indexedBlocking]?.fromBase64()?.let { - keyStore.decrypt(it) - } + return blockingSnapshot[key.indexedBlocking]?.let { decrypt(key, it) } } catch (c: CancellationException) { throw c } catch (t: Throwable) { @@ -93,9 +127,9 @@ class Keychain @Inject constructor( fun upsert(key: String, value: ByteArray) { try { - val encryptedValue = keyStore.encrypt(value) + val encryptedValue = encrypt(key, value, blockingSnapshot) runBlocking { - keychain.edit { it[key.indexedBlocking] = encryptedValue.toBase64() } + keychain.edit { it[key.indexedBlocking] = encryptedValue } } } catch (c: CancellationException) { throw c @@ -125,8 +159,8 @@ class Keychain @Inject constructor( if (exists(key)) throw KeychainError.FailedToSaveAlreadyExists(key) try { - val encryptedValue = keyStore.encrypt(value) - keychain.edit { it[key.indexed] = encryptedValue.toBase64() } + val encryptedValue = encrypt(key, value, keychain.data.first()) + keychain.edit { it[key.indexed] = encryptedValue } } catch (c: CancellationException) { throw c } catch (t: Throwable) { @@ -145,8 +179,8 @@ class Keychain @Inject constructor( private suspend fun upsertIndexed(key: String, value: String, indexedKey: Preferences.Key) { try { - val encryptedValue = keyStore.encrypt(value.toByteArray()) - keychain.edit { it[indexedKey] = encryptedValue.toBase64() } + val encryptedValue = encrypt(key, value.toByteArray(), keychain.data.first()) + keychain.edit { it[indexedKey] = encryptedValue } } catch (c: CancellationException) { throw c } catch (t: Throwable) { @@ -182,6 +216,7 @@ class Keychain @Inject constructor( val keys = snapshot.asMap().keys keychain.edit { it.clear() } keyStore.resetEncryptionKey() + largeValueKeyStore.deleteKey() val count = keys.size Logger.info("Reset keychain encryption key and deleted all '$count' entries", context = TAG) @@ -223,7 +258,10 @@ class Keychain @Inject constructor( ) { if (!loadDiagnosticsEmitted.add(key)) return - val aliasPresent = probe { keyStore.containsAlias() } + val aliasPresent = probe { + val isLargeValue = snapshot[preferenceKey()]?.startsWith(LARGE_VALUE_PREFIX) == true + if (isLargeValue) AndroidKeyStore.containsAlias(LARGE_VALUE_ALIAS) else keyStore.containsAlias() + } val entryPresent = probe { snapshot.contains(preferenceKey()) } val walletIndex = probe { runBlocking { db.configDao().getAll().first() }.firstOrNull()?.walletIndex ?: 0L diff --git a/changelog.d/next/2227.fixed.md b/changelog.d/next/2227.fixed.md new file mode 100644 index 0000000000..c6065d1a65 --- /dev/null +++ b/changelog.d/next/2227.fixed.md @@ -0,0 +1 @@ +Restoring a wallet with a large Paykit backup takes seconds instead of minutes.