c13f308ba9b0
fix: MF-6 duress slot-B under duress passphrase — slot B keyed by passphrase (no sentinel, no stored hash), dual-slot constant-time unlock, DuressConfigStore reduced to {enabled,action}, collision guard vs real password, ProtectionBody passphrase form; 5 DuressSlotB tests (v2.2.2)
- time
- 2026-06-09 18:23 UTC · 5 months ago
- machine
- koh2
- agent
- claude-opus-4-8
- session
- audit fixes duress slot-b
- parent
- 1340d93f5f95
↓ peach-android-c13f308b.tar.gzatlas at this save
files changed6 files
app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt+18 −17app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+3 −3app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+7 −1app/src/main/java/com/peachpasswords/vault/DuressConfig.kt+19 −74app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+83 −37app/src/test/java/com/peachpasswords/vault/DuressSlotBTest.kt+86 −0app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt+18 −17
@@ -9,7 +9,6 @@99 import com.peachpasswords.ui.security.scorePassword1010 import com.peachpasswords.vault.DuressAction1111 import com.peachpasswords.vault.DuressConfigStore12-import com.peachpasswords.vault.DuressMatch1312 import com.peachpasswords.vault.UnlockResult1413 import com.peachpasswords.vault.VaultCrypto1514 import com.peachpasswords.vault.VaultLockTimer@@ -58,22 +57,22 @@5857 if (password.isBlank() || _state.value.loading) return5958 _state.update { it.copy(loading = true, error = null) }6059 viewModelScope.launch {61- // Derive the duress hash and slot A CONCURRENTLY so the wall-clock time to62- // reject/accept does not reveal whether the entered password was the real63- // password, the duress password, or simply wrong (MF-5, mirrors browser64- // DUR-002). Both Argon2id derivations always run to completion; the branch65- // happens only after both finish. The slot-A derivation is non-committing66- // (no mutex, no session mutation) so it is safe to discard when duress wins.67- val (duressMatch, slotA) = withContext(Dispatchers.Default) {68- val duressDeferred = async { duress.verify(password) }60+ // Derive slot A and the duress slot (slot B) CONCURRENTLY so the wall-clock61+ // time to reject/accept never reveals whether the entered password was the62+ // real password, the duress passphrase, or simply wrong (MF-5/MF-6, mirrors63+ // browser DUR-002). Both Argon2id derivations run to completion; the branch64+ // happens only after both finish. Each derivation is non-committing (no65+ // mutex, no session mutation) so the loser is simply discarded.66+ val (duressUnlock, slotA) = withContext(Dispatchers.Default) {67+ val duressDeferred = async { if (duress.isConfigured()) vault.tryUnlockDuress(password) else null }6968 val slotADeferred = async { vault.tryUnlockSlotA(password) }7069 duressDeferred.await() to slotADeferred.await()7170 }7271 when {73- // Duress takes precedence: a matching duress password never reaches the real vault.74- duressMatch is DuressMatch.Match -> {72+ // Duress takes precedence: the duress passphrase never reaches the real vault.73+ duressUnlock != null -> {7574 slotA?.let(vault::discardSlotAUnlock)76- handleDuress(duressMatch.action)75+ handleDuress(duressUnlock)7776 }7877 slotA != null -> {7978 vault.commitSlotAUnlock(slotA)@@ -88,18 +87,20 @@8887 }8988 9089 /**91- * Carry out the configured duress action. Both paths look like an ordinary92- * successful (decoy) or fresh-install (destroy) unlock to a coercer — no error.90+ * Carry out the configured duress action against an already-derived slot-B unlock.91+ * Both paths look like an ordinary successful (decoy) or fresh-install (destroy)92+ * unlock to a coercer — no error, no hint that a duress passphrase was used.9393 */94- private suspend fun handleDuress(action: DuressAction) {95- when (action) {96- DuressAction.DECOY -> when (vault.unlockDecoy()) {94+ private suspend fun handleDuress(duressUnlock: VaultRepository.DuressUnlock) {95+ when (duress.action()) {96+ DuressAction.DECOY -> when (vault.commitDuressUnlock(duressUnlock)) {9797 is UnlockResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true) } }9898 else -> _state.update {9999 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)100100 }101101 }102102 DuressAction.DESTROY -> {103+ vault.discardDuressUnlock(duressUnlock)103104 vault.destroyVault()104105 duress.clear()105106 _state.update { it.copy(loading = false, hasVault = false, duressDestroyed = true) }app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+3 −3
@@ -727,8 +727,8 @@727727 728728 AnimatedVisibility(enabled) {729729 Column(Modifier.fillMaxWidth().padding(top = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {730- PwField("DURESS PASSWORD", password, fg) { password = it; error = null }731- PwField("CONFIRM DURESS PASSWORD", confirm, fg) { confirm = it; error = null }730+ PwField("DURESS PASSPHRASE", password, fg) { password = it; error = null }731+ PwField("CONFIRM DURESS PASSPHRASE", confirm, fg) { confirm = it; error = null }732732 733733 Text(734734 "When your duress password is entered at the lock screen, Peach will:",@@ -754,7 +754,7 @@754754 if (vm.saveDuress(password, action)) {755755 password = ""; confirm = ""; enabled = false756756 } else {757- error = "Couldn't save duress password"757+ error = "Couldn't save — the duress passphrase must differ from your real password"758758 }759759 }760760 }app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+7 −1
@@ -33,13 +33,19 @@3333 private val _duressConfigured = MutableStateFlow(duress.isConfigured())3434 val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()3535 36+ /**37+ * MF-6: seal a decoy vault (slot B) under the duress passphrase, then record the38+ * action policy. The passphrase keys slot B directly and is never stored as a hash.39+ */3640 suspend fun saveDuress(password: String, action: com.peachpasswords.vault.DuressAction): Boolean {37- val ok = duress.save(password, action)41+ if (!vault.setDuressPassphrase(password)) return false42+ val ok = duress.enable(action)3843 if (ok) _duressConfigured.value = true3944 return ok4045 }4146 4247 fun disableDuress() {48+ viewModelScope.launch { vault.clearDuress() }4349 duress.clear()4450 _duressConfigured.value = false4551 }app/src/main/java/com/peachpasswords/vault/DuressConfig.kt+19 −74
@@ -5,12 +5,11 @@55 import androidx.security.crypto.MasterKey66 import dagger.hilt.android.qualifiers.ApplicationContext77 import org.json.JSONObject8-import java.util.Base6498 import javax.inject.Inject109 import javax.inject.Singleton1110 1211 /**13- * The action Peach takes when the duress password is entered at the lock screen.12+ * The action Peach takes when the duress passphrase is entered at the lock screen.1413 *1514 * - [DECOY] open a separate empty/minimal "decoy" vault; the real vault stays1615 * sealed and hidden.@@ -30,30 +29,21 @@3029 }3130 3231 /**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- */37-sealed interface DuressMatch {38- data object None : DuressMatch39- data class Match(val action: DuressAction) : DuressMatch40-}41-42-/**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".32+ * Stores only the duress *policy* — whether duress is enabled and which33+ * [DuressAction] to take — in a dedicated EncryptedSharedPreferences file.4634 *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.35+ * MF-6: the duress passphrase is NOT stored here (no hash, no salt). Instead it36+ * keys a real second vault — slot B (the decoy slot in [VaultStorage]) — sealed37+ * with Argon2id under the passphrase itself, exactly like the real slot A. The38+ * lock screen tries to decrypt slot B with whatever password is typed; success39+ * means the duress passphrase was entered. This matches the browser's40+ * slot-B-under-duress-passphrase model and removes the old sentinel-keyed decoy41+ * that was reachable without any secret.5242 *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).43+ * This store therefore holds no secret material — only the action token — but44+ * remains in EncryptedSharedPreferences for parity with the license store and so45+ * the action is not trivially readable. The slot-B ciphertext is the actual46+ * gate; this is policy metadata read only after that gate opens.5747 */5848 @Singleton5949 class DuressConfigStore @Inject constructor(@@ -73,72 +63,27 @@7363 7464 fun isConfigured(): Boolean = prefs.contains(KEY_DURESS_CONFIG)7565 76- fun storedAction(): DuressAction? =77- load()?.let { DuressAction.fromWire(it.optString(FIELD_ACTION)) }66+ /** The configured action, or [DuressAction.DECOY] when none is set. */67+ fun action(): DuressAction = load()?.let { DuressAction.fromWire(it.optString(FIELD_ACTION)) } ?: DuressAction.DECOY7868 79- /**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)69+ /** Record that duress is enabled with [action]. The passphrase lives in slot B, never here. */70+ fun enable(action: DuressAction): Boolean {8771 val json = JSONObject().apply {88- put(FIELD_VERSION, 1)89- put(FIELD_SALT, b64(salt))90- put(FIELD_HASH, b64(hash))72+ put(FIELD_VERSION, 2)9173 put(FIELD_ACTION, action.wire)9274 }93- VaultCrypto.zero(hash)9475 return prefs.edit().putString(KEY_DURESS_CONFIG, json.toString()).commit()9576 }9677 9778 fun clear(): Boolean = prefs.edit().remove(KEY_DURESS_CONFIG).commit()9879 99- /**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- }120-12180 private fun load(): JSONObject? =12281 prefs.getString(KEY_DURESS_CONFIG, null)?.let { runCatching { JSONObject(it) }.getOrNull() }12382 124- 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- }130-131- private fun b64(bytes: ByteArray): String =132- Base64.getEncoder().withoutPadding().encodeToString(bytes)133-134- private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)135-13683 companion object {13784 private const val PREFS_FILE = "peach_duress_prefs"13885 private const val KEY_DURESS_CONFIG = "duress_config"13986 private const val FIELD_VERSION = "v"140- private const val FIELD_SALT = "salt"141- private const val FIELD_HASH = "hash"14287 private const val FIELD_ACTION = "action"14388 }14489 }app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+83 −37
@@ -17,9 +17,6 @@1717 /** Cap on retained past passwords per entry. Mirrors the browser PASSWORD_HISTORY_MAX. */1818 private const val PASSWORD_HISTORY_MAX = 501919 20-/** Fixed in-app key material for the decoy vault — holds nothing secret by design. */21-private const val DECOY_SENTINEL = "peach_decoy_v1"22-2320 sealed interface UnlockResult {2421 data object Success : UnlockResult2522 data object WrongPassword : UnlockResult@@ -203,43 +200,48 @@203200 /** Zero a derived [SlotAUnlock] that will not be adopted. */204201 fun discardSlotAUnlock(unlock: SlotAUnlock) = VaultCrypto.zero(unlock.key)205202 203+ // ---- Duress slot B (MF-6) ---------------------------------------------204+206205 /**207- * Unlock into the decoy (duress) vault. Creates an empty decoy on first use,208- * sealed under a fixed in-app sentinel key with its own salt. The real slot A209- * is never read, so the real vault stays hidden. Edits during a decoy session210- * persist to the decoy slot only (see [persistSlotA]).206+ * A duress-slot (slot B) unlock derived but not yet adopted. Holds the live key207+ * and decoded decoy payload so it can be derived concurrently with slot A and208+ * only committed if the duress passphrase was the one entered (MF-5/MF-6).211209 */212- suspend fun unlockDecoy(): UnlockResult = mutex.withLock {210+ class DuressUnlock internal constructor(211+ internal val key: ByteArray,212+ internal val payload: VaultPayload,213+ )214+215+ /**216+ * Try to decrypt the duress slot (slot B) with [password] WITHOUT mutating the217+ * session. Success means the entered password is the duress passphrase that keys218+ * slot B — indistinguishable from the real slot A at the lock screen. Pure219+ * computation (no mutex), safe to run concurrently with [tryUnlockSlotA].220+ * Returns null when no duress slot exists or the password is not the duress one.221+ */222+ fun tryUnlockDuress(password: String): DuressUnlock? {223+ val slot = store.loadDecoySlot() ?: return null224+ val key = VaultCrypto.deriveKey(password, unb64(slot.salt))213225 return try {214- val existing = store.loadDecoySlot()215- if (existing == null) {216- val salt = VaultCrypto.generateSalt()217- val key = VaultCrypto.deriveKey(DECOY_SENTINEL, salt)218- entryList = mutableListOf()219- duressConfigured = false220- recoveryWordHash = null221- recoveryWordsSet = false222- rootKey = VaultCrypto.generateRootKey()223- derivedKey = key224- decoyMode = true225- val plaintext = VaultCodec.encode(currentPayload())226- val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))227- if (!store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob)))228- return UnlockResult.Error("storage_write_failed")229- } else {230- val key = VaultCrypto.deriveKey(DECOY_SENTINEL, unb64(existing.salt))231- val payload = VaultCodec.decode(232- VaultCrypto.decrypt(unb64(existing.blob), key, VaultCrypto.AAD_SLOT_A),233- )234- derivedKey = key235- decoyMode = true236- entryList = payload.entries.toMutableList()237- duressConfigured = false238- recoveryWordHash = payload.recoveryWordHash239- recoveryWordsSet = payload.recoveryWordsSet240- rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)241- else VaultCrypto.generateRootKey()242- }226+ val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A))227+ DuressUnlock(key, payload)228+ } catch (_: Exception) {229+ VaultCrypto.zero(key)230+ null231+ }232+ }233+234+ /** Adopt a derived [DuressUnlock] as a live decoy session (edits persist to slot B only). */235+ suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {236+ return try {237+ derivedKey = unlock.key238+ decoyMode = true239+ entryList = unlock.payload.entries.toMutableList()240+ duressConfigured = false241+ recoveryWordHash = unlock.payload.recoveryWordHash242+ recoveryWordsSet = unlock.payload.recoveryWordsSet243+ rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)244+ else VaultCrypto.generateRootKey()243245 _settings.value = store.loadSettings()244246 publish()245247 _isUnlocked.value = true@@ -247,6 +249,50 @@247249 } catch (e: Exception) {248250 UnlockResult.Error(e.message ?: "decoy_unlock_failed")249251 }252+ }253+254+ /** Zero a derived [DuressUnlock] that will not be adopted. */255+ fun discardDuressUnlock(unlock: DuressUnlock) = VaultCrypto.zero(unlock.key)256+257+ /**258+ * Configure the duress vault (MF-6): seal a fresh, empty decoy payload under an259+ * Argon2id key derived from [duressPassphrase] (fresh salt) into slot B. The260+ * passphrase is never stored — only its ability to decrypt slot B proves it.261+ * Requires the real vault to be unlocked and not itself a decoy session.262+ */263+ suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {264+ if (derivedKey == null || decoyMode) return false265+ // Reject a duress passphrase that also opens the real vault: it would make the266+ // lock screen ambiguous (both slots would decrypt for the same input).267+ tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }268+ return try {269+ val salt = VaultCrypto.generateSalt()270+ val key = VaultCrypto.deriveKey(duressPassphrase, salt)271+ // An empty decoy vault with its own fresh sync root key — nothing real leaks.272+ val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = b64(VaultCrypto.generateRootKey()))273+ val plaintext = VaultCodec.encode(decoyPayload)274+ val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))275+ VaultCrypto.zero(key)276+ VaultCrypto.zero(plaintext)277+ val ok = store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))278+ if (ok) {279+ duressConfigured = true280+ runCatching { persistSlotA(bumpVersion = false) }281+ }282+ ok283+ } catch (_: Exception) {284+ false285+ }286+ }287+288+ /** Tear down the duress vault: drop slot B and the duress flag on the real payload. */289+ suspend fun clearDuress(): Boolean = mutex.withLock {290+ store.clearDecoySlot()291+ if (derivedKey != null && !decoyMode) {292+ duressConfigured = false293+ runCatching { persistSlotA(bumpVersion = false) }294+ }295+ true250296 }251297 252298 /** Unlock with an already-derived AES-256 key (biometric path). */app/src/test/java/com/peachpasswords/vault/DuressSlotBTest.kt+86 −0
@@ -0,0 +1,86 @@1+package com.peachpasswords.vault2+3+import kotlinx.coroutines.runBlocking4+import org.junit.Assert.assertEquals5+import org.junit.Assert.assertFalse6+import org.junit.Assert.assertNotNull7+import org.junit.Assert.assertNull8+import org.junit.Assert.assertTrue9+import org.junit.Test10+11+/** In-memory [VaultStorage] including a decoy (slot B) slot, for the MF-6 duress model. */12+private class DuressFakeStorage : VaultStorage {13+ private var slotA: StoredVault? = null14+ private var slotB: String? = null15+ private var ver: Long = 016+ private var settings = VaultSettings()17+ override fun loadSlotA() = slotA18+ override fun hasVault() = slotA != null19+ override fun writeSlotA(slot: StoredVault): Boolean { slotA = slot; return true }20+ override fun writeSlotB(blobBase64: String): Boolean { slotB = blobBase64; return true }21+ private var decoy: StoredVault? = null22+ override fun loadDecoySlot() = decoy23+ override fun writeDecoySlot(slot: StoredVault): Boolean { decoy = slot; return true }24+ override fun hasDecoySlot() = decoy != null25+ override fun clearDecoySlot() { decoy = null }26+ override fun version() = ver27+ override fun stampLocalMutation(): Long { ver = maxOf(System.currentTimeMillis(), ver + 1); return ver }28+ override fun loadSettings() = settings29+ override fun writeSettings(s: VaultSettings): Boolean { settings = s; return true }30+ override fun clearVault() { slotA = null; slotB = null; ver = 0; settings = VaultSettings() }31+}32+33+/**34+ * MF-6: the duress passphrase keys a real second vault (slot B), sealed exactly35+ * like slot A. At the lock screen, both slots are tried and the outcome is36+ * invisible from outside — no sentinel, no separate hash.37+ */38+class DuressSlotBTest {39+ private val real = "the-real-password-123"40+ private val duressPass = "open-the-decoy-456"41+42+ private fun configuredRepo(): VaultRepository = runBlocking {43+ val repo = VaultRepository(DuressFakeStorage())44+ repo.createVault(real)45+ repo.addEntry(VaultEntry(id = "", title = "Secret", type = "login", password = "pw", createdAt = 0, modifiedAt = 0))46+ assertTrue("duress passphrase sealed into slot B", repo.setDuressPassphrase(duressPass))47+ repo.lock()48+ repo49+ }50+51+ @Test fun real_password_opens_slot_a_only() = runBlocking {52+ val repo = configuredRepo()53+ assertNotNull("real password opens slot A", repo.tryUnlockSlotA(real))54+ assertNull("real password does NOT open the duress slot", repo.tryUnlockDuress(real))55+ }56+57+ @Test fun duress_passphrase_opens_decoy_only() = runBlocking {58+ val repo = configuredRepo()59+ assertNull("duress passphrase does NOT open slot A", repo.tryUnlockSlotA(duressPass))60+ val duress = repo.tryUnlockDuress(duressPass)61+ assertNotNull("duress passphrase opens the duress slot", duress)62+ assertEquals(UnlockResult.Success, repo.commitDuressUnlock(duress!!))63+ assertTrue(repo.isUnlocked.value)64+ assertEquals("decoy vault is empty — no real entries leak", 0, repo.getEntries().size)65+ }66+67+ @Test fun wrong_password_opens_neither() = runBlocking {68+ val repo = configuredRepo()69+ assertNull(repo.tryUnlockSlotA("totally-wrong"))70+ assertNull(repo.tryUnlockDuress("totally-wrong"))71+ }72+73+ @Test fun duress_passphrase_cannot_equal_real_password() = runBlocking {74+ val repo = VaultRepository(DuressFakeStorage())75+ repo.createVault(real)76+ assertFalse("a duress passphrase matching the real password is rejected", repo.setDuressPassphrase(real))77+ }78+79+ @Test fun clear_duress_removes_the_slot() = runBlocking {80+ val repo = configuredRepo()81+ assertEquals(UnlockResult.Success, repo.unlock(real))82+ assertTrue(repo.clearDuress())83+ repo.lock()84+ assertNull("duress slot gone after clear", repo.tryUnlockDuress(duressPass))85+ }86+}