package com.cottondb.android.platform import android.content.Context import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyProperties import com.cottondb.android.identity.DeviceKeySlot import com.cottondb.android.identity.DeviceSeedRandom import com.cottondb.android.identity.DeviceKeyStorage import com.cottondb.android.identity.DeviceKeyWrite import java.io.File import java.io.FileOutputStream import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.StandardCopyOption import java.security.KeyStore import java.security.SecureRandom import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.SecretKey import 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) }