Cotton code
323 lines · 13.2 KB · KotlinRaw
package com.cottondb.android.platformimport android.content.Contextimport android.os.Buildimport android.security.keystore.KeyGenParameterSpecimport android.security.keystore.KeyPropertiesimport android.util.Base64import java.io.Fileimport java.io.FileOutputStreamimport java.nio.charset.StandardCharsetsimport java.nio.file.Filesimport java.nio.file.StandardCopyOptionimport java.security.KeyPairGeneratorimport java.security.KeyStoreimport java.security.PrivateKeyimport java.security.PublicKeyimport java.security.SecureRandomimport java.security.spec.MGF1ParameterSpecimport javax.crypto.Cipherimport javax.crypto.spec.OAEPParameterSpecimport javax.crypto.spec.PSourceimport org.bouncycastle.math.ec.rfc7748.X25519/** * This device's X25519 vault key. * * The 32-byte scalar is encrypted with an Android Keystore RSA key whose private * operation requires a BiometricPrompt CryptoObject. Its public * X25519 half is cached separately because joining and publishing must never prompt. * The Keystore RSA public key encrypts without authentication, so minting has the same * no-prompt property as adding iOS's presence-protected Keychain item. */class VaultKeyring internal constructor(    private val keyAlias: String,    private val privateSlot: File,    private val publicSlot: File,) {    constructor(context: Context) : this(        KEY_ALIAS,        File(context.noBackupFilesDir, PRIVATE_SLOT_NAME),        File(context.noBackupFilesDir, PUBLIC_SLOT_NAME),    )    /**     * Returns this device's public vault key, minting a private scalar if needed.     *     * This does not read the protected key and therefore never asks for user presence.     * Any partial previous state is named as an error. Minting over it could orphan a     * server wrap that may still be useful.     */    fun publicKey(): String? = synchronized(lock) {        when (storageState()) {            StorageState.Complete -> return@synchronized requireCachedPublicKey()            StorageState.Incomplete -> throw VaultKeyException("The vault key storage is incomplete.")            StorageState.Fresh -> Unit        }        val scalar = ByteArray(KEY_BYTES).also(SecureRandom()::nextBytes)        try {            val public = publicOf(scalar)            val sealed = encrypt(requirePublicWrappingKey(), scalar)            writeAtomically(privateSlot, sealed)            writeAtomically(publicSlot, public.toByteArray(StandardCharsets.US_ASCII))            public        } catch (failure: Exception) {            throw VaultKeyException("The vault key could not be stored.", failure)        } finally {            scalar.fill(0)        }    }    /** Returns the cached public half without minting or asking for user presence. */    fun cachedPublicKey(): String? = synchronized(lock) {        when (storageState()) {            StorageState.Fresh -> null            StorageState.Incomplete -> throw VaultKeyException("The vault key storage is incomplete.")            StorageState.Complete -> requireCachedPublicKey()        }    }    /**     * Creates the decrypt cipher that the UI must present to BiometricPrompt.     * Call [unlock] only after its success callback returns the same CryptoObject cipher.     */    fun prepareUnlock(): VaultUnlockRequest = synchronized(lock) {        val sealed = readSealedSlot()        val cipher = Cipher.getInstance(RSA_TRANSFORMATION)        cipher.init(Cipher.DECRYPT_MODE, requirePrivateWrappingKey(), OAEP_SPEC)        VaultUnlockRequest(cipher, sealed)    }    /**     * Opens the private X25519 scalar using the authenticated cipher from [prepareUnlock].     *     * It repairs the public cache while the scalar is in hand. Authentication and storage     * failures preserve every artifact: only a deliberate erase may forget this key.     */    fun unlock(request: VaultUnlockRequest): String = synchronized(lock) {        if (!request.claim()) throw VaultKeyException("This vault unlock request was already used.")        val current = readSealedSlot()        if (!current.contentEquals(request.sealed)) {            throw VaultKeyException("The vault key changed while it was being unlocked.")        }        val scalar = try {            request.cipher.doFinal(current)        } catch (failure: Exception) {            throw VaultKeyException("The vault key could not be opened.", failure)        }        try {            if (scalar.size != KEY_BYTES) {                throw VaultKeyException("The vault key is not a 32-byte X25519 scalar.")            }            val public = publicOf(scalar)            writeAtomically(publicSlot, public.toByteArray(StandardCharsets.US_ASCII))            return encode(scalar)        } catch (failure: VaultKeyException) {            throw failure        } catch (failure: Exception) {            throw VaultKeyException("The vault public key could not be stored.", failure)        } finally {            scalar.fill(0)        }    }    /**     * Deliberately removes only this vault's sealed scalar, public cache and wrapping alias.     * No private-key operation is needed, so it is safe and idempotent during an erase.     */    fun forget() = synchronized(lock) { forgetLocked() }    private fun readCachedPublicKey(): String? {        if (!publicSlot.isFile) return null        val candidate = try {            publicSlot.readText(StandardCharsets.US_ASCII)        } catch (failure: Exception) {            throw VaultKeyException("The vault public-key cache could not be read.", failure)        }        return candidate.takeIf(::isCanonicalEncodedKey)    }    private fun requireCachedPublicKey(): String = readCachedPublicKey()        ?: throw VaultKeyException("The vault public-key cache is unreadable.")    private fun readSealedSlot(): ByteArray {        if (!privateSlot.isFile) throw VaultKeyException("This device has no vault key yet.")        val sealed = try {            privateSlot.readBytes()        } catch (failure: Exception) {            throw VaultKeyException("The vault key could not be read.", failure)        }        if (sealed.size != SEALED_BYTES || sealed.firstOrNull()?.toInt() != FORMAT_VERSION) {            throw VaultKeyException("The vault key is unreadable.")        }        return sealed.copyOfRange(1, sealed.size)    }    private fun encrypt(publicKey: PublicKey, scalar: ByteArray): ByteArray {        val cipher = Cipher.getInstance(RSA_TRANSFORMATION)        cipher.init(Cipher.ENCRYPT_MODE, publicKey, OAEP_SPEC)        val ciphertext = cipher.doFinal(scalar)        check(ciphertext.size == RSA_BYTES) { "Unexpected RSA ciphertext size" }        return byteArrayOf(FORMAT_VERSION.toByte()) + ciphertext    }    private fun publicOf(scalar: ByteArray): String {        val public = ByteArray(KEY_BYTES)        X25519.generatePublicKey(scalar, 0, public, 0)        return try {            encode(public)        } finally {            public.fill(0)        }    }    private fun requirePublicWrappingKey(): PublicKey {        val store = keyStore()        if (!store.containsAlias(keyAlias)) createWrappingKey()        return store.getCertificate(keyAlias)?.publicKey            ?: throw VaultKeyException("The vault wrapping key is unavailable.")    }    private fun requirePrivateWrappingKey(): PrivateKey =        (keyStore().getKey(keyAlias, null) as? PrivateKey)            ?: throw VaultKeyException("The vault wrapping key is unavailable.")    private fun createWrappingKey() {        val generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, ANDROID_KEY_STORE)        val parameters =            KeyGenParameterSpec.Builder(                keyAlias,                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,            )                .setKeySize(RSA_BITS)                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)                .setDigests(KeyProperties.DIGEST_SHA256)                .setUserAuthenticationRequired(true)                // This is Android's counterpart to iOS `userPresence`, not                // `biometryCurrentSet`: adding a fingerprint must not strand                // an otherwise recoverable vault key.                .setInvalidatedByBiometricEnrollment(false)        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {            // API 30 introduced a per-use policy that binds the returned            // CryptoObject to either a Class 3 biometric or the lock-screen            // credential. A zero timeout means every private-key operation.            parameters.setUserAuthenticationParameters(                0,                KeyProperties.AUTH_BIOMETRIC_STRONG or KeyProperties.AUTH_DEVICE_CREDENTIAL,            )        } else {            // Pre-30 Android cannot attach a CryptoObject to device-credential            // fallback. Keep the honest biometric-only, auth-per-use policy;            // a Keyguard credential time window would weaken every reveal.            parameters.setUserAuthenticationValidityDurationSeconds(-1)        }        generator.initialize(            parameters.build(),        )        generator.generateKeyPair()    }    private fun forgetLocked() {        try {            deleteIfPresent(privateSlot)            deleteIfPresent(publicSlot)            val store = keyStore()            if (store.containsAlias(keyAlias)) {                store.deleteEntry(keyAlias)                check(!store.containsAlias(keyAlias)) { "Vault wrapping key was not deleted" }            }        } catch (failure: VaultKeyException) {            throw failure        } catch (failure: Exception) {            throw VaultKeyException("The vault key could not be erased.", failure)        }    }    private fun deleteIfPresent(file: File) {        if (!file.exists()) return        check(file.isFile) { "Vault key slot is not a file" }        Files.delete(file.toPath())    }    private fun writeAtomically(target: File, contents: ByteArray) {        val parent = target.parentFile ?: throw VaultKeyException("No vault-key directory.")        if (!parent.exists() && !parent.mkdirs()) throw VaultKeyException("No vault-key directory.")        val temporary = File.createTempFile("${target.name}.", ".tmp", parent)        try {            FileOutputStream(temporary).use { output ->                output.write(contents)                output.fd.sync()            }            Files.move(temporary.toPath(), target.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)        } finally {            temporary.delete()        }    }    private fun keyStore(): KeyStore = KeyStore.getInstance(ANDROID_KEY_STORE).also { it.load(null) }    private fun storageState(): StorageState {        val privatePresent = privateSlot.exists()        val publicPresent = publicSlot.exists()        val wrappingPresent = keyStore().containsAlias(keyAlias)        return when {            !privatePresent && !publicPresent && !wrappingPresent -> StorageState.Fresh            privateSlot.isFile && publicSlot.isFile && wrappingPresent -> StorageState.Complete            else -> StorageState.Incomplete        }    }    private enum class StorageState { Fresh, Complete, Incomplete }    companion object {        private const val ANDROID_KEY_STORE = "AndroidKeyStore"        private const val KEY_ALIAS = "com.cottondb.cotton.vault-key.wrap.v1"        private const val PRIVATE_SLOT_NAME = "vault-key.v1"        private const val PUBLIC_SLOT_NAME = "vault-public-key.v1"        private const val FORMAT_VERSION = 1        private const val KEY_BYTES = 32        private const val RSA_BITS = 2048        private const val RSA_BYTES = RSA_BITS / 8        private const val SEALED_BYTES = RSA_BYTES + 1        private const val RSA_TRANSFORMATION = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"        private val OAEP_SPEC = OAEPParameterSpec(            "SHA-256",            "MGF1",            // Android Keystore supports this explicit portable OAEP combination from API 28.            // MGF1 SHA-256 cannot be required until API 35.            MGF1ParameterSpec.SHA1,            PSource.PSpecified.DEFAULT,        )        private val BASE64_FLAGS = Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP        private val ENCODED_KEY = Regex("[A-Za-z0-9_-]{43}")        private val lock = Any()        private fun encode(bytes: ByteArray): String = Base64.encodeToString(bytes, BASE64_FLAGS)        private fun isCanonicalEncodedKey(value: String): Boolean {            if (!ENCODED_KEY.matches(value)) return false            val decoded = runCatching { Base64.decode(value, BASE64_FLAGS) }.getOrNull() ?: return false            return try {                decoded.size == KEY_BYTES && encode(decoded) == value            } finally {                decoded.fill(0)            }        }    }}/** The CryptoObject cipher the UI passes to BiometricPrompt, then back to [VaultKeyring.unlock]. */class VaultUnlockRequest internal constructor(    internal val cipher: Cipher,    internal val sealed: ByteArray,) {    private var used = false    internal fun claim(): Boolean = synchronized(this) {        if (used) false else true.also { used = true }    }}class VaultKeyException(message: String, cause: Throwable? = null) : IllegalStateException(message, cause)