android: gate the Keystore passphrase key on device unlock, and migrate old installs
All checks were successful
android-ci / android (pull_request) Successful in 11m41s
All checks were successful
android-ci / android (pull_request) Successful in 11m41s
`setUnlockedDeviceRequired(true)` is now set on the key that wraps the store
passphrase (API 28+; below that the pre-gate path is unchanged and logs which
branch ran). `setUserAuthenticationRequired(false)` is untouched: the gate only
refuses while the lock screen is up, it is not a biometric prompt, so an
unattended unlock on an unlocked device still works.
A Keystore key cannot be retrofitted, so the gate needs a second alias:
`onionwire.store.unlock-gated` is generated with the flag and is the only key a
fresh install creates; `onionwire.store` is the pre-gate key and exists only on
installs that stored a passphrase earlier. Migration runs the next time the
passphrase is in hand (save(), or a successful load() — never inside open(),
which must not generate keys):
1. seal under the unlock-gated key (created here if needed)
2. write the blob to `…bin.tmp`
3. read those bytes back, open them with the gated key alone, compare to the
passphrase in hand — failure drops the temp file, throws SecretUnavailable
with the reason, and leaves the previous blob and key untouched
4. rename the temp file over the blob
5. only now delete the pre-gate alias
A crash before 4 leaves the old blob and key intact; a crash between 4 and 5
leaves a working gated blob plus a stale alias the next save/unlock retires.
`open()` tries the gated key first and falls back to the pre-gate key, so that
window is harmless. `forget()` deletes both aliases.
Reporting is honest about a platform limit: `KeyInfo` exposes
`isUserAuthenticationRequired` but has no getter for the unlock requirement, so
nothing can ask the Keystore whether the flag stuck.
`KeystorePassphraseCipher.unlockGateReport()` reports our own bookkeeping (which
alias the live key was generated under) plus `platformReportsGate = false`, and
a device whose Keystore refuses the flag falls back to the ungated alias and
says so instead of claiming the gate. A locked device that makes the gated key
unusable is reported as "the device is locked", not as a GCM tag failure.
Instrumentation: migration happy path (gated key appears, pre-gate alias gone
only after the on-disk blob opens under the new key), a failed re-wrap (old key
and blob byte-identical, no temp file), the gated proof refusing a pre-gate
blob, and the crash window still unlocking. Logcat lines print
MANUFACTURER/MODEL/SDK_INT and the branch taken. Not run here: no device or
emulator on this host. JVM suite still 213 tests / 0 failures; androidTest
sources compile.
This commit is contained in:
parent
36969a7e95
commit
d64114ca1c
3 changed files with 784 additions and 47 deletions
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue