DuressConfig.kt

5.5 KB · raw

1package com.peachpasswords.vault23import android.content.Context4import androidx.security.crypto.EncryptedSharedPreferences5import androidx.security.crypto.MasterKey6import dagger.hilt.android.qualifiers.ApplicationContext7import org.json.JSONObject8import java.util.Base649import javax.inject.Inject10import javax.inject.Singleton1112/**13 * The action Peach takes when the duress password is entered at the lock screen.14 *15 *  - [DECOY]   open a separate empty/minimal "decoy" vault; the real vault stays16 *              sealed and hidden.17 *  - [DESTROY] irreversibly wipe the real vault, then drop to CreateVault.18 *19 * Persisted as the lowercase [wire] string so a future schema migration sees a20 * stable token, never an ordinal.21 */22enum class DuressAction(val wire: String) {23    DECOY("decoy"),24    DESTROY("destroy");2526    companion object {27        fun fromWire(s: String?): DuressAction =28            entries.firstOrNull { it.wire == s } ?: DECOY29    }30}3132/**33 * What [DuressConfigStore.verify] reports for an entered lock-screen password.34 * [None] means "not the duress password" — the caller falls through to the35 * normal vault unlock path. The verifier never decides policy; it only matches.36 */37sealed interface DuressMatch {38    data object None : DuressMatch39    data class Match(val action: DuressAction) : DuressMatch40}4142/**43 * Stores the duress password as an Argon2id hash (never plaintext) plus the44 * selected [DuressAction], in a dedicated EncryptedSharedPreferences file under45 * the single key "duress_config".46 *47 * The hash is the Argon2id output of the duress password over a freshly-minted48 * 16-byte salt, using the SAME parameters as the vault KDF ([VaultCrypto]). The49 * salt is stored alongside the hash (base64) — it is not secret; it only forces50 * the verifier to re-derive rather than compare a precomputed digest. This51 * mirrors the at-rest model of slot A, whose salt is likewise in the clear.52 *53 * Why a separate prefs file (not the slot-A payload): the duress password must be54 * verifiable BEFORE the real vault is unlocked. It cannot live inside the55 * AES-GCM blob that only the real master password can open. The license store56 * uses the same EncryptedSharedPreferences pattern (see LicenseRepository).57 */58@Singleton59class DuressConfigStore @Inject constructor(60    @ApplicationContext context: Context,61) {62    private val masterKey = MasterKey.Builder(context)63        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)64        .build()6566    private val prefs = EncryptedSharedPreferences.create(67        context,68        PREFS_FILE,69        masterKey,70        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,71        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,72    )7374    fun isConfigured(): Boolean = prefs.contains(KEY_DURESS_CONFIG)7576    fun storedAction(): DuressAction? =77        load()?.let { DuressAction.fromWire(it.optString(FIELD_ACTION)) }7879    /**80     * Hash [password] with Argon2id over a fresh salt and persist {salt, hash,81     * action}. Overwrites any prior duress config. Returns false if the value82     * could not be committed.83     */84    fun save(password: String, action: DuressAction): Boolean {85        val salt = VaultCrypto.generateSalt()86        val hash = VaultCrypto.deriveKey(password, salt)87        val json = JSONObject().apply {88            put(FIELD_VERSION, 1)89            put(FIELD_SALT, b64(salt))90            put(FIELD_HASH, b64(hash))91            put(FIELD_ACTION, action.wire)92        }93        VaultCrypto.zero(hash)94        return prefs.edit().putString(KEY_DURESS_CONFIG, json.toString()).commit()95    }9697    fun clear(): Boolean = prefs.edit().remove(KEY_DURESS_CONFIG).commit()9899    /**100     * Check [password] against the stored duress hash. Re-derives the Argon2id101     * key over the stored salt and constant-time-compares against the stored102     * hash. Returns [DuressMatch.None] when no config exists or the password is103     * not the duress password.104     */105    fun verify(password: String): DuressMatch {106        val json = load() ?: return DuressMatch.None107        val salt = runCatching { unb64(json.getString(FIELD_SALT)) }.getOrNull()108            ?: return DuressMatch.None109        val expected = runCatching { unb64(json.getString(FIELD_HASH)) }.getOrNull()110            ?: return DuressMatch.None111        val derived = VaultCrypto.deriveKey(password, salt)112        val matches = constantTimeEquals(derived, expected)113        VaultCrypto.zero(derived)114        return if (matches) {115            DuressMatch.Match(DuressAction.fromWire(json.optString(FIELD_ACTION)))116        } else {117            DuressMatch.None118        }119    }120121    private fun load(): JSONObject? =122        prefs.getString(KEY_DURESS_CONFIG, null)?.let { runCatching { JSONObject(it) }.getOrNull() }123124    private fun constantTimeEquals(a: ByteArray, b: ByteArray): Boolean {125        if (a.size != b.size) return false126        var diff = 0127        for (i in a.indices) diff = diff or (a[i].toInt() xor b[i].toInt())128        return diff == 0129    }130131    private fun b64(bytes: ByteArray): String =132        Base64.getEncoder().withoutPadding().encodeToString(bytes)133134    private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)135136    companion object {137        private const val PREFS_FILE = "peach_duress_prefs"138        private const val KEY_DURESS_CONFIG = "duress_config"139        private const val FIELD_VERSION = "v"140        private const val FIELD_SALT = "salt"141        private const val FIELD_HASH = "hash"142        private const val FIELD_ACTION = "action"143    }144}