Merge branch 'onionwire/t_438331aa-close-the-legacy-signature-surface-and-d' into onionwire/t_e31d85e7-gate-profile-prf-legacy-signature-accept
This commit is contained in:
commit
061723def1
7 changed files with 1309 additions and 64 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
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
301
docs/design/pq-bootstrap-epoch.md
Normal file
301
docs/design/pq-bootstrap-epoch.md
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
# ADR: a post-quantum bootstrap epoch (epoch 0)
|
||||
|
||||
**Status:** proposed. This is a decision record: it recommends a direction and
|
||||
changes no code. The protocol and threat-model wording it depends on is already
|
||||
on `main`; this file does not restate it.
|
||||
|
||||
**Decision:** accept the window (Option C). Revisit when the one-shot session
|
||||
model changes, or when a one-time prekey can reach the peer without a new wire
|
||||
field.
|
||||
|
||||
Related: [PROTOCOL.md](../PROTOCOL.md) ("Hybrid ratchet steps, and why epoch 0
|
||||
stays classical") and [THREAT_MODEL.md](../THREAT_MODEL.md) ("Epoch 0 is
|
||||
classical — this is the remaining harvest-now window").
|
||||
|
||||
## 1. Context: the invariant, stated exactly
|
||||
|
||||
Epoch 0 is the ratchet state a friend pair starts from. It is derived, not
|
||||
negotiated:
|
||||
|
||||
1. **Each chat message is its own one-shot Noise session.** `Node::send` encodes
|
||||
exactly one `rat ` frame and hands those bytes to the outbox
|
||||
(`src/node.rs:1905`, `src/outbox.rs:168`). Sending again opens a new Noise
|
||||
session to the same onion. There is no connection, stream, or session object
|
||||
that outlives one application frame.
|
||||
2. **The Noise handshake carries no application payload.** It is frozen at
|
||||
`Noise_IK_25519_ChaChaPoly_BLAKE2s`, so no field can hand the peer an initial
|
||||
ratchet key (`src/node.rs:2316`).
|
||||
3. **Either peer may send first.** Two peers can each build a sending chain
|
||||
before either has received anything. The resolution is per-direction chains
|
||||
over the *unordered pair* of ratchet public keys, so authorship of a direction
|
||||
is decided by key order rather than by who spoke first
|
||||
(`src/ratchet.rs:94-116`).
|
||||
4. **Therefore epoch 0 must be a pure function of material both sides already
|
||||
have**: the X25519 DH of the two long-lived signed prekeys, with each side's
|
||||
initial ratchet keypair seeded by
|
||||
`HKDF(info = "ratchet-key" || pubkey)`
|
||||
(`src/node.rs:2325-2370`). No wire field, no round trip, no per-session
|
||||
secret. This is the invariant the three options are measured against.
|
||||
|
||||
The consequence, already documented and not re-argued here: epoch 0 is derived
|
||||
with the classical `KDF_RK` and the ML-KEM secret enters at the **first
|
||||
rotation** (`src/ratchet.rs:66-73`, `docs/PROTOCOL.md:683`). Every frame sent
|
||||
before that point is X25519-only at the ratchet layer.
|
||||
|
||||
Two facts bound how much that costs, and they matter for the ranking:
|
||||
|
||||
- **For a v2 friend the `rat ` frame rides inside a hybrid Noise session.** A
|
||||
recorded transcript is not opened by an X25519 break alone; the ML-KEM-768
|
||||
prelude has to be broken too, and it is per-dial. Epoch 0 becomes the exposed
|
||||
layer when the rat frame is separated from the session that carried it — a
|
||||
state snapshot, an outbox row at rest, a logging client, or a classical peer
|
||||
(`docs/THREAT_MODEL.md:163-192`).
|
||||
- **The ML-KEM half of a ratchet keypair is derived from the X25519 secret**
|
||||
(`src/ratchet.rs:56-63`, `src/ratchet.rs:326`). It adds no independent secret
|
||||
to epoch 0, so "every keypair is hybrid" does not mean the bootstrap epoch is.
|
||||
|
||||
## 2. Options
|
||||
|
||||
Each subsection has the same shape: mechanism, wire cost, convergence, effect on
|
||||
the outbox and stored/replayed frames, test surface, and cost in slice-days. One
|
||||
slice-day is one focused working day for one agent in this repo, including tests
|
||||
and the doc updates the change would force.
|
||||
|
||||
### Option A — one-time prekey batch in the invite
|
||||
|
||||
**Mechanism.** The invite carries N ML-KEM-768 one-time prekeys (OPKs) in
|
||||
addition to the long-lived `kem=`. The peer consumes one per dial or per epoch,
|
||||
depending on which layer the OPK is meant to protect — that ambiguity is the
|
||||
first finding below. The threat model already lists "No one-time prekeys" as an
|
||||
honest limit (`docs/THREAT_MODEL.md:199-203`), so this is the option that would
|
||||
close a named gap; the size and convergence findings are what kill it.
|
||||
|
||||
**What the invite gains.** A new version, necessarily. The v2 signature domain is
|
||||
`onionwire-invite-v2 || 0x00 || k || 0x00 || o || 0x00 || spk || 0x00 || kem`
|
||||
(`src/qr.rs:38`), and `parse_fields` rejects any unrecognised field with
|
||||
`unknown field` (`src/qr.rs`, `parse_fields`). So an `opk=` field on a v2 string
|
||||
is a decode error, not an ignored extra: the batch is `onionwire:v3`, a new
|
||||
signature domain, and a new field in the signed message.
|
||||
|
||||
**Size, numerically.** A v2 invite is 1930 characters for a 56-character v3
|
||||
onion. Each ML-KEM-768 OPK is 1184 bytes, which is 1579 base64url characters
|
||||
plus a 5-character `:opk=` prefix — **1584 characters each**. The decoder caps
|
||||
input at `MAX_INVITE = 4096` (`src/qr.rs:30`), and the TUI renders the invite
|
||||
through `qrcode` 0.14.1 at its default `EcLevel::M` (`src/tui.rs:2818`), whose
|
||||
byte capacity is **2331 characters** (measured against the pinned crate, not
|
||||
recalled). Therefore:
|
||||
|
||||
| Invite | chars | fits `MAX_INVITE` | fits one QR at M |
|
||||
|---|---|---|---|
|
||||
| v2 today | 1930 | yes | yes |
|
||||
| v3, 1 OPK | 3514 | yes | **no** |
|
||||
| v3, 2 OPKs | 5098 | **no** | no |
|
||||
| v3, 4 OPKs | 8266 | no | no |
|
||||
|
||||
A batch that could survive more than one use cannot be carried by this invite at
|
||||
all: two OPKs already exceed the decoder's own cap, and one already exceeds what
|
||||
the QR path can render. The invite would have to move to a file/NFC transfer, or
|
||||
the QR would have to be dropped, before the batch is even representable.
|
||||
|
||||
**What is consumed, and when.** This is where the option loses its premise. If
|
||||
the OPK is consumed at the **transport** layer (one per Noise dial), it is one
|
||||
per message: a retry after a queued send is a new dial and burns another, and a
|
||||
batch of N is exhausted after N dials with no replenishment path — the peer has
|
||||
the invite, not a directory, so the next invite paste is the only refill. If it
|
||||
is consumed at the **ratchet** layer, it is one per epoch, and the secret has to
|
||||
reach the peer: ML-KEM encapsulation is randomised, so the sender must transmit
|
||||
a 1088-byte ciphertext. That is exactly Option B's wire field. **A does not fix
|
||||
epoch 0 without B**; on its own it only improves the transport handshake, which
|
||||
already carries a per-dial ML-KEM secret in the v2 prelude.
|
||||
|
||||
**Unused prekeys.** They are decapsulation keys stored for the life of the
|
||||
install, with no expiry and no ratchet benefit. A state snapshot hands them over,
|
||||
so they become an additional long-lived secret rather than a forward-secrecy
|
||||
win. The roster already drops state when a peer's prekey changes
|
||||
(`src/node.rs:2385-2395`); a batch would need its own consumption cursor, its own
|
||||
versioned blob, and a rule for when a partly-consumed batch is abandoned.
|
||||
|
||||
**Wire cost.** Invite only, if the OPK is used at the transport layer (+1584
|
||||
characters per prekey, and the QR stops working at one). Invite *and* frame
|
||||
(+1088 header bytes per epoch-0 frame, repeated until the first rotation) if used
|
||||
at the ratchet layer — at which point it is B.
|
||||
|
||||
**Convergence.** At the transport layer, unchanged: each Noise session's two
|
||||
endpoints both know that session's `ss_kem`, so per-dial secrets are fine there.
|
||||
At the ratchet layer, A *breaks* convergence on its own: both peers encapsulate
|
||||
to the same OPK, get different secrets (fresh randomness on each side), and
|
||||
derive different epoch-0 roots. Only one direction's ciphertext can be the
|
||||
authoritative one, and carrying it is a wire field.
|
||||
|
||||
**Outbox and replayed frames.** A stored `rat ` frame is replayed byte-for-byte
|
||||
over a fresh Noise session (`src/outbox.rs:161-175`; the retry loop must not
|
||||
advance the sending chain twice, so the frame is encoded once). Transport-layer
|
||||
OPK consumption therefore drains the batch on retries, not on delivered
|
||||
messages. Ratchet-layer consumption requires the receiver to retain the OPK
|
||||
private key until every queued row encrypted under it is delivered or
|
||||
terminally failed — unbounded retention, which contradicts "one-time".
|
||||
|
||||
**Test surface.** Invite v3 round-trip and signature domain; rejection of `opk=`
|
||||
on v2; batch exhaustion and the fallback to `kem=`; QR capacity (the invite
|
||||
render path currently has no graceful path for "too long for one symbol");
|
||||
retry-burns-a-prekey; a both-send-first test showing the two roots diverge if the
|
||||
ratchet layer is attempted without a field.
|
||||
|
||||
**Cost (estimate).** 5–7 slice-days for the invite/transport version of A (invite v3,
|
||||
signed field, store pool, consumption cursor, tests, docs). It buys a
|
||||
transport-layer improvement that is already covered by the per-dial prelude, and
|
||||
leaves epoch 0 exactly as it is. The ratchet-layer variant is B plus this cost.
|
||||
|
||||
### Option B — per-session epoch derivation with an extra wire field
|
||||
|
||||
**Mechanism.** Add material to the ratchet header and derive the epoch from it.
|
||||
The natural shape is a new version byte (`0x03` classical + field, `0x04` hybrid
|
||||
+ field) because `0x01` and `0x02` are already taken and the header is the AEAD
|
||||
associated data, so its exact shape is load-bearing
|
||||
(`src/ratchet.rs:1-40`, `src/ratchet.rs:585-601`). The field would be a 32-byte
|
||||
salt, or a 1088-byte ML-KEM ciphertext if it carries a prekey secret.
|
||||
|
||||
**Wire cost.** 32 bytes per frame (salt) or 1088 bytes per frame (ciphertext),
|
||||
repeated on every frame of the epoch-0 chain because the first frame can be lost.
|
||||
The classical header goes 40 → 72 bytes, the hybrid header 2312 → 3400, and the
|
||||
documented minimum frame sizes (350 classical, 2622 hybrid,
|
||||
`docs/THREAT_MODEL.md:217-220`) all move. The minimum-size tests and the padding
|
||||
ladder's interaction with the floor would have to be re-derived, not just
|
||||
re-numbered.
|
||||
|
||||
**Convergence.** This is the option's fatal case. The field arrives *in* the
|
||||
frame, so neither side has the other's field before its first send. Two designs
|
||||
are available and neither restores the invariant:
|
||||
|
||||
- *Sender-chosen salt, per direction.* Each side derives its own sending chain
|
||||
from its own salt. That works for the first message in each direction, but the
|
||||
epoch's shared root advance now depends on two salts, and the side that rotates
|
||||
first — the tie-break side rotates on its first *decrypt*
|
||||
(`src/ratchet.rs:624-630`) — may have seen only one of them. The root is no
|
||||
longer a pure function of the pair, so the lockstep argument in
|
||||
`src/ratchet.rs:100-116` no longer holds and the peers can diverge at the
|
||||
first rotation.
|
||||
- *Salt derived from the Noise session secret.* Then the two peers' first sends
|
||||
ride different sessions with different secrets, and message 2 rides a third
|
||||
session, so a stored and retried frame cannot be re-derived at all — see the
|
||||
outbox row.
|
||||
|
||||
A public salt in the header adds no secrecy, because it is transmitted in clear
|
||||
inside the Noise transport. It would only bind the chain to a random value,
|
||||
which is not the threat. So B is either a no-op against harvest-now, or it is a
|
||||
salt that breaks convergence, or it is a KEM ciphertext that reintroduces A's
|
||||
consumption and retention problems.
|
||||
|
||||
**Outbox and replayed frames.** A salt lives in the stored frame, so a verbatim
|
||||
replay is consistent. A ciphertext likewise survives the replay, but the
|
||||
receiver must still hold the matching private key when the retry lands — so the
|
||||
"one-time" key is retained until the outbox row is delivered or fails, and
|
||||
`DEFAULT_MAX_ATTEMPTS` (8) with a 30-minute backoff cap means that retention is
|
||||
measured in hours at minimum. This is the same retention conflict as A, now on
|
||||
the frame path.
|
||||
|
||||
**Test surface.** New version bytes and header layout; AAD coverage of the new
|
||||
field; the both-send-first matrix re-derived (the existing convergence tests in
|
||||
`src/ratchet.rs` and `tests/ratchet_wire.rs` assert the current argument, not just
|
||||
the happy path); `STATE_VERSION` 2 → 3 with a v2 blob dropped exactly like v1
|
||||
(`src/ratchet.rs:163`, `src/node.rs:2385-2395`); cross-version interop, since a
|
||||
friend with a v2 invite has no field to send — downgrade is decided by the
|
||||
roster, never by what arrives on the wire, so these are two different epoch
|
||||
shapes that must never be negotiated dynamically; padding floor and minimum-frame
|
||||
constants.
|
||||
|
||||
**Cost (estimate).** 8–12 slice-days, and it leaves the ambiguous root-advance rule open
|
||||
(that is the item in "Not solved by this doc").
|
||||
|
||||
### Option C — accept the window, keep the honesty bounds
|
||||
|
||||
**Mechanism.** No change. Epoch 0 stays prekey-derived and classical; the KEM
|
||||
secret enters at the first rotation; the docs keep saying so in the three places
|
||||
they already do (`src/ratchet.rs:66-73`, `docs/PROTOCOL.md:683-720`,
|
||||
`docs/THREAT_MODEL.md:163-192`).
|
||||
|
||||
**What has to be true for this to stay acceptable.** These are the conditions the
|
||||
decision rests on; if one stops holding, the trigger in §3 fires.
|
||||
|
||||
- *The first rotation is prompt.* It happens on the first inbound frame after
|
||||
`established`, and the lower-key side also rotates immediately on that decrypt
|
||||
(`src/ratchet.rs:624-630`). A peer that sends and never receives stays on
|
||||
epoch 0 by definition; the window closes with the first reply, not with time.
|
||||
- *Nothing claims otherwise.* "Post-quantum transport, classical bootstrap
|
||||
epoch" is the ceiling. `docs/THREAT_MODEL.md:25` and
|
||||
`docs/THREAT_MODEL.md:163` are the sentences that must not drift, and
|
||||
README/marketing copy inherits them.
|
||||
- *A state snapshot is already the whole game.* The ratchet state lives in the
|
||||
same SQLCipher file as the plaintext history, and `docs/THREAT_MODEL.md:205-209`
|
||||
says a snapshot carries both chain keys, the skipped keys, and the history.
|
||||
Epoch 0 is therefore not the weakest link at rest: an attacker with the store
|
||||
reads the messages, not the chain. The epoch-0 exposure is about frames outside
|
||||
the store — captured traffic and delivered outbox rows — not about the device.
|
||||
- *Outbox exposure stays bounded by delivery.* A row encoded on epoch 0 carries
|
||||
epoch-0 keys until it is delivered or terminally fails
|
||||
(`docs/THREAT_MODEL.md:176`). The queue is local, bounded by
|
||||
`DEFAULT_MAX_ATTEMPTS`, and never handed to a third party, so this is the same
|
||||
window as a live epoch-0 message, not a new one.
|
||||
- *The roster still decides downgrade.* A v1 friend has no PQ layer anywhere;
|
||||
that is a roster fact, not a wire negotiation
|
||||
(`docs/THREAT_MODEL.md:183-187`).
|
||||
|
||||
**Wire cost.** Zero. **Convergence.** Unchanged, and covered by the existing
|
||||
both-send-first and cross-peer tests. **Outbox and stored frames.** Unchanged;
|
||||
the verbatim-replay property stays exact. **Test surface.** No new tests; the
|
||||
existing ones already pin the invariant. **Cost.** 0 slice-days. The standing
|
||||
cost is one honest sentence in the docs, which is already paid.
|
||||
|
||||
## 3. Comparison and decision
|
||||
|
||||
| | A — OPK batch | B — epoch field | C — accept |
|
||||
|---|---|---|---|
|
||||
| Wire cost | +1584 chars/invite (QR dies at 1) | +32 or +1088 B/frame, new versions | 0 |
|
||||
| Fixes epoch 0? | no (transport only; needs B for ratchet) | only as a public salt, which is not the threat | n/a |
|
||||
| Convergence | breaks it at the ratchet layer | ambiguous root advance; breaks lockstep | unchanged |
|
||||
| Outbox / replay | drains batch on retries; unbounded OPK retention | verbatim replay OK, retention unbounded | unchanged, bounded by delivery |
|
||||
| Test surface | invite v3, pool, QR capacity, divergence | header, state v3, both-send-first matrix, floors | none |
|
||||
| Slice-days (est.) | 5–7 (and buys no epoch-0 fix) | 8–12 | 0 |
|
||||
|
||||
**Decision: C.** A does not make epoch 0 post-quantum — it adds invite mass and a
|
||||
consumption problem, and the part that would touch the ratchet is B's wire field,
|
||||
which cannot converge under both-send-first without an ambiguous root rule. C
|
||||
costs nothing, keeps the one property the design actually relies on (a root that
|
||||
is a pure function of the prekey pair), and the exposure it accepts is already
|
||||
shadowed for v2 friends by the per-dial hybrid Noise session.
|
||||
|
||||
**Revisit triggers**, in priority order. Any one of these reopens this ADR; none
|
||||
is a reason to start work now:
|
||||
|
||||
1. **The one-shot session model changes.** If chat ever gets a session that
|
||||
outlives one frame, the blocker in §1 disappears and epoch 0 can take a
|
||||
per-session secret. This is the real trigger.
|
||||
2. **A delivery path for a prekey ciphertext exists without a new field.** E.g.
|
||||
the handshake gains an application payload. Then A becomes viable at the
|
||||
ratchet layer.
|
||||
3. **The invite stops being QR-first.** If invites move to file/NFC and the
|
||||
`MAX_INVITE` cap can move with them, a batch is at least representable — still
|
||||
subject to the replenishment problem, so this alone is not enough.
|
||||
4. **Any doc or release note claims post-quantum messaging.** That is a
|
||||
documentation failure to fix immediately, not a reason to ship A or B.
|
||||
|
||||
**Consequences.** No code changes. The next card on this topic is not A or B; if
|
||||
one is proposed anyway, it must answer B's root-advance question and the QR
|
||||
capacity finding in A before it can be scoped. The docs on `main` continue to be
|
||||
the authority on what is and is not post-quantum.
|
||||
|
||||
## 4. Not solved by this doc
|
||||
|
||||
- **In-band revocation / unfriend.** There is no revoke frame; the roster drops
|
||||
a friend locally, and the peer keeps the current onion until F4
|
||||
(`docs/THREAT_MODEL.md:19`).
|
||||
- **Prekey or KEM rotation without a new invite.** F8 rotates the signed prekey
|
||||
and the ML-KEM install key, and every friend must paste the new invite; there
|
||||
is no push path (`docs/THREAT_MODEL.md:21-24`). Option A makes this worse, not
|
||||
better: a batch has no refill channel, so it inherits the same hard cut.
|
||||
- **Option B's open question.** Which input advances the epoch root when two
|
||||
per-direction salts exist and the first rotator has seen only one of them. A
|
||||
future B proposal has to answer that before it can be implemented; this doc
|
||||
does not.
|
||||
- **Guard discovery.** The long-lived v3 onion and Arti's vanguards-lite are a
|
||||
separate opsec gap and are not addressed by any of the three options.
|
||||
165
src/wallet.rs
165
src/wallet.rs
|
|
@ -1,4 +1,5 @@
|
|||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use rand::RngCore;
|
||||
|
|
@ -363,12 +364,16 @@ pub fn readiness(configured: bool, connected: bool, no_spend: bool, is_tip: bool
|
|||
Readiness::Ready
|
||||
}
|
||||
|
||||
/// What a redacted credential renders as. One spelling everywhere: the
|
||||
/// existing `Debug` pins and the URL accessor must agree.
|
||||
pub(crate) const REDACTED: &str = "<redacted>";
|
||||
|
||||
/// Display copy, not a log line: drop the secret if some lower layer put it in
|
||||
/// the message, and keep it short enough for a status line.
|
||||
pub(crate) fn redact(msg: &str, secret: &str) -> String {
|
||||
let mut out = msg.trim().to_string();
|
||||
if !secret.is_empty() {
|
||||
out = out.replace(secret, "<redacted>");
|
||||
out = out.replace(secret, REDACTED);
|
||||
}
|
||||
const MAX: usize = 120;
|
||||
if out.chars().count() > MAX {
|
||||
|
|
@ -378,6 +383,51 @@ pub(crate) fn redact(msg: &str, secret: &str) -> String {
|
|||
out
|
||||
}
|
||||
|
||||
/// [`redact`] for a whole `user:pass` login: drop the pair first (so no
|
||||
/// `user:<redacted>` survives), then the password half on its own, in case a
|
||||
/// lower layer printed only that. Every error/status string built from a
|
||||
/// [`WalletConfig`] goes through here.
|
||||
pub(crate) fn redact_login(msg: &str, login: &str) -> String {
|
||||
let login = login.trim();
|
||||
if login.is_empty() {
|
||||
return redact(msg, "");
|
||||
}
|
||||
let pass = login.split_once(':').map(|(_, p)| p).unwrap_or(login);
|
||||
redact(&redact(msg, login), pass)
|
||||
}
|
||||
|
||||
/// The URL with its userinfo replaced, for anything that prints a wallet
|
||||
/// endpoint: `http://<redacted>:<redacted>@127.0.0.1:<port>/json_rpc`. A URL
|
||||
/// with no userinfo is returned unchanged.
|
||||
pub(crate) fn redact_url(url: &str) -> String {
|
||||
match (url.find("://"), url.find('@')) {
|
||||
(Some(scheme), Some(at)) if at > scheme + 3 => {
|
||||
format!(
|
||||
"{}://{REDACTED}:{REDACTED}@{}",
|
||||
&url[..scheme],
|
||||
&url[at + 1..]
|
||||
)
|
||||
}
|
||||
_ => url.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one-shot notice for a login taken from the environment. Environment is
|
||||
/// readable through `/proc`, inherited by children, and lands in shell history,
|
||||
/// so the store is the preferred channel (`Wallet::for_boot` already tries it
|
||||
/// first). `true` only on the call that actually printed.
|
||||
static ENV_LOGIN_WARNED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
fn warn_env_login_once() -> bool {
|
||||
if ENV_LOGIN_WARNED.swap(true, Ordering::SeqCst) {
|
||||
return false;
|
||||
}
|
||||
eprintln!(
|
||||
"ONIONWIRE_WALLET_RPC_LOGIN: environment is readable by other processes and lands in shell history; put it in the wallet setup screen instead"
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Endpoint {
|
||||
host: String,
|
||||
|
|
@ -387,14 +437,25 @@ struct Endpoint {
|
|||
pass: Zeroizing<String>,
|
||||
}
|
||||
|
||||
impl Endpoint {
|
||||
/// The URL with both halves of the login replaced, for any log line, error
|
||||
/// string or status row:
|
||||
/// `http://<redacted>:<redacted>@127.0.0.1:<port>/json_rpc`.
|
||||
pub(crate) fn redacted(&self) -> String {
|
||||
format!(
|
||||
"http://{REDACTED}:{REDACTED}@{}{}",
|
||||
host_header(&self.host, self.port),
|
||||
self.path
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// `Debug` goes through [`Endpoint::redacted`]: a `{:?}` must never be the one
|
||||
/// place the login survives.
|
||||
impl std::fmt::Debug for Endpoint {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Endpoint")
|
||||
.field("host", &self.host)
|
||||
.field("port", &self.port)
|
||||
.field("path", &self.path)
|
||||
.field("user", &self.user)
|
||||
.field("pass", &"<redacted>")
|
||||
.field("url", &self.redacted())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
|
@ -524,7 +585,13 @@ impl Wallet {
|
|||
.map(|v| Zeroizing::new(v.trim().to_string()))
|
||||
.filter(|v| !v.is_empty());
|
||||
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
|
||||
Ok(endpoint) => Self::new(Some(endpoint), no_spend),
|
||||
Ok(endpoint) => {
|
||||
// Store wins (see `for_boot`); this path only runs when
|
||||
// no usable stored config exists, so the login really is
|
||||
// coming from the environment.
|
||||
warn_env_login_once();
|
||||
Self::new(Some(endpoint), no_spend)
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
|
||||
Self::new(None, no_spend)
|
||||
|
|
@ -546,7 +613,7 @@ impl Wallet {
|
|||
return Err(Error("wallet RPC endpoint required".into()));
|
||||
}
|
||||
let ep = parse_http_url(cfg.rpc_url.trim(), Some(cfg.rpc_login.as_str()))
|
||||
.map_err(|e| Error(redact(&e.to_string(), cfg.secret())))?;
|
||||
.map_err(|e| Error(redact_login(&e.to_string(), cfg.rpc_login.as_str())))?;
|
||||
Ok(Self::new(Some(ep), cfg.no_spend))
|
||||
}
|
||||
|
||||
|
|
@ -632,7 +699,7 @@ impl Wallet {
|
|||
return PingResult {
|
||||
ok: false,
|
||||
status: "not connected".into(),
|
||||
error: Some(redact(&e.to_string(), cfg.secret())),
|
||||
error: Some(redact_login(&e.to_string(), cfg.rpc_login.as_str())),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
|
@ -654,12 +721,13 @@ impl Wallet {
|
|||
|
||||
/// Display-safe copy of an error: no RPC password, short enough for a line.
|
||||
fn sanitize(&self, msg: &str) -> String {
|
||||
let pass = self
|
||||
.endpoint
|
||||
.as_ref()
|
||||
.map(|e| e.pass.as_str())
|
||||
.unwrap_or("");
|
||||
redact(msg, pass)
|
||||
// Both halves of `user:pass`, not just the password: an error that
|
||||
// names the URL's userinfo must not survive as `user:<redacted>`.
|
||||
let login = match self.endpoint.as_ref() {
|
||||
Some(ep) => Zeroizing::new(format!("{}:{}", ep.user, ep.pass.as_str())),
|
||||
None => Zeroizing::new(String::new()),
|
||||
};
|
||||
redact_login(msg, login.as_str())
|
||||
}
|
||||
|
||||
/// Set both RPC budgets. The timeout is a property of the backend, not a
|
||||
|
|
@ -1798,3 +1866,70 @@ fn hex_val(c: u8) -> Option<u8> {
|
|||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// The env is process-wide; these are the only lib tests that touch it.
|
||||
static ENV_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[test]
|
||||
fn redacting_an_error_drops_the_whole_login_not_just_the_password() {
|
||||
let msg = "dial http://ow:[email protected]:18083 failed for ow:hunter2";
|
||||
let out = redact_login(msg, "ow:hunter2");
|
||||
assert!(!out.contains("hunter2"), "{out}");
|
||||
assert!(!out.contains("ow:hunter2"), "{out}");
|
||||
assert!(out.contains("127.0.0.1:18083"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacted_url_keeps_the_endpoint_and_drops_the_userinfo() {
|
||||
assert_eq!(
|
||||
redact_url("http://ow:[email protected]:18083/json_rpc"),
|
||||
"http://<redacted>:<redacted>@127.0.0.1:18083/json_rpc"
|
||||
);
|
||||
assert_eq!(
|
||||
redact_url("http://127.0.0.1:18083/json_rpc"),
|
||||
"http://127.0.0.1:18083/json_rpc"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wallet_debug_prints_no_login() {
|
||||
let w = Wallet::from_url("http://ow:[email protected]:18083").unwrap();
|
||||
let dbg = format!("{w:?}");
|
||||
assert!(!dbg.contains("hunter2"), "{dbg}");
|
||||
assert!(!dbg.contains("ow:hunter2"), "{dbg}");
|
||||
assert!(dbg.contains("127.0.0.1"), "{dbg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_login_warns_once_per_process_and_not_for_a_stored_config() {
|
||||
let _guard = ENV_LOCK.lock().unwrap();
|
||||
ENV_LOGIN_WARNED.store(false, Ordering::SeqCst);
|
||||
// The one-shot gate itself: the first call prints, later ones do not.
|
||||
assert!(warn_env_login_once(), "first env login must warn");
|
||||
assert!(!warn_env_login_once(), "warning is once per process");
|
||||
ENV_LOGIN_WARNED.store(false, Ordering::SeqCst);
|
||||
|
||||
unsafe {
|
||||
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://127.0.0.1:18083");
|
||||
std::env::set_var("ONIONWIRE_WALLET_RPC_LOGIN", "ow:hunter2");
|
||||
}
|
||||
let _ = Wallet::from_env();
|
||||
let warned_from_env = ENV_LOGIN_WARNED.load(Ordering::SeqCst);
|
||||
unsafe { std::env::remove_var("ONIONWIRE_WALLET_RPC_LOGIN") };
|
||||
assert!(warned_from_env, "an env login must warn");
|
||||
|
||||
// The store is the preferred channel; `for_boot` takes it and never
|
||||
// reaches the env path, so no warning.
|
||||
ENV_LOGIN_WARNED.store(false, Ordering::SeqCst);
|
||||
let cfg = WalletConfig::new("http://127.0.0.1:18083", "ow:hunter2", false);
|
||||
let _ = Wallet::for_boot(Some(&cfg));
|
||||
let warned_from_store = ENV_LOGIN_WARNED.load(Ordering::SeqCst);
|
||||
unsafe { std::env::remove_var("ONIONWIRE_WALLET_RPC") };
|
||||
assert!(!warned_from_store, "a stored login must not warn");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,13 @@
|
|||
//! * The two Tor clients do not share state: the SOCKS child gets its own
|
||||
//! `state_dir`/`cache_dir` under the wallet dir.
|
||||
//! * `--trusted-daemon` is never passed: a remote daemon is untrusted.
|
||||
//! * Residual, and not fixable while the child is a spawned `monero-wallet-rpc`:
|
||||
//! `--rpc-login` is visible in `/proc/<pid>/cmdline` to same-uid processes
|
||||
//! because `monero-wallet-rpc` offers no other credential channel. The
|
||||
//! mitigation is a loopback-only bind, a strong generated login, and never
|
||||
//! handing the child a remote daemon. The login is also never rendered: the
|
||||
//! client's `url()` carries it for `Wallet::from_url`, while `Debug` and
|
||||
//! [`WalletClient::redacted_url`] show `http://<redacted>:<redacted>@127.0.0.1:<port>`.
|
||||
//! * The in-process daemon is *not* a child: it is a value owned by this struct,
|
||||
//! and dropping it shuts the node down. It still binds the same loopback RPC
|
||||
//! port, so everything downstream of `--daemon-address` is unchanged.
|
||||
|
|
@ -1060,12 +1067,23 @@ impl WalletChildStatus {
|
|||
/// The loopback client built from the generated URL — the production path when
|
||||
/// the app owns the child. Never `ONIONWIRE_WALLET_RPC`, never anything but
|
||||
/// numeric loopback.
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Clone)]
|
||||
pub struct WalletClient {
|
||||
url: String,
|
||||
no_spend: bool,
|
||||
}
|
||||
|
||||
/// Hand-written: `url` carries the generated login, so a derived `Debug` would
|
||||
/// turn any `{:?}` — a log line, a panic message, an assert — into a leak.
|
||||
impl std::fmt::Debug for WalletClient {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("WalletClient")
|
||||
.field("url", &self.redacted_url())
|
||||
.field("no_spend", &self.no_spend)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl WalletClient {
|
||||
/// Build the [`Wallet`] this child serves. The chain-side RPC budget is the
|
||||
/// wallet backend's default (see `CHAIN_RPC_TIMEOUT`), because a first sync
|
||||
|
|
@ -1076,11 +1094,18 @@ impl WalletClient {
|
|||
.with_no_spend(self.no_spend)
|
||||
}
|
||||
|
||||
/// The loopback URL. Carries the generated creds — do not log it.
|
||||
/// The loopback URL. Carries the generated creds — do not log it; use
|
||||
/// [`WalletClient::redacted_url`] for anything a human or a log can see.
|
||||
pub fn url(&self) -> &str {
|
||||
&self.url
|
||||
}
|
||||
|
||||
/// The same endpoint with both halves of the login replaced:
|
||||
/// `http://<redacted>:<redacted>@127.0.0.1:<port>/json_rpc`.
|
||||
pub fn redacted_url(&self) -> String {
|
||||
wallet::redact_url(&self.url)
|
||||
}
|
||||
|
||||
pub fn no_spend(&self) -> bool {
|
||||
self.no_spend
|
||||
}
|
||||
|
|
@ -2055,6 +2080,26 @@ mod tests {
|
|||
rest.split('@').next().expect("userinfo").to_string()
|
||||
}
|
||||
|
||||
/// The client dials with creds in the URL, but nothing that renders it may
|
||||
/// repeat them: `Debug` and `redacted_url` are the display surfaces.
|
||||
#[test]
|
||||
fn wallet_client_debug_and_redacted_url_hide_the_login() {
|
||||
let client = WalletClient {
|
||||
url: "http://alice:[email protected]:18083/json_rpc".into(),
|
||||
no_spend: false,
|
||||
};
|
||||
let dbg = format!("{client:?}");
|
||||
assert!(!dbg.contains("s3cret"), "{dbg}");
|
||||
assert!(!dbg.contains("alice:s3cret"), "{dbg}");
|
||||
assert!(dbg.contains("127.0.0.1"), "{dbg}");
|
||||
assert_eq!(
|
||||
client.redacted_url(),
|
||||
"http://<redacted>:<redacted>@127.0.0.1:18083/json_rpc"
|
||||
);
|
||||
// The dial still needs the real userinfo — redaction is for display.
|
||||
assert!(client.url().contains("alice:s3cret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pick_port_is_free_loopback_and_bindable() {
|
||||
let port = WalletChild::pick_port().unwrap();
|
||||
|
|
|
|||
|
|
@ -101,6 +101,33 @@ fn password_absent_from_url_errors() {
|
|||
);
|
||||
}
|
||||
|
||||
/// A 401 on the authenticated retry means the login is wrong. That copy is
|
||||
/// rendered in the TUI/Android status line, so it must not echo either half of
|
||||
/// the credential — not the password, not `user:pass`, not a URL with userinfo.
|
||||
#[tokio::test]
|
||||
async fn ping_401_error_carries_no_credential() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
// Answer the authenticated retry with another 401: the digest was built
|
||||
// from this connection's own challenge, so this is a wrong login.
|
||||
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> =
|
||||
Arc::new(|_| digest_401("refused-again"));
|
||||
tokio::spawn(serve_rpc_conns_with(listener, reply, None, None, true));
|
||||
|
||||
let pass = "s3cretPASS";
|
||||
let login = format!("ow:{pass}");
|
||||
let res = Wallet::ping(&format!("http://127.0.0.1:{}", addr.port()), login.as_str()).await;
|
||||
assert!(!res.ok, "a refused digest must not report connected");
|
||||
let err = res.error.expect("failure carries a reason");
|
||||
println!("401 ping error: {err}");
|
||||
assert!(!err.contains(pass), "password leaked in error: {err}");
|
||||
assert!(!err.contains(&login), "login leaked in error: {err}");
|
||||
assert!(
|
||||
!err.contains(&format!("://{login}@")),
|
||||
"URL userinfo leaked in error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mock_get_address_parses_string() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
|
|
|
|||
Loading…
Reference in a new issue