Merge branch 'main' into onionwire/t_79e98511-wallet-rpc-keep-spend-credentials-out-of
Some checks failed
android-ci / android (pull_request) Successful in 11m10s
ci / test (pull_request) Has been cancelled
ci / sdk (pull_request) Has been cancelled

This commit is contained in:
sirius 2026-10-23 02:46:18 +00:00
commit af9077046b
3 changed files with 784 additions and 47 deletions

View file

@ -3,6 +3,8 @@ package com.siriusdevops.onionwire.crypto
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Log
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
@ -12,9 +14,13 @@ import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File
import java.security.KeyStore
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
/**
* The device half of the Keystore story. The unit-test JVM has no
@ -28,6 +34,13 @@ import java.io.File
* `KeyInfo`/`isInsideSecureHardware`/`securityLevel` report — the point of
* [key_backing_is_reported_and_logged] is to print the truth, not to assert a
* hardware-backed key on hardware that does not have one.
*
* The migration tests below are the device half of the device-unlock gate:
* a pre-gate key is retired **only** after the replacement blob opens under the
* new key, and an interrupted migration leaves an install that still unlocks.
* They also log `MANUFACTURER`/`MODEL`/`SDK_INT` and the branch taken, because
* `setUnlockedDeviceRequired` is an OEM-sensitive flag and a red test on a
* specific phone is only diagnosable with that line.
*/
@RunWith(AndroidJUnit4::class)
class KeystorePassphraseCipherTest {
@ -39,6 +52,20 @@ class KeystorePassphraseCipherTest {
private val passphrase = "correct horse battery staple".toCharArray()
@Before
fun cleanSlate() {
// Both aliases: a leftover gated key from an aborted run would hide a
// migration that never happened.
val store = keyStore()
for (alias in listOf(KeystorePassphraseCipher.ALIAS_UNLOCK_GATED, KeystorePassphraseCipher.ALIAS)) {
try {
store.deleteEntry(alias)
} catch (_: Exception) {
// Nothing to delete.
}
}
}
@After
fun tearDown() {
cipher.deleteKey()
@ -93,12 +120,14 @@ class KeystorePassphraseCipherTest {
val strongBoxAdvertised = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
val backing = cipher.backing()
val gate = cipher.unlockGateReport()
Log.i(
"OnionWireKeystore",
TAG,
"alias=${KeystorePassphraseCipher.ALIAS} backing=$backing " +
"strongBoxAdvertised=$strongBoxAdvertised " +
"sdk=${Build.VERSION.SDK_INT} device=${Build.MANUFACTURER} ${Build.MODEL}",
"sdk=${Build.VERSION.SDK_INT} device=${Build.MANUFACTURER} ${Build.MODEL} " +
"gate=${gate.describe()}",
)
if (strongBoxAdvertised) {
@ -115,7 +144,9 @@ class KeystorePassphraseCipherTest {
fun open_does_not_require_user_authentication() {
// The card's contract: unlocking must not need a fingerprint. If the
// key had been created with setUserAuthenticationRequired(true), this
// open() would throw UserNotAuthenticatedException.
// open() would throw UserNotAuthenticatedException. The device-unlock
// gate is a different flag: it only refuses while the lock screen is up,
// which is not the case while this test runs.
val out = cipher.open(cipher.seal(passphrase))
StoreSecret.wipe(out)
assertTrue(cipher.keyPresent())
@ -147,4 +178,273 @@ class KeystorePassphraseCipherTest {
} catch (_: SecretUnavailable) {
}
}
// ------------------------------------------------------- device-unlock gate
/**
* The upgrade path: an install that stored its passphrase before the gate
* landed has one pre-gate key and a blob wrapped by it. The next successful
* unlock re-wraps that blob under a newly generated unlock-gated key, proves
* it, and only then retires the old alias.
*/
@Test
fun a_pre_flag_key_is_migrated_to_the_unlock_gated_alias_on_unlock() {
val branch = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
"unlock-gated (API >= 28)"
} else {
"ungated (API < 28 — setUnlockedDeviceRequired unavailable)"
}
Log.i(
TAG,
"migration: manufacturer=${Build.MANUFACTURER} model=${Build.MODEL} " +
"sdk=${Build.VERSION.SDK_INT} branch=$branch",
)
val legacy = createPreFlagKey()
val dir = File(context.filesDir, "secrets-migration")
dir.mkdirs()
val store = StoredPassphraseStore(File(dir, "store-passphrase.bin"), cipher)
try {
val blob = StoreSecret.seal(legacy, passphrase)
try {
File(store.path).writeBytes(blob)
} finally {
StoreSecret.wipe(blob)
}
assertTrue("precondition: the pre-gate alias exists", hasAlias(KeystorePassphraseCipher.ALIAS))
assertFalse(
"precondition: no gated key yet",
hasAlias(KeystorePassphraseCipher.ALIAS_UNLOCK_GATED),
)
// The unlock path: load() is where the passphrase is in hand.
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
try {
assertArrayEquals("the unlock must still return the passphrase", passphrase, loaded.passphrase)
} finally {
StoreSecret.wipe(loaded.passphrase)
}
val gate = cipher.unlockGateReport()
Log.i(TAG, "migration: after=${gate.describe()} legacyPending=${gate.legacyKeyPending}")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
assertTrue(
"expected a gated key after the re-wrap: ${gate.describe()}",
hasAlias(KeystorePassphraseCipher.ALIAS_UNLOCK_GATED),
)
assertFalse(
"the pre-gate key must be retired once the new blob verifies: ${gate.describe()}",
hasAlias(KeystorePassphraseCipher.ALIAS),
)
assertTrue("the report must say the live key is gated: ${gate.describe()}", gate.keyIsUnlockGated)
assertFalse("nothing may stay pending: ${gate.describe()}", gate.legacyKeyPending)
// The blob on disk must open under the NEW key alone — this is
// the proof the alias delete was allowed to happen.
val onDisk = File(store.path).readBytes()
val back = try {
StoreSecret.open(requireNotNull(gatedKey()), onDisk)
} finally {
StoreSecret.wipe(onDisk)
}
try {
assertArrayEquals(passphrase, back)
} finally {
StoreSecret.wipe(back)
}
} else {
assertFalse(
"API 26–27 has no flag, so no gated key may be invented",
hasAlias(KeystorePassphraseCipher.ALIAS_UNLOCK_GATED),
)
assertTrue("below API 28 the pre-gate key stays", hasAlias(KeystorePassphraseCipher.ALIAS))
}
} finally {
store.forget()
dir.deleteRecursively()
}
}
/**
* Every failure before "the new blob verified" must leave the previous blob
* and the pre-gate key in place. The simulated failure is the proof step
* itself, which is exactly the step that guards the alias delete.
*/
@Test
fun a_failed_re_wrap_keeps_the_pre_gate_key_and_the_previous_blob() {
val legacy = createPreFlagKey()
val dir = File(context.filesDir, "secrets-failed-migration")
dir.mkdirs()
val file = File(dir, "store-passphrase.bin")
try {
val oldBlob = StoreSecret.seal(legacy, passphrase)
try {
file.writeBytes(oldBlob)
} finally {
StoreSecret.wipe(oldBlob)
}
val before = file.readBytes()
try {
val doomed = StoredPassphraseStore(file, FailingVerifyCipher(cipher))
try {
doomed.save(passphrase)
fail("expected the simulated verification failure")
} catch (e: SecretUnavailable) {
assertTrue(
"the reason must say the old copy was kept: ${e.message}",
e.message!!.contains("previous blob and key were kept"),
)
}
assertTrue(
"the pre-gate key must survive a failed re-wrap",
hasAlias(KeystorePassphraseCipher.ALIAS),
)
assertFalse(
"a failed re-wrap must not leave a temp blob behind",
File(dir, "store-passphrase.bin.tmp").exists(),
)
assertArrayEquals(
"the previous blob must be untouched by a failed re-wrap",
before,
file.readBytes(),
)
} finally {
StoreSecret.wipe(before)
}
// The previous blob is byte-for-byte intact and still opens with the
// pre-gate key: an install that has not migrated is still usable.
val untouched = file.readBytes()
try {
val back = StoreSecret.open(requireNotNull(legacyKey()), untouched)
try {
assertArrayEquals(passphrase, back)
} finally {
StoreSecret.wipe(back)
}
} finally {
StoreSecret.wipe(untouched)
}
// A save that can verify finishes the migration on the spot.
StoredPassphraseStore(file, cipher).save(passphrase)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
assertFalse(
"the pre-gate key is retired as soon as the re-wrap verifies",
hasAlias(KeystorePassphraseCipher.ALIAS),
)
assertTrue(hasAlias(KeystorePassphraseCipher.ALIAS_UNLOCK_GATED))
}
} finally {
cipher.deleteKey()
dir.deleteRecursively()
}
}
/**
* The mirror of [a_pre_flag_key_is_migrated_to_the_unlock_gated_alias_on_unlock]:
* the proof step must use the gated key only. A fallback decrypt succeeding
* must never be mistaken for "the new blob is wrapped by the new key" — that
* is what would allow the alias delete to destroy the only working copy.
*/
@Test
fun the_gated_proof_refuses_a_blob_wrapped_by_the_pre_gate_key() {
val legacy = createPreFlagKey()
val blob = StoreSecret.seal(legacy, passphrase)
try {
cipher.seal(passphrase) // creates the gated key; the legacy key still exists
try {
cipher.openWithUnlockGate(blob)
fail("a pre-gate blob must not verify under the unlock-gated key")
} catch (_: SecretUnavailable) {
// On API 26–27 there is no gated key at all, so this is the
// "no key to prove against" refusal. Both are refusals.
}
} finally {
StoreSecret.wipe(blob)
}
}
/** The crash window: gated key created, blob not yet replaced. Must still open. */
@Test
fun a_blob_wrapped_by_the_pre_gate_key_still_opens_while_both_keys_exist() {
val legacy = createPreFlagKey()
val blob = StoreSecret.seal(legacy, passphrase)
try {
cipher.seal(passphrase) // gated key now exists too
val out = cipher.open(blob)
try {
assertArrayEquals(passphrase, out)
} finally {
StoreSecret.wipe(out)
}
} finally {
StoreSecret.wipe(blob)
}
}
// ------------------------------------------------------------------ helpers
private fun keyStore(): KeyStore =
KeyStore.getInstance(KeystorePassphraseCipher.PROVIDER).apply { load(null) }
private fun hasAlias(alias: String): Boolean = keyStore().containsAlias(alias)
private fun key(alias: String): SecretKey? = keyStore().getKey(alias, null) as? SecretKey
private fun gatedKey(): SecretKey? = key(KeystorePassphraseCipher.ALIAS_UNLOCK_GATED)
private fun legacyKey(): SecretKey? = key(KeystorePassphraseCipher.ALIAS)
/**
* Reproduces the key the app generated before the device-unlock gate
* existed: AES-256-GCM under [KeystorePassphraseCipher.ALIAS], no user-auth
* requirement, no unlock requirement. This is the install state the
* migration test starts from, not a new production path.
*/
private fun createPreFlagKey(): SecretKey {
val spec = KeyGenParameterSpec.Builder(
KeystorePassphraseCipher.ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(StoreSecret.KEY_BITS)
.setRandomizedEncryptionRequired(true)
.setUserAuthenticationRequired(false)
.build()
val generator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES,
KeystorePassphraseCipher.PROVIDER,
)
generator.init(spec)
return generator.generateKey()
}
/**
* Delegates to the real Keystore cipher except for the proof step, so the
* "the old key is deleted only after the new blob verifies" ordering can be
* asserted on a device without a way to corrupt a real Keystore blob.
*/
private class FailingVerifyCipher(
private val real: KeystorePassphraseCipher,
) : PassphraseCipher by real, PassphraseKeyMigration {
override fun unlockGateInEffect(): Boolean = real.unlockGateInEffect()
override fun legacyKeyPending(): Boolean = real.legacyKeyPending()
override fun openWithUnlockGate(blob: ByteArray): CharArray =
throw SecretUnavailable("simulated verify failure")
override fun retireLegacyKey() = real.retireLegacyKey()
override fun noteMigrationFailure(reason: String) = real.noteMigrationFailure(reason)
}
private companion object {
const val TAG = KeystorePassphraseCipher.TAG
}
}

View file

@ -1,11 +1,15 @@
package com.siriusdevops.onionwire.crypto
import android.app.KeyguardManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyInfo
import android.security.keystore.KeyProperties
import android.security.keystore.UserNotAuthenticatedException
import android.util.Log
import java.security.GeneralSecurityException
import java.security.KeyStore
import java.security.ProviderException
import javax.crypto.KeyGenerator
@ -13,7 +17,7 @@ import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
/**
* AES-256-GCM key held by the Android Keystore under [ALIAS].
* AES-256-GCM key held by the Android Keystore, wrapping the store passphrase.
*
* The key material is never readable by this process (`SecretKey.encoded` is
* null for AndroidKeyStore keys) — that is the whole point: pulling
@ -28,32 +32,99 @@ import javax.crypto.SecretKeyFactory
* fingerprint to unlock the node would turn "fail closed" into "unusable
* unattended", and the SDK's contract is that an unlock either opens the node
* or reports why it did not.
*
* ## Device-unlock gate (what this class adds on top of the flag above)
*
* The key is additionally bound to the device's lock state with
* `setUnlockedDeviceRequired(true)` (API 28+): while the lock screen is up, the
* key refuses to decrypt, so a blob lifted off a powered-on-but-locked device
* is not decryptable by the app's own process either. That is still not a
* fingerprint prompt — an unattended unlock on an unlocked device keeps
* working — it only refuses *while the device is locked*.
*
* Two aliases are in play because a Keystore key cannot be retrofitted and
* cannot be re-aliased:
*
* - [ALIAS] (`onionwire.store`) — the pre-gate key. Never generated by this
* class on API 28+; it exists only on installs that stored a passphrase
* before the gate landed.
* - [ALIAS_UNLOCK_GATED] (`onionwire.store.unlock-gated`) — generated with the
* device-unlock requirement. This is the only key a fresh install ever
* creates.
*
* At most one of the two is live after a migration; both exist only in the
* window between "the re-wrapped blob verified" and "the pre-gate key was
* deleted". [StoredPassphraseStore] drives that window, in that order, and is
* the only thing allowed to delete the pre-gate key.
*
* ## What can be *reported* about the gate, honestly
*
* `KeyInfo` on this API range exposes `isUserAuthenticationRequired` but has
* **no getter for the unlock requirement**, so no code here can ask the
* Keystore whether the flag stuck. [unlockGateReport] therefore reports our own
* bookkeeping — "the live key was generated under the unlock-gated alias" — and
* [UnlockGateReport.platformReportsGate] is a constant `false` saying so. On a
* device whose Keystore refuses the flag, the report shows
* `supported && !keyIsUnlockGated` plus the refusal reason; nothing pretends
* otherwise.
*/
class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher {
class KeystorePassphraseCipher(private val context: Context) :
PassphraseCipher,
PassphraseKeyMigration {
private var cached: SecretKey? = null
private var cached: ActiveKey? = null
override fun seal(plaintext: CharArray): ByteArray =
StoreSecret.seal(loadOrCreateKey(), plaintext)
/** Why this process's attempt at an unlock-gated key failed, if it did. */
private var gateRefusal: String? = null
/** Why the last re-wrap of the stored blob did not finish. Report-only. */
private var migrationFailure: String? = null
override fun seal(plaintext: CharArray): ByteArray {
val key = keyForSeal()
return try {
StoreSecret.seal(key.secret, plaintext)
} catch (e: SecretUnavailable) {
throw gateMessage(e, gatedKeyInPlay = key.gated)
}
}
/**
* Never creates a key. A freshly generated key cannot decrypt an old blob,
* and generating one here would turn "the key is gone" into a confusing
* GCM tag failure. The caller needs the real reason to tell the user.
*
* A blob written before the gate landed is wrapped by [ALIAS], so an
* unlock-gated key is tried first and the pre-gate key is the fallback —
* that ordering is what makes the crash window of the migration harmless.
*/
override fun open(blob: ByteArray): CharArray {
val key = cached ?: existingKey()
val active = activeKey()
?: throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
return StoreSecret.open(key, blob)
try {
return StoreSecret.open(active.secret, blob)
} catch (first: SecretUnavailable) {
if (active.gated) {
val legacy = existingKey(ALIAS)
if (legacy != null) {
try {
return StoreSecret.open(legacy, blob)
} catch (_: SecretUnavailable) {
// Fall through to the honest report below.
}
}
}
throw gateMessage(first, gatedKeyInPlay = active.gated)
}
}
override fun keyPresent(): Boolean = (cached ?: existingKey()) != null
override fun keyPresent(): Boolean = activeKey() != null
override fun backing(): KeyBacking {
val key = cached ?: existingKey() ?: return KeyBacking.UNKNOWN
val key = activeKey() ?: return KeyBacking.UNKNOWN
val info = try {
SecretKeyFactory.getInstance(key.algorithm, PROVIDER)
.getKeySpec(key, KeyInfo::class.java) as KeyInfo
SecretKeyFactory.getInstance(key.secret.algorithm, PROVIDER)
.getKeySpec(key.secret, KeyInfo::class.java) as KeyInfo
} catch (_: Exception) {
// Some OEM Keystore implementations refuse getKeySpec. Report
// UNKNOWN rather than guessing hardware backing.
@ -71,47 +142,189 @@ class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher
return if (inSecureHardware) KeyBacking.HARDWARE else KeyBacking.SOFTWARE
}
/** Deletes both aliases: `forget()` must leave nothing that can decrypt. */
override fun deleteKey() {
cached = null
val store = try {
keyStore()
} catch (_: Exception) {
return
}
for (alias in listOf(ALIAS_UNLOCK_GATED, ALIAS)) {
try {
store.deleteEntry(alias)
} catch (_: Exception) {
// Nothing usable to delete under that alias.
}
}
}
// ---------------------------------------------------------------- report
/**
* What can honestly be said about the device-unlock gate on the live key.
* See the class doc: there is no platform getter for the flag itself.
*/
fun unlockGateReport(): UnlockGateReport {
val active = activeKey()
return UnlockGateReport(
supported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P,
sdkInt = Build.VERSION.SDK_INT,
keyIsUnlockGated = active?.gated == true,
legacyKeyPending = existingKey(ALIAS) != null,
backing = if (active == null) KeyBacking.UNKNOWN else backing(),
gateRefusal = gateRefusal,
migrationFailure = migrationFailure,
)
}
private fun logBranch(branch: String) {
Log.i(
TAG,
"wrap key: branch=$branch sdk=${Build.VERSION.SDK_INT} " +
"manufacturer=${Build.MANUFACTURER} model=${Build.MODEL}",
)
}
// --------------------------------------------------- PassphraseKeyMigration
/**
* True when the key [seal] just wrapped with is the unlock-gated one. False
* on API 26–27 and on a device whose Keystore refused the flag — in both
* cases there is nothing to migrate to, and the caller must not delete the
* pre-gate key.
*/
override fun unlockGateInEffect(): Boolean =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && existingKey(ALIAS_UNLOCK_GATED) != null
override fun legacyKeyPending(): Boolean = existingKey(ALIAS) != null
/** Decrypts [blob] with the unlock-gated key alone — never the fallback. */
override fun openWithUnlockGate(blob: ByteArray): CharArray {
val key = existingKey(ALIAS_UNLOCK_GATED)
?: throw SecretUnavailable("no unlock-gated key exists to prove the blob against")
return try {
StoreSecret.open(key, blob)
} catch (e: SecretUnavailable) {
throw gateMessage(e, gatedKeyInPlay = true)
}
}
/**
* Deletes [ALIAS]. [StoredPassphraseStore] calls this only after the
* replacement blob is on disk and has been opened back under the new key;
* a blob wrapped by this alias becomes undecryptable the moment it runs.
*/
override fun retireLegacyKey() {
if (!legacyKeyPending()) return
try {
keyStore().deleteEntry(ALIAS)
} catch (_: Exception) {
// Nothing usable to delete.
} catch (e: Exception) {
noteMigrationFailure("could not delete the pre-gate key under $ALIAS (${e.message})")
return
}
if (cached?.gated == false) cached = null
Log.i(TAG, "retired the pre-gate Keystore key under $ALIAS; only $ALIAS_UNLOCK_GATED remains")
}
private fun existingKey(): SecretKey? {
override fun noteMigrationFailure(reason: String) {
migrationFailure = reason
Log.w(TAG, "unlock-gated key migration did not complete: $reason (blob and pre-gate key kept)")
}
// ------------------------------------------------------------------ keys
private class ActiveKey(val secret: SecretKey, val gated: Boolean)
/** Existing key we would decrypt with, unlock-gated first. Never creates. */
private fun activeKey(): ActiveKey? {
cached?.let { return it }
val key = try {
keyStore().getKey(ALIAS, null) as? SecretKey
} catch (_: Exception) {
existingKey(ALIAS_UNLOCK_GATED)?.let { return ActiveKey(it, gated = true).also { k -> cached = k } }
existingKey(ALIAS)?.let { return ActiveKey(it, gated = false).also { k -> cached = k } }
return null
}
/**
* The key [seal] uses. Prefers the unlock-gated alias (creating it if the
* platform allows), which is what turns a pre-gate install into a gated one
* the next time a passphrase is stored.
*/
private fun keyForSeal(): ActiveKey {
val active = activeKey()
if (active?.gated == true) return active
return gatedKeyOrCreate() ?: active ?: legacyKeyOrCreate()
}
private fun gatedKeyOrCreate(): ActiveKey? {
cached?.let { if (it.gated) return it }
existingKey(ALIAS_UNLOCK_GATED)?.let { return ActiveKey(it, gated = true).also { k -> cached = k } }
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return null
// One attempt per process: a Keystore that refused the flag will refuse
// it again, and unlock must not retry key generation on every call.
if (gateRefusal != null) return null
return try {
val key = generateWithFallback(ALIAS_UNLOCK_GATED, unlockGated = true)
logBranch("unlock-gated alias=$ALIAS_UNLOCK_GATED")
ActiveKey(key, gated = true).also { cached = it }
} catch (e: GeneralSecurityException) {
recordGateRefusal(e)
null
} catch (e: ProviderException) {
recordGateRefusal(e)
null
}
cached = key
return key
}
private fun loadOrCreateKey(): SecretKey = cached ?: existingKey() ?: createKey()
private fun legacyKeyOrCreate(): ActiveKey {
cached?.let { if (!it.gated) return it }
existingKey(ALIAS)?.let { return ActiveKey(it, gated = false).also { k -> cached = k } }
val key = generateWithFallback(ALIAS, unlockGated = false)
logBranch(
"ungated alias=$ALIAS" +
(gateRefusal?.let { " (unlock gate refused: $it)" } ?: ""),
)
return ActiveKey(key, gated = false).also { cached = it }
}
private fun createKey(): SecretKey {
val strongBoxAdvertised =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
if (strongBoxAdvertised) {
private fun recordGateRefusal(e: Exception) {
gateRefusal = "${e.javaClass.simpleName}: ${e.message}"
Log.w(
TAG,
"Keystore refused setUnlockedDeviceRequired(true) under $ALIAS_UNLOCK_GATED; " +
"falling back to the pre-gate alias $ALIAS (=$gateRefusal) " +
"sdk=${Build.VERSION.SDK_INT} manufacturer=${Build.MANUFACTURER} model=${Build.MODEL}",
)
}
private fun existingKey(alias: String): SecretKey? = try {
keyStore().getKey(alias, null) as? SecretKey
} catch (_: Exception) {
null
}
private fun strongBoxAdvertised(): Boolean =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
private fun generateWithFallback(alias: String, unlockGated: Boolean): SecretKey {
if (strongBoxAdvertised()) {
try {
return generate(strongBox = true).also { cached = it }
} catch (_: ProviderException) {
return generate(alias, strongBox = true, unlockGated = unlockGated)
} catch (e: ProviderException) {
// StrongBoxUnavailableException is a ProviderException: the chip
// exists but its slots are full, or it refuses AES-256. Fall
// through to a normal Keystore key instead of failing unlock.
Log.i(TAG, "StrongBox refused a key under $alias (${e.javaClass.simpleName}: ${e.message})")
} catch (e: GeneralSecurityException) {
Log.i(TAG, "StrongBox refused a key under $alias (${e.javaClass.simpleName}: ${e.message})")
}
}
return generate(strongBox = false).also { cached = it }
return generate(alias, strongBox = false, unlockGated = unlockGated)
}
private fun generate(strongBox: Boolean): SecretKey {
private fun generate(alias: String, strongBox: Boolean, unlockGated: Boolean): SecretKey {
val builder = KeyGenParameterSpec.Builder(
ALIAS,
alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
@ -119,7 +332,14 @@ class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher
.setKeySize(StoreSecret.KEY_BITS)
// Our IV comes from Cipher.init, and the Keystore supplies it.
.setRandomizedEncryptionRequired(true)
// Locked decision: no fingerprint gate on an unattended node.
.setUserAuthenticationRequired(false)
if (unlockGated && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// Refuses while the lock screen is up. No user-auth prompt is
// involved, so this does not turn "fail closed" into "unusable
// unattended" — it narrows *when* the key works, not who is awake.
builder.setUnlockedDeviceRequired(true)
}
if (strongBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
builder.setIsStrongBoxBacked(true)
}
@ -130,10 +350,114 @@ class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher
private fun keyStore(): KeyStore = KeyStore.getInstance(PROVIDER).apply { load(null) }
/**
* A gated key refuses to work while the lock screen is up, and the Keystore
* surfaces that as a plain crypto failure. "the stored secret did not
* authenticate" would read as a corrupt blob, so say what happened.
*/
private fun gateMessage(e: SecretUnavailable, gatedKeyInPlay: Boolean): SecretUnavailable {
if (!gatedKeyInPlay) return e
val lockRefusal = e.cause is UserNotAuthenticatedException || deviceLocked()
if (!lockRefusal) return e
return SecretUnavailable(
"the device is locked — the passphrase key is only usable while the device is unlocked",
e,
)
}
private fun deviceLocked(): Boolean =
context.getSystemService(KeyguardManager::class.java)?.isDeviceLocked == true
companion object {
const val PROVIDER = "AndroidKeyStore"
/** One key per app: the passphrase it wraps is the only secret here. */
/** Logcat tag; also what `adb logcat -s OnionWireKeystore` filters on. */
const val TAG = "OnionWireKeystore"
/**
* The pre-gate key's alias. Kept as the app's original name: a Keystore
* alias cannot be renamed, so an upgraded install keeps this one until
* [retireLegacyKey] deletes it.
*/
const val ALIAS = "onionwire.store"
/** The key that carries `setUnlockedDeviceRequired(true)`. */
const val ALIAS_UNLOCK_GATED = "onionwire.store.unlock-gated"
}
}
/**
* Re-wrapping a stored blob under a key that carries the device-unlock
* requirement.
*
* Deliberately **not** part of [PassphraseCipher]: an implementation without a
* Keystore (the JVM fakes in `StoredPassphraseStoreTest`) has nothing to
* migrate, and adding methods to the cipher interface would force every fake to
* grow a no-op. [StoredPassphraseStore] asks for this capability with a safe
* cast and skips migration entirely when it is absent.
*/
interface PassphraseKeyMigration {
/**
* True when the key the cipher just sealed with is the unlock-gated one.
* When false — API 26/27, or a Keystore that refused the flag — there is
* nothing to migrate to and the pre-gate key must be left alone.
*/
fun unlockGateInEffect(): Boolean
/** A pre-gate key still exists under [KeystorePassphraseCipher.ALIAS]. */
fun legacyKeyPending(): Boolean
/**
* Decrypts [blob] with the unlock-gated key **only**. Used to prove a
* freshly written blob before the pre-gate key is deleted, so a fallback
* decrypt cannot masquerade as proof.
*
* @throws SecretUnavailable when the blob is not wrapped by that key.
*/
fun openWithUnlockGate(blob: ByteArray): CharArray
/**
* Deletes the pre-gate key. Only valid once the replacement blob is durable
* and [openWithUnlockGate] has proven it.
*/
fun retireLegacyKey()
/** Records why a re-wrap attempt stopped, for logs and [unlockGateReport]. */
fun noteMigrationFailure(reason: String)
}
/**
* What we can honestly say about the device-unlock gate on the live key.
*
* [platformReportsGate] is always `false`: `KeyInfo` has no getter for
* `setUnlockedDeviceRequired`, so the gate state is our own bookkeeping about
* which alias the key was generated under, not a Keystore attestation.
*/
data class UnlockGateReport(
/** API 28+ can carry the flag at all. */
val supported: Boolean,
val sdkInt: Int,
/** The live key was generated under the unlock-gated alias. */
val keyIsUnlockGated: Boolean,
/** The pre-gate key still exists — a migration has not completed yet. */
val legacyKeyPending: Boolean,
val backing: KeyBacking,
/** Set when this process's attempt at a gated key was refused. */
val gateRefusal: String?,
/** Set when a re-wrap of the stored blob did not finish. */
val migrationFailure: String?,
/** No platform getter exists for the unlock requirement. Always false. */
val platformReportsGate: Boolean = false,
) {
/** One honest sentence for logcat / a status line. Never claims hardware proof. */
fun describe(): String = when {
keyIsUnlockGated -> "key: ${backing.name.lowercase()}, unusable while the device is locked"
!supported -> "key: ${backing.name.lowercase()}, unlock gate unsupported on SDK $sdkInt"
gateRefusal != null ->
"key: ${backing.name.lowercase()}, NOT unlock-gated — the Keystore refused the flag"
legacyKeyPending ->
"key: ${backing.name.lowercase()}, NOT unlock-gated — pre-gate key, migrates on the next unlock"
else -> "key: ${backing.name.lowercase()}, NOT unlock-gated"
}
}

View file

@ -11,6 +11,27 @@ import java.io.IOException
* The blob is the envelope from [StoreSecret] — magic + IV + ciphertext + tag.
* There is no second copy, no SharedPreferences mirror, and nothing outside the
* app's data dir.
*
* ## Migrating the wrapping key to the device-unlock gate
*
* A Keystore key cannot be retrofitted with `setUnlockedDeviceRequired`, so an
* install that stored a passphrase before the gate landed keeps an ungated key
* until the passphrase is in hand again. The only two places that happens are
* the ones below, and both go through the same crash-safe order:
*
* 1. `cipher.seal()` wraps under the unlock-gated key, creating it if needed.
* 2. The new blob is written to `…bin.tmp`.
* 3. Those exact bytes are read back and opened with the unlock-gated key and
* compared to the passphrase in hand. Failure ⇒ temp file dropped,
* everything else untouched (a [SecretUnavailable] with the reason, not a
* bare "did not authenticate").
* 4. Only then is the temp file renamed over the real blob.
* 5. Only then is the pre-gate Keystore alias deleted.
*
* A crash anywhere before 4 leaves the previous blob and the previous key
* intact; a crash between 4 and 5 leaves a working gated blob plus a stale
* alias that the next save/unlock retires. The pre-gate key is therefore never
* deleted before a blob that supersedes it is proven.
*/
class StoredPassphraseStore(
private val file: File,
@ -26,34 +47,53 @@ class StoredPassphraseStore(
/**
* Something is stored but cannot be read: the Keystore key is gone or
* invalidated, or the file is corrupt. Fall back to typing.
* unusable, the device is locked, or the file is corrupt. Fall back to
* typing.
*/
data class Unavailable(val reason: String) : Load
}
/**
* The optional key-migration capability. Absent for any cipher that is not
* the Keystore one (the JVM fakes in tests), which simply means there is
* nothing to migrate and the pre-gate order above does not apply.
*/
private fun migrator(): PassphraseKeyMigration? = cipher as? PassphraseKeyMigration
fun exists(): Boolean = file.isFile && file.length() > 0L
/** Where the wrapping key actually lives. See [PassphraseCipher.backing]. */
fun backing(): KeyBacking = cipher.backing()
/** True when the stored blob is wrapped by a device-unlock-gated key. */
fun unlockGated(): Boolean = migrator()?.unlockGateInEffect() == true
/** Path for diagnostics in tests. Never logged with its contents. */
val path: String get() = file.absolutePath
/**
* Encrypts and replaces the stored blob. Atomic-ish: written to a sibling
* temp file and renamed, so a crash mid-write cannot leave half a blob.
* Encrypts and replaces the stored blob, then retires a pre-gate key.
*
* Replaces the blob atomically: written to a sibling temp file, proven to
* open under the key that produced it, and only then renamed, so a crash
* mid-write cannot leave half a blob or a blob nobody can decrypt.
*
* @throws SecretUnavailable when the blob could not be written or could not
* be proven under the unlock-gated key. The previous blob is still in
* place in that case.
*/
fun save(passphrase: CharArray) {
require(passphrase.isNotEmpty()) { "refusing to store an empty passphrase" }
// seal() may create the unlock-gated key, so ask about the gate only
// afterwards — on a fresh install there is no gated key before this.
val blob = cipher.seal(passphrase)
try {
file.parentFile?.mkdirs()
val tmp = File(file.parentFile, file.name + ".tmp")
tmp.writeBytes(blob)
if (!tmp.renameTo(file)) {
file.writeBytes(blob)
tmp.delete()
}
val migration = migrator()
val gated = migration?.unlockGateInEffect() == true
writeVerified(blob, passphrase, if (gated) migration else null)
// The replacement blob is durable and proven. Only now may the
// pre-gate alias go: deleting it earlier would strand a blob.
if (gated) migration?.retireLegacyKey()
} finally {
StoreSecret.wipe(blob)
}
@ -62,6 +102,10 @@ class StoredPassphraseStore(
/**
* Reads and decrypts the blob. The returned array is the caller's to wipe.
*
* A successful read is also the moment the wrapping key can be upgraded: the
* passphrase is in hand, so a pre-gate key is re-wrapped here rather than
* asking the user to type it again.
*
* A failed decrypt does **not** delete the blob: a transient Keystore
* failure must not silently destroy the user's only copy. Use [forget] to
* drop it deliberately.
@ -73,13 +117,15 @@ class StoredPassphraseStore(
} catch (e: IOException) {
return Load.Unavailable("the stored passphrase file could not be read (${e.message})")
}
return try {
Load.Loaded(cipher.open(blob))
val passphrase = try {
cipher.open(blob)
} catch (e: SecretUnavailable) {
Load.Unavailable(e.message ?: "the stored passphrase did not authenticate")
return Load.Unavailable(e.message ?: "the stored passphrase did not authenticate")
} finally {
StoreSecret.wipe(blob)
}
migrateOnSuccessfulUnlock(passphrase)
return Load.Loaded(passphrase)
}
/** Drops the ciphertext and the Keystore key. Irreversible. */
@ -88,4 +134,71 @@ class StoredPassphraseStore(
File(file.parentFile, file.name + ".tmp").delete()
cipher.deleteKey()
}
/**
* Best effort, after a successful unlock. The unlock itself already
* succeeded, so a failed re-wrap must not fail it — but it must not be
* silent either: the reason goes to logcat and to
* [KeystorePassphraseCipher.unlockGateReport], and the install stays
* honestly "not unlock-gated" until a later save/unlock succeeds.
*/
private fun migrateOnSuccessfulUnlock(passphrase: CharArray) {
val migration = migrator() ?: return
if (!migration.unlockGateInEffect() || !migration.legacyKeyPending()) return
try {
save(passphrase)
} catch (e: Exception) {
migration.noteMigrationFailure(e.message ?: e.toString())
}
}
/**
* Writes [blob] to the temp file, proves the written bytes open under the
* unlock-gated key alone, and renames it into place.
*
* [verifier] is null when no unlock-gated key exists on this device (API
* 26–27, or a Keystore that refused the flag): the blob is then wrapped by
* the pre-gate key, which is the only key there is.
*/
private fun writeVerified(
blob: ByteArray,
passphrase: CharArray,
verifier: PassphraseKeyMigration?,
) {
file.parentFile?.mkdirs()
val tmp = File(file.parentFile, file.name + ".tmp")
tmp.writeBytes(blob)
if (verifier != null) {
val written = tmp.readBytes()
try {
val back = try {
verifier.openWithUnlockGate(written)
} catch (e: SecretUnavailable) {
tmp.delete()
throw SecretUnavailable(
"the new passphrase blob did not open under the unlock-gated key; " +
"the previous blob and key were kept",
e,
)
}
try {
if (!back.contentEquals(passphrase)) {
tmp.delete()
throw SecretUnavailable(
"the new passphrase blob did not read back identically; " +
"the previous blob and key were kept",
)
}
} finally {
StoreSecret.wipe(back)
}
} finally {
StoreSecret.wipe(written)
}
}
if (!tmp.renameTo(file)) {
file.writeBytes(blob)
tmp.delete()
}
}
}