diff --git a/android/app/src/androidTest/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipherTest.kt b/android/app/src/androidTest/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipherTest.kt index 2763026..fa1ec83 100644 --- a/android/app/src/androidTest/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipherTest.kt +++ b/android/app/src/androidTest/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipherTest.kt @@ -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 + } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipher.kt b/android/app/src/main/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipher.kt index 1153139..c40fce4 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipher.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipher.kt @@ -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" } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/crypto/StoredPassphraseStore.kt b/android/app/src/main/java/com/siriusdevops/onionwire/crypto/StoredPassphraseStore.kt index 4b88fed..40c89fc 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/crypto/StoredPassphraseStore.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/crypto/StoredPassphraseStore.kt @@ -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() + } + } } diff --git a/src/wallet.rs b/src/wallet.rs index a31990a..c5cf04f 100644 --- a/src/wallet.rs +++ b/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 = ""; + /// 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, ""); + 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:` 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://:@127.0.0.1:/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, } +impl Endpoint { + /// The URL with both halves of the login replaced, for any log line, error + /// string or status row: + /// `http://:@127.0.0.1:/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", &"") + .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:`. + 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 { _ => 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:hunter2@127.0.0.1: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:hunter2@127.0.0.1:18083/json_rpc"), + "http://:@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:hunter2@127.0.0.1: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"); + } +} diff --git a/src/wallet_child.rs b/src/wallet_child.rs index 6fa7e5b..2e797ac 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -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//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://:@127.0.0.1:`. //! * 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://:@127.0.0.1:/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:s3cret@127.0.0.1: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://:@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(); diff --git a/tests/wallet.rs b/tests/wallet.rs index 1337439..92723b0 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -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 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();