Cotton code
180 lines · 7.4 KB · KotlinRaw
package com.cottondb.android.platformimport android.content.Contextimport android.security.keystore.KeyGenParameterSpecimport android.security.keystore.KeyPropertiesimport com.cottondb.android.identity.DeviceKeySlotimport com.cottondb.android.identity.DeviceSeedRandomimport com.cottondb.android.identity.DeviceKeyStorageimport com.cottondb.android.identity.DeviceKeyWriteimport java.io.Fileimport java.io.FileOutputStreamimport java.nio.charset.StandardCharsetsimport java.nio.file.Filesimport java.nio.file.StandardCopyOptionimport java.security.KeyStoreimport java.security.SecureRandomimport javax.crypto.Cipherimport javax.crypto.KeyGeneratorimport javax.crypto.SecretKeyimport javax.crypto.spec.GCMParameterSpec/** * Android's one owner of the device seed. It keeps an AES-256-GCM ciphertext in no-backup * storage and its wrapping key in Android Keystore. Neither key uses biometrics: background * sync must be able to sign after the device has been unlocked once. */class DeviceKeyStore internal constructor(    private val keyAlias: String,    private val slot: File,) : DeviceKeyStorage {    constructor(context: Context) : this(KEY_ALIAS, File(context.noBackupFilesDir, SLOT_NAME))    override fun read(): DeviceKeySlot = synchronized(lock) { readLocked() }    override fun writeIfAbsent(secret: String): DeviceKeyWrite = synchronized(lock) {        when (val existing = readLocked()) {            DeviceKeySlot.Fresh -> writeFreshLocked(secret)            else -> DeviceKeyWrite.Existing(existing)        }    }    /**     * Erases this device's sealed seed and only its matching Android Keystore alias.     *     * The caller invokes this during an erase, on its IO dispatcher. A partial     * erase remains visible: if deleting either half fails, this throws and a later call retries     * the remaining half. It never silently mints a replacement over an unreadable identity.     */    fun forget() = synchronized(lock) {        try {            if (slot.exists()) {                check(slot.isFile) { "Identity slot is not a file" }                Files.delete(slot.toPath())            }            val store = keyStore()            if (store.containsAlias(keyAlias)) {                store.deleteEntry(keyAlias)                check(!store.containsAlias(keyAlias)) { "Identity wrapping key was not deleted" }            }        } catch (failure: Exception) {            throw IllegalStateException("Device identity could not be erased", failure)        }    }    private fun readLocked(): DeviceKeySlot {        return try {            val keyExists = hasWrappingKey()            if (!slot.exists()) {                return if (keyExists) DeviceKeySlot.WrappingKeyWithoutSlot else DeviceKeySlot.Fresh            }            if (!slot.isFile || !keyExists || slot.length() != ENVELOPE_BYTES.toLong()) {                return DeviceKeySlot.Unreadable("identity slot unavailable")            }            val plaintext = decrypt(requireWrappingKey(), slot.readBytes())            try {                DeviceKeySlot.Stored(plaintext.toString(StandardCharsets.UTF_8))            } finally {                plaintext.fill(0)            }        } catch (_: Exception) {            DeviceKeySlot.Unreadable("identity slot could not be opened")        }    }    private fun writeFreshLocked(secret: String): DeviceKeyWrite = try {        val bytes = secret.toByteArray(StandardCharsets.UTF_8)        try {            val encrypted = encrypt(getOrCreateWrappingKey(), bytes)            writeAtomically(encrypted)        } finally {            bytes.fill(0)        }        DeviceKeyWrite.Stored(secret)    } catch (_: Exception) {        // If key creation succeeded but the file did not, the next read explicitly refuses.        DeviceKeyWrite.Failed("identity slot could not be stored")    }    private fun encrypt(key: SecretKey, plaintext: ByteArray): ByteArray {        val cipher = Cipher.getInstance(TRANSFORMATION)        cipher.init(Cipher.ENCRYPT_MODE, key)        val iv = cipher.iv        require(iv.size == IV_BYTES)        val ciphertext = cipher.doFinal(plaintext)        return byteArrayOf(FORMAT_VERSION.toByte(), iv.size.toByte()) + iv + ciphertext    }    private fun decrypt(key: SecretKey, envelope: ByteArray): ByteArray {        require(envelope.size > HEADER_BYTES + GCM_TAG_BYTES)        require(envelope[0].toInt() == FORMAT_VERSION)        val ivSize = envelope[1].toInt() and 0xff        require(ivSize == IV_BYTES && envelope.size > HEADER_BYTES + ivSize + GCM_TAG_BYTES)        val iv = envelope.copyOfRange(HEADER_BYTES, HEADER_BYTES + ivSize)        val ciphertext = envelope.copyOfRange(HEADER_BYTES + ivSize, envelope.size)        val cipher = Cipher.getInstance(TRANSFORMATION)        cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(GCM_TAG_BITS, iv))        return cipher.doFinal(ciphertext)    }    private fun writeAtomically(contents: ByteArray) {        val parent = slot.parentFile ?: throw IllegalStateException("No identity directory")        if (!parent.exists() && !parent.mkdirs()) throw IllegalStateException("No identity directory")        if (slot.exists()) throw IllegalStateException("Identity slot appeared during creation")        val temporary = File.createTempFile("$SLOT_NAME.", ".tmp", parent)        try {            FileOutputStream(temporary).use { output ->                output.write(contents)                output.fd.sync()            }            Files.move(                temporary.toPath(),                slot.toPath(),                StandardCopyOption.ATOMIC_MOVE,            )        } finally {            temporary.delete()        }    }    private fun hasWrappingKey(): Boolean = keyStore().containsAlias(keyAlias)    private fun requireWrappingKey(): SecretKey =        (keyStore().getKey(keyAlias, null) as? SecretKey)            ?: throw IllegalStateException("Missing identity wrapping key")    private fun getOrCreateWrappingKey(): SecretKey {        if (hasWrappingKey()) return requireWrappingKey()        val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE)        generator.init(            KeyGenParameterSpec.Builder(keyAlias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)                .setKeySize(256)                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)                .setUserAuthenticationRequired(false)                .build(),        )        return generator.generateKey()    }    private fun keyStore(): KeyStore = KeyStore.getInstance(ANDROID_KEY_STORE).also { it.load(null) }    private companion object {        const val ANDROID_KEY_STORE = "AndroidKeyStore"        const val KEY_ALIAS = "com.cottondb.cotton.device-key.wrap.v1"        const val SLOT_NAME = "device-key.v1"        const val TRANSFORMATION = "AES/GCM/NoPadding"        const val FORMAT_VERSION = 1        const val HEADER_BYTES = 2        const val IV_BYTES = 12        const val GCM_TAG_BYTES = 16        const val GCM_TAG_BITS = 128        const val ENVELOPE_BYTES = HEADER_BYTES + IV_BYTES + 43 + GCM_TAG_BYTES        val lock = Any()    }}/** The production seed source; tests inject a deterministic [DeviceSeedRandom] instead. */class SecureDeviceSeedRandom : DeviceSeedRandom {    override fun nextSeed(): ByteArray = ByteArray(32).also(SecureRandom()::nextBytes)}