Merge branch 'main' into onionwire/t_fb6ffa87-strengthen-and-version-the-store-backup
Some checks failed
ci / sdk (pull_request) Has been cancelled
ci / test (pull_request) Has been cancelled

This commit is contained in:
sirius 2026-10-26 16:13:01 +00:00
commit 4cf0a09ceb
13 changed files with 1661 additions and 99 deletions

View file

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

View file

@ -1,11 +1,15 @@
package com.siriusdevops.onionwire.crypto package com.siriusdevops.onionwire.crypto
import android.app.KeyguardManager
import android.content.Context import android.content.Context
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.os.Build import android.os.Build
import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyInfo import android.security.keystore.KeyInfo
import android.security.keystore.KeyProperties 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.KeyStore
import java.security.ProviderException import java.security.ProviderException
import javax.crypto.KeyGenerator import javax.crypto.KeyGenerator
@ -13,7 +17,7 @@ import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory 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 * The key material is never readable by this process (`SecretKey.encoded` is
* null for AndroidKeyStore keys) — that is the whole point: pulling * 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 * 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 * unattended", and the SDK's contract is that an unlock either opens the node
* or reports why it did not. * 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 = /** Why this process's attempt at an unlock-gated key failed, if it did. */
StoreSecret.seal(loadOrCreateKey(), plaintext) 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, * 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 * 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. * 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 { override fun open(blob: ByteArray): CharArray {
val key = cached ?: existingKey() val active = activeKey()
?: throw SecretUnavailable("the device's Keystore key for OnionWire is gone") ?: 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 { override fun backing(): KeyBacking {
val key = cached ?: existingKey() ?: return KeyBacking.UNKNOWN val key = activeKey() ?: return KeyBacking.UNKNOWN
val info = try { val info = try {
SecretKeyFactory.getInstance(key.algorithm, PROVIDER) SecretKeyFactory.getInstance(key.secret.algorithm, PROVIDER)
.getKeySpec(key, KeyInfo::class.java) as KeyInfo .getKeySpec(key.secret, KeyInfo::class.java) as KeyInfo
} catch (_: Exception) { } catch (_: Exception) {
// Some OEM Keystore implementations refuse getKeySpec. Report // Some OEM Keystore implementations refuse getKeySpec. Report
// UNKNOWN rather than guessing hardware backing. // 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 return if (inSecureHardware) KeyBacking.HARDWARE else KeyBacking.SOFTWARE
} }
/** Deletes both aliases: `forget()` must leave nothing that can decrypt. */
override fun deleteKey() { override fun deleteKey() {
cached = null 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 { try {
keyStore().deleteEntry(ALIAS) keyStore().deleteEntry(ALIAS)
} catch (_: Exception) { } catch (e: Exception) {
// Nothing usable to delete. 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 } cached?.let { return it }
val key = try { existingKey(ALIAS_UNLOCK_GATED)?.let { return ActiveKey(it, gated = true).also { k -> cached = k } }
keyStore().getKey(ALIAS, null) as? SecretKey existingKey(ALIAS)?.let { return ActiveKey(it, gated = false).also { k -> cached = k } }
} catch (_: Exception) { 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 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 { private fun recordGateRefusal(e: Exception) {
val strongBoxAdvertised = gateRefusal = "${e.javaClass.simpleName}: ${e.message}"
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && Log.w(
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE) TAG,
if (strongBoxAdvertised) { "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 { try {
return generate(strongBox = true).also { cached = it } return generate(alias, strongBox = true, unlockGated = unlockGated)
} catch (_: ProviderException) { } catch (e: ProviderException) {
// StrongBoxUnavailableException is a ProviderException: the chip // StrongBoxUnavailableException is a ProviderException: the chip
// exists but its slots are full, or it refuses AES-256. Fall // exists but its slots are full, or it refuses AES-256. Fall
// through to a normal Keystore key instead of failing unlock. // 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( val builder = KeyGenParameterSpec.Builder(
ALIAS, alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
) )
.setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
@ -119,7 +332,14 @@ class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher
.setKeySize(StoreSecret.KEY_BITS) .setKeySize(StoreSecret.KEY_BITS)
// Our IV comes from Cipher.init, and the Keystore supplies it. // Our IV comes from Cipher.init, and the Keystore supplies it.
.setRandomizedEncryptionRequired(true) .setRandomizedEncryptionRequired(true)
// Locked decision: no fingerprint gate on an unattended node.
.setUserAuthenticationRequired(false) .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) { if (strongBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
builder.setIsStrongBoxBacked(true) builder.setIsStrongBoxBacked(true)
} }
@ -130,10 +350,114 @@ class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher
private fun keyStore(): KeyStore = KeyStore.getInstance(PROVIDER).apply { load(null) } 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 { companion object {
const val PROVIDER = "AndroidKeyStore" 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" const val ALIAS = "onionwire.store"
/** The key that carries `setUnlockedDeviceRequired(true)`. */
const val ALIAS_UNLOCK_GATED = "onionwire.store.unlock-gated"
}
}
/**
* Re-wrapping a stored blob under a key that carries the device-unlock
* requirement.
*
* Deliberately **not** part of [PassphraseCipher]: an implementation without a
* Keystore (the JVM fakes in `StoredPassphraseStoreTest`) has nothing to
* migrate, and adding methods to the cipher interface would force every fake to
* grow a no-op. [StoredPassphraseStore] asks for this capability with a safe
* cast and skips migration entirely when it is absent.
*/
interface PassphraseKeyMigration {
/**
* True when the key the cipher just sealed with is the unlock-gated one.
* When false — API 26/27, or a Keystore that refused the flag — there is
* nothing to migrate to and the pre-gate key must be left alone.
*/
fun unlockGateInEffect(): Boolean
/** A pre-gate key still exists under [KeystorePassphraseCipher.ALIAS]. */
fun legacyKeyPending(): Boolean
/**
* Decrypts [blob] with the unlock-gated key **only**. Used to prove a
* freshly written blob before the pre-gate key is deleted, so a fallback
* decrypt cannot masquerade as proof.
*
* @throws SecretUnavailable when the blob is not wrapped by that key.
*/
fun openWithUnlockGate(blob: ByteArray): CharArray
/**
* Deletes the pre-gate key. Only valid once the replacement blob is durable
* and [openWithUnlockGate] has proven it.
*/
fun retireLegacyKey()
/** Records why a re-wrap attempt stopped, for logs and [unlockGateReport]. */
fun noteMigrationFailure(reason: String)
}
/**
* What we can honestly say about the device-unlock gate on the live key.
*
* [platformReportsGate] is always `false`: `KeyInfo` has no getter for
* `setUnlockedDeviceRequired`, so the gate state is our own bookkeeping about
* which alias the key was generated under, not a Keystore attestation.
*/
data class UnlockGateReport(
/** API 28+ can carry the flag at all. */
val supported: Boolean,
val sdkInt: Int,
/** The live key was generated under the unlock-gated alias. */
val keyIsUnlockGated: Boolean,
/** The pre-gate key still exists — a migration has not completed yet. */
val legacyKeyPending: Boolean,
val backing: KeyBacking,
/** Set when this process's attempt at a gated key was refused. */
val gateRefusal: String?,
/** Set when a re-wrap of the stored blob did not finish. */
val migrationFailure: String?,
/** No platform getter exists for the unlock requirement. Always false. */
val platformReportsGate: Boolean = false,
) {
/** One honest sentence for logcat / a status line. Never claims hardware proof. */
fun describe(): String = when {
keyIsUnlockGated -> "key: ${backing.name.lowercase()}, unusable while the device is locked"
!supported -> "key: ${backing.name.lowercase()}, unlock gate unsupported on SDK $sdkInt"
gateRefusal != null ->
"key: ${backing.name.lowercase()}, NOT unlock-gated — the Keystore refused the flag"
legacyKeyPending ->
"key: ${backing.name.lowercase()}, NOT unlock-gated — pre-gate key, migrates on the next unlock"
else -> "key: ${backing.name.lowercase()}, NOT unlock-gated"
} }
} }

View file

@ -11,6 +11,27 @@ import java.io.IOException
* The blob is the envelope from [StoreSecret] — magic + IV + ciphertext + tag. * The blob is the envelope from [StoreSecret] — magic + IV + ciphertext + tag.
* There is no second copy, no SharedPreferences mirror, and nothing outside the * There is no second copy, no SharedPreferences mirror, and nothing outside the
* app's data dir. * 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( class StoredPassphraseStore(
private val file: File, private val file: File,
@ -26,34 +47,53 @@ class StoredPassphraseStore(
/** /**
* Something is stored but cannot be read: the Keystore key is gone or * 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 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 fun exists(): Boolean = file.isFile && file.length() > 0L
/** Where the wrapping key actually lives. See [PassphraseCipher.backing]. */ /** Where the wrapping key actually lives. See [PassphraseCipher.backing]. */
fun backing(): KeyBacking = cipher.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. */ /** Path for diagnostics in tests. Never logged with its contents. */
val path: String get() = file.absolutePath val path: String get() = file.absolutePath
/** /**
* Encrypts and replaces the stored blob. Atomic-ish: written to a sibling * Encrypts and replaces the stored blob, then retires a pre-gate key.
* temp file and renamed, so a crash mid-write cannot leave half a blob. *
* 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) { fun save(passphrase: CharArray) {
require(passphrase.isNotEmpty()) { "refusing to store an empty passphrase" } 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) val blob = cipher.seal(passphrase)
try { try {
file.parentFile?.mkdirs() val migration = migrator()
val tmp = File(file.parentFile, file.name + ".tmp") val gated = migration?.unlockGateInEffect() == true
tmp.writeBytes(blob) writeVerified(blob, passphrase, if (gated) migration else null)
if (!tmp.renameTo(file)) { // The replacement blob is durable and proven. Only now may the
file.writeBytes(blob) // pre-gate alias go: deleting it earlier would strand a blob.
tmp.delete() if (gated) migration?.retireLegacyKey()
}
} finally { } finally {
StoreSecret.wipe(blob) StoreSecret.wipe(blob)
} }
@ -62,6 +102,10 @@ class StoredPassphraseStore(
/** /**
* Reads and decrypts the blob. The returned array is the caller's to wipe. * 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 * A failed decrypt does **not** delete the blob: a transient Keystore
* failure must not silently destroy the user's only copy. Use [forget] to * failure must not silently destroy the user's only copy. Use [forget] to
* drop it deliberately. * drop it deliberately.
@ -73,13 +117,15 @@ class StoredPassphraseStore(
} catch (e: IOException) { } catch (e: IOException) {
return Load.Unavailable("the stored passphrase file could not be read (${e.message})") return Load.Unavailable("the stored passphrase file could not be read (${e.message})")
} }
return try { val passphrase = try {
Load.Loaded(cipher.open(blob)) cipher.open(blob)
} catch (e: SecretUnavailable) { } 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 { } finally {
StoreSecret.wipe(blob) StoreSecret.wipe(blob)
} }
migrateOnSuccessfulUnlock(passphrase)
return Load.Loaded(passphrase)
} }
/** Drops the ciphertext and the Keystore key. Irreversible. */ /** Drops the ciphertext and the Keystore key. Irreversible. */
@ -88,4 +134,71 @@ class StoredPassphraseStore(
File(file.parentFile, file.name + ".tmp").delete() File(file.parentFile, file.name + ".tmp").delete()
cipher.deleteKey() 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()
}
}
} }

View file

@ -312,20 +312,42 @@ prefix.
### Application-frame signatures ### Application-frame signatures
`loc`, `prf`, `inv`, and `rcp` each carry an ed25519 signature over the `loc`, `prf`, `inv`, `rcp`, and `tip` each carry an ed25519 signature over the
**fields**, not the 4-byte typed prefix. Encode MUST sign the domain-separated **fields**, not the 4-byte typed prefix. Encode MUST sign the domain-separated
form (type tag, then each field, `0x00` separators). Verify MUST accept that form (type tag, then each field, `0x00` separators). Verify MUST accept that
form and, for mixed-version peers, the legacy untagged LF-joined layout. form and, for mixed-version peers, the legacy untagged LF-joined layout.
Anything else fails closed. Do not emit the legacy layout. Anything else fails closed. Do not emit the legacy layout.
`tip` is signed over the LF-joined fields only (no domain tag on encode today). The invite string is separate and uses `onionwire-invite-v2` (see Invite).
The `tip ` prefix is not signed.
The invite string is separate and keeps `onionwire-invite-v1` (see Invite). Legacy acceptance is one switch, `LEGACY_SIGS`, default **on**. Every fallback
listed below reads it; with it off, verification accepts only the emitted
(tagged) form. It is a local capability constant, not a wire field: it is never
sent, and a peer cannot negotiate it.
Older builds verify only the untagged bytes, so they reject tagged signatures | frame | emitted | accepted inbound |
(fail closed, no downgrade). Mixed-version fleets break outbound application | --- | --- | --- |
frames from a new sender to an old receiver until both sides are updated. | invite | `onionwire-invite-v2`, `0x00`-separated over `k`, `o`, `spk`, `kem` | same; `onionwire:v1` over `onionwire-invite-v1` `0x00`-separated `k`,`o`,`spk`, or over `k \|\| o \|\| spk` (legacy only) |
| `loc ` | `"onionwire-loc-v1"` `0x00` `onion` `0x00` `ts` | same; `onion \|\| LF \|\| ts` (legacy only) |
| `prf ` | `"onionwire-prf-v1"` `0x00` `name` `0x00` `bio` `0x00` `xmr_addr` `0x00` `ts` | same; the four fields joined by LF (not yet gated — see below) |
| `inv ` | `"onionwire-inv-v1"` `0x00` `amount_atomic` `0x00` `address` `0x00` `memo` `0x00` `ts` | same; the four fields joined by LF (legacy only) |
| `rcp ` | `"onionwire-rcp-v1"` `0x00` `txid` `0x00` `amount_atomic` `0x00` `address` `0x00` `ts` | same; the four fields joined by LF (legacy only) |
| `tip ` | `"onionwire-tip-v1"` `0x00` `txid` `0x00` `amount_atomic` `0x00` `address` `0x00` `memo` `0x00` `ts` | same; the five fields joined by LF (legacy only) |
The tag suffixes do say `-v1`; that is the tag's own version, not the invite
string version.
`prf ` is the one frame whose legacy fallback is not yet gated: it is accepted
unconditionally in this revision and moving it under `LEGACY_SIGS` is a
separate change.
**Mixed-fleet consequence.** Older builds verify only the untagged bytes, so
they reject every tagged signature from a new sender — including `tip `, which
older builds emitted and verified untagged. That direction needs the peer
updated before tips flow. The reverse works while `LEGACY_SIGS` is on: a new
build verifies an old sender's untagged `loc`/`prf`/`inv`/`rcp`/`tip` and an
`onionwire:v1` invite. Turning the switch off is a fleet-wide cutover, not a
per-peer choice.
### `loc ` — locator update ### `loc ` — locator update
@ -348,8 +370,8 @@ ed25519_sign(identity_sk,
``` ```
**Legacy accept:** a signature over `onion || LF || ascii(ts)` is still **Legacy accept:** a signature over `onion || LF || ascii(ts)` is still
accepted on verify so old loc frames verify. New loc frames MUST use the accepted on verify while `LEGACY_SIGS` is on, so old loc frames verify. New loc
domain-separated form. Do not emit legacy. frames MUST use the domain-separated form. Do not emit legacy.
Apply only if **all** of: Apply only if **all** of:
@ -380,7 +402,7 @@ ed25519_sign(identity_sk,
**Legacy accept:** a signature over the four fields joined by LF is still **Legacy accept:** a signature over the four fields joined by LF is still
accepted on verify. New profile frames MUST use the domain-separated form. accepted on verify. New profile frames MUST use the domain-separated form.
Do not emit legacy. Do not emit legacy. This fallback is not yet read through `LEGACY_SIGS`.
Apply only for an existing friend, valid signature, newer `ts`. Not a public Apply only for an existing friend, valid signature, newer `ts`. Not a public
profile. Not a directory. profile. Not a directory.
@ -403,8 +425,8 @@ ed25519_sign(identity_sk,
``` ```
**Legacy accept:** a signature over the four fields joined by LF is still **Legacy accept:** a signature over the four fields joined by LF is still
accepted on verify. New invoices MUST use the domain-separated form. Do not accepted on verify while `LEGACY_SIGS` is on. New invoices MUST use the
emit legacy. domain-separated form. Do not emit legacy.
The frame is a signed claim, not a payment. It is one-shot: if the peer onion The frame is a signed claim, not a payment. It is one-shot: if the peer onion
is down, the send fails. There is no queued invoice. is down, the send fails. There is no queued invoice.
@ -425,8 +447,8 @@ ed25519_sign(identity_sk,
``` ```
**Legacy accept:** a signature over the four fields joined by LF is still **Legacy accept:** a signature over the four fields joined by LF is still
accepted on verify. New receipts MUST use the domain-separated form. Do not accepted on verify while `LEGACY_SIGS` is on. New receipts MUST use the
emit legacy. domain-separated form. Do not emit legacy.
Signature proves which friend sent the claim. It does **not** prove money Signature proves which friend sent the claim. It does **not** prove money
moved. Local `verified=1` only if a user-hosted `monero-wallet-rpc` returns moved. Local `verified=1` only if a user-hosted `monero-wallet-rpc` returns
@ -442,13 +464,20 @@ Sent after a chain transfer, together with `rcp `. One-shot.
tip <txid>\n<amount_atomic>\n<address>\n<memo>\n<ts>\n<sig_hex> tip <txid>\n<amount_atomic>\n<address>\n<memo>\n<ts>\n<sig_hex>
``` ```
The `tip ` prefix is **not** signed. Encode signs the LF-joined fields: The `tip ` prefix is **not** signed.
**Current signature (encode this):**
``` ```
ed25519_sign(identity_sk, ed25519_sign(identity_sk,
txid || LF || amount_atomic || LF || address || LF || memo || LF || ascii(ts)) "onionwire-tip-v1" || 0x00 || txid || 0x00 || amount_atomic || 0x00 ||
address || 0x00 || memo || 0x00 || ascii(ts))
``` ```
**Legacy accept:** a signature over the five fields joined by LF is still
accepted on verify while `LEGACY_SIGS` is on. New tips MUST use the
domain-separated form. Do not emit legacy.
`memo` MUST NOT contain newlines. Same address and amount rules as invoices. `memo` MUST NOT contain newlines. Same address and amount rules as invoices.
A peer that does not implement `tip ` MUST drop it as an unknown typed prefix, A peer that does not implement `tip ` MUST drop it as an unknown typed prefix,
not render it as chat. not render it as chat.
@ -880,7 +909,8 @@ signature covers `kem_ascii`, removing the field or substituting a different
key fails verification — that is the anti-strip/anti-substitution property. key fails verification — that is the anti-strip/anti-substitution property.
**Legacy accept (`onionwire:v1`):** a v1 invite has no `kem` field. Decode **Legacy accept (`onionwire:v1`):** a v1 invite has no `kem` field. Decode
accepts it and yields a friend with no `kem_pk`, i.e. a classical peer. A v1 accepts it while `LEGACY_SIGS` is on and yields a friend with no `kem_pk`, i.e.
a classical peer; with the switch off a v1 invite fails closed. A v1
signature is accepted in either historical form: the tagged signature is accepted in either historical form: the tagged
`"onionwire-invite-v1" || 0x00 || k || 0x00 || o || 0x00 || spk` or the raw `"onionwire-invite-v1" || 0x00 || k || 0x00 || o || 0x00 || spk` or the raw
concatenation `k || o || spk` (no tag, no separators), so old invites keep concatenation `k || o || spk` (no tag, no separators), so old invites keep

View 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.

View file

@ -54,9 +54,10 @@ pub fn verify(identity_pk: &[u8], loc: &Loc) -> bool {
let signature = Signature::from_bytes(&sig); let signature = Signature::from_bytes(&sig);
vk.verify(&sign_msg_v2(&loc.onion, loc.ts), &signature) vk.verify(&sign_msg_v2(&loc.onion, loc.ts), &signature)
.is_ok() .is_ok()
|| vk || (crate::pay::legacy_sigs()
.verify(&sign_msg_v1(&loc.onion, loc.ts), &signature) && vk
.is_ok() .verify(&sign_msg_v1(&loc.onion, loc.ts), &signature)
.is_ok())
} }
pub fn encode(loc: &Loc) -> Vec<u8> { pub fn encode(loc: &Loc) -> Vec<u8> {

View file

@ -1,9 +1,47 @@
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use sha3::{Digest, Keccak256}; use sha3::{Digest, Keccak256};
use std::cell::Cell;
use zeroize::Zeroizing; use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
/// Legacy signature acceptance.
///
/// Every signed frame is **emitted** in its domain-tagged form. Inbound, the
/// historical untagged / LF-joined layout (and the `onionwire:v1` invite
/// string) is still accepted so a mixed-version fleet keeps working; that
/// fallback is gated on this one switch. Set it to `false` to fail closed on
/// legacy signatures for every frame that reads it — `loc`, the invite string,
/// `inv`, `rcp`, and `tip`. (`prf` is not yet gated; see `docs/PROTOCOL.md`.)
pub const LEGACY_SIGS: bool = true;
thread_local! {
/// Per-thread override for tests. `None` follows [`LEGACY_SIGS`].
static LEGACY_SIGS_OVERRIDE: Cell<Option<bool>> = const { Cell::new(None) };
}
/// Whether legacy (pre-domain-tag) signatures are accepted inbound.
pub fn legacy_sigs() -> bool {
LEGACY_SIGS_OVERRIDE
.with(|o| o.get())
.unwrap_or(LEGACY_SIGS)
}
/// Run `f` with legacy acceptance forced to `on`, then restore the previous
/// thread state. A test hook, not a runtime setting: production code reads the
/// switch through [`legacy_sigs`] only.
#[doc(hidden)]
pub fn with_legacy_sigs<R>(on: bool, f: impl FnOnce() -> R) -> R {
struct Restore(Option<bool>);
impl Drop for Restore {
fn drop(&mut self) {
LEGACY_SIGS_OVERRIDE.with(|o| o.set(self.0));
}
}
let _restore = Restore(LEGACY_SIGS_OVERRIDE.with(|o| o.replace(Some(on))));
f()
}
#[derive(Debug)] #[derive(Debug)]
pub struct Error(String); pub struct Error(String);
@ -202,11 +240,12 @@ pub fn verify_invoice(identity_pk: &[u8], inv: &Invoice) -> bool {
identity_pk, identity_pk,
&inv_sign_msg_v2(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts), &inv_sign_msg_v2(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
&inv.sig, &inv.sig,
) || verify_bytes( ) || (legacy_sigs()
identity_pk, && verify_bytes(
&inv_sign_msg_v1(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts), identity_pk,
&inv.sig, &inv_sign_msg_v1(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
) &inv.sig,
))
} }
pub fn encode_invoice(inv: &Invoice) -> Vec<u8> { pub fn encode_invoice(inv: &Invoice) -> Vec<u8> {
@ -273,11 +312,12 @@ pub fn verify_receipt(identity_pk: &[u8], rcp: &Receipt) -> bool {
identity_pk, identity_pk,
&rcp_sign_msg_v2(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts), &rcp_sign_msg_v2(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
&rcp.sig, &rcp.sig,
) || verify_bytes( ) || (legacy_sigs()
identity_pk, && verify_bytes(
&rcp_sign_msg_v1(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts), identity_pk,
&rcp.sig, &rcp_sign_msg_v1(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
) &rcp.sig,
))
} }
pub fn encode_receipt(rcp: &Receipt) -> Vec<u8> { pub fn encode_receipt(rcp: &Receipt) -> Vec<u8> {
@ -339,6 +379,20 @@ fn check_tip_fields(txid: &str, amount_atomic: &str, address: &str, memo: &str)
Ok(()) Ok(())
} }
fn tip_sign_msg_v2(txid: &str, amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
tagged(
b"onionwire-tip-v1",
&[
txid.as_bytes(),
amount_atomic.as_bytes(),
address.as_bytes(),
memo.as_bytes(),
ts.to_string().as_bytes(),
],
)
}
/// Historical untagged form. Accept-only, and only while [`LEGACY_SIGS`] is on.
fn tip_sign_msg_v1(txid: &str, amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> { fn tip_sign_msg_v1(txid: &str, amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
let mut msg = Vec::from(txid.as_bytes()); let mut msg = Vec::from(txid.as_bytes());
msg.push(b'\n'); msg.push(b'\n');
@ -361,7 +415,10 @@ pub fn sign_tip(
ts: i64, ts: i64,
) -> Result<Tip> { ) -> Result<Tip> {
check_tip_fields(txid, amount_atomic, address, memo)?; check_tip_fields(txid, amount_atomic, address, memo)?;
let sig = sign_bytes(identity_sk, &tip_sign_msg_v1(txid, amount_atomic, address, memo, ts))?; let sig = sign_bytes(
identity_sk,
&tip_sign_msg_v2(txid, amount_atomic, address, memo, ts),
)?;
Ok(Tip { Ok(Tip {
txid: txid.to_string(), txid: txid.to_string(),
amount_atomic: amount_atomic.to_string(), amount_atomic: amount_atomic.to_string(),
@ -378,9 +435,26 @@ pub fn verify_tip(identity_pk: &[u8], tip: &Tip) -> bool {
} }
verify_bytes( verify_bytes(
identity_pk, identity_pk,
&tip_sign_msg_v1(&tip.txid, &tip.amount_atomic, &tip.address, &tip.memo, tip.ts), &tip_sign_msg_v2(
&tip.txid,
&tip.amount_atomic,
&tip.address,
&tip.memo,
tip.ts,
),
&tip.sig, &tip.sig,
) ) || (legacy_sigs()
&& verify_bytes(
identity_pk,
&tip_sign_msg_v1(
&tip.txid,
&tip.amount_atomic,
&tip.address,
&tip.memo,
tip.ts,
),
&tip.sig,
))
} }
pub fn encode_tip(tip: &Tip) -> Vec<u8> { pub fn encode_tip(tip: &Tip) -> Vec<u8> {

View file

@ -101,6 +101,11 @@ pub fn decode(raw: &str) -> Result<QrPayload> {
if kem_ascii.is_some() { if kem_ascii.is_some() {
return Err(Error("unknown field".into())); return Err(Error("unknown field".into()));
} }
// A v1 invite only ever carries a legacy signature: with legacy
// acceptance off it fails closed here, before any verify.
if !crate::pay::legacy_sigs() {
return Err(Error("legacy invite signatures disabled".into()));
}
let ok_tagged = vk let ok_tagged = vk
.verify(&sign_msg_v1_tagged(&k, &onion, &spk), &signature) .verify(&sign_msg_v1_tagged(&k, &onion, &spk), &signature)
.is_ok(); .is_ok();

View file

@ -1,4 +1,5 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration; use std::time::Duration;
use rand::RngCore; use rand::RngCore;
@ -363,12 +364,16 @@ pub fn readiness(configured: bool, connected: bool, no_spend: bool, is_tip: bool
Readiness::Ready 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 /// 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. /// the message, and keep it short enough for a status line.
pub(crate) fn redact(msg: &str, secret: &str) -> String { pub(crate) fn redact(msg: &str, secret: &str) -> String {
let mut out = msg.trim().to_string(); let mut out = msg.trim().to_string();
if !secret.is_empty() { if !secret.is_empty() {
out = out.replace(secret, "<redacted>"); out = out.replace(secret, REDACTED);
} }
const MAX: usize = 120; const MAX: usize = 120;
if out.chars().count() > MAX { if out.chars().count() > MAX {
@ -378,6 +383,51 @@ pub(crate) fn redact(msg: &str, secret: &str) -> String {
out 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)] #[derive(Clone)]
struct Endpoint { struct Endpoint {
host: String, host: String,
@ -387,14 +437,25 @@ struct Endpoint {
pass: Zeroizing<String>, 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 { impl std::fmt::Debug for Endpoint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Endpoint") f.debug_struct("Endpoint")
.field("host", &self.host) .field("url", &self.redacted())
.field("port", &self.port)
.field("path", &self.path)
.field("user", &self.user)
.field("pass", &"<redacted>")
.finish() .finish()
} }
} }
@ -524,7 +585,13 @@ impl Wallet {
.map(|v| Zeroizing::new(v.trim().to_string())) .map(|v| Zeroizing::new(v.trim().to_string()))
.filter(|v| !v.is_empty()); .filter(|v| !v.is_empty());
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) { 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) => { Err(e) => {
eprintln!("ONIONWIRE_WALLET_RPC: {e}"); eprintln!("ONIONWIRE_WALLET_RPC: {e}");
Self::new(None, no_spend) Self::new(None, no_spend)
@ -546,7 +613,7 @@ impl Wallet {
return Err(Error("wallet RPC endpoint required".into())); return Err(Error("wallet RPC endpoint required".into()));
} }
let ep = parse_http_url(cfg.rpc_url.trim(), Some(cfg.rpc_login.as_str())) 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)) Ok(Self::new(Some(ep), cfg.no_spend))
} }
@ -632,7 +699,7 @@ impl Wallet {
return PingResult { return PingResult {
ok: false, ok: false,
status: "not connected".into(), 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. /// Display-safe copy of an error: no RPC password, short enough for a line.
fn sanitize(&self, msg: &str) -> String { fn sanitize(&self, msg: &str) -> String {
let pass = self // Both halves of `user:pass`, not just the password: an error that
.endpoint // names the URL's userinfo must not survive as `user:<redacted>`.
.as_ref() let login = match self.endpoint.as_ref() {
.map(|e| e.pass.as_str()) Some(ep) => Zeroizing::new(format!("{}:{}", ep.user, ep.pass.as_str())),
.unwrap_or(""); None => Zeroizing::new(String::new()),
redact(msg, pass) };
redact_login(msg, login.as_str())
} }
/// Set both RPC budgets. The timeout is a property of the backend, not a /// 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, _ => 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");
}
}

View file

@ -22,6 +22,13 @@
//! * The two Tor clients do not share state: the SOCKS child gets its own //! * The two Tor clients do not share state: the SOCKS child gets its own
//! `state_dir`/`cache_dir` under the wallet dir. //! `state_dir`/`cache_dir` under the wallet dir.
//! * `--trusted-daemon` is never passed: a remote daemon is untrusted. //! * `--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, //! * 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 //! and dropping it shuts the node down. It still binds the same loopback RPC
//! port, so everything downstream of `--daemon-address` is unchanged. //! 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 loopback client built from the generated URL — the production path when
/// the app owns the child. Never `ONIONWIRE_WALLET_RPC`, never anything but /// the app owns the child. Never `ONIONWIRE_WALLET_RPC`, never anything but
/// numeric loopback. /// numeric loopback.
#[derive(Debug, Clone)] #[derive(Clone)]
pub struct WalletClient { pub struct WalletClient {
url: String, url: String,
no_spend: bool, 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 { impl WalletClient {
/// Build the [`Wallet`] this child serves. The chain-side RPC budget is the /// 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 /// wallet backend's default (see `CHAIN_RPC_TIMEOUT`), because a first sync
@ -1076,11 +1094,18 @@ impl WalletClient {
.with_no_spend(self.no_spend) .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 { pub fn url(&self) -> &str {
&self.url &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 { pub fn no_spend(&self) -> bool {
self.no_spend self.no_spend
} }
@ -2055,6 +2080,26 @@ mod tests {
rest.split('@').next().expect("userinfo").to_string() 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] #[test]
fn pick_port_is_free_loopback_and_bindable() { fn pick_port_is_free_loopback_and_bindable() {
let port = WalletChild::pick_port().unwrap(); let port = WalletChild::pick_port().unwrap();

View file

@ -198,3 +198,188 @@ fn inv_signature_does_not_verify_as_rcp() {
"inv-shaped payload must not verify as rcp" "inv-shaped payload must not verify as rcp"
); );
} }
// ---- legacy acceptance is one switch (`pay::LEGACY_SIGS`) ----
fn untagged_loc(sk: &SigningKey, onion: &str, ts: i64) -> Loc {
let mut msg = Vec::from(onion.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(ts.to_string().as_bytes());
Loc {
onion: onion.into(),
ts,
sig: sk.sign(&msg).to_bytes().to_vec(),
}
}
fn untagged_inv(sk: &SigningKey, amount: &str, address: &str, memo: &str, ts: i64) -> Invoice {
let mut msg = Vec::from(amount.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(address.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(memo.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(ts.to_string().as_bytes());
Invoice {
amount_atomic: amount.into(),
address: address.into(),
memo: memo.into(),
ts,
sig: sk.sign(&msg).to_bytes().to_vec(),
}
}
fn untagged_rcp(sk: &SigningKey, txid: &str, amount: &str, address: &str, ts: i64) -> Receipt {
let mut msg = Vec::from(txid.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(amount.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(address.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(ts.to_string().as_bytes());
Receipt {
txid: txid.into(),
amount_atomic: amount.into(),
address: address.into(),
ts,
sig: sk.sign(&msg).to_bytes().to_vec(),
}
}
fn untagged_tip(
sk: &SigningKey,
txid: &str,
amount: &str,
address: &str,
memo: &str,
ts: i64,
) -> onionwire::pay::Tip {
let mut msg = Vec::from(txid.as_bytes());
for f in [amount, address, memo] {
msg.push(b'\n');
msg.extend_from_slice(f.as_bytes());
}
msg.push(b'\n');
msg.extend_from_slice(ts.to_string().as_bytes());
onionwire::pay::Tip {
txid: txid.into(),
amount_atomic: amount.into(),
address: address.into(),
memo: memo.into(),
ts,
sig: sk.sign(&msg).to_bytes().to_vec(),
}
}
#[test]
fn legacy_untagged_tip_still_verifies() {
let (sk, pk) = keypair();
let tip = untagged_tip(&sk, "abc123", "1", MAINNET_STD, "coffee", 42);
assert!(
pay::verify_tip(&pk, &tip),
"legacy tip LF layout must still verify while LEGACY_SIGS is on"
);
}
#[test]
fn legacy_off_rejects_untagged_loc() {
let (sk, pk) = keypair();
let legacy = untagged_loc(&sk, "abc.onion", 42);
let tagged = loc::sign(&sk.to_bytes(), "abc.onion", 42).unwrap();
pay::with_legacy_sigs(false, || {
assert!(
!loc::verify(&pk, &legacy),
"untagged loc must be rejected with legacy off"
);
assert!(
loc::verify(&pk, &tagged),
"tagged loc must still verify with legacy off"
);
});
assert!(
loc::verify(&pk, &legacy),
"the switch restores acceptance after the scoped override"
);
}
#[test]
fn legacy_off_rejects_untagged_inv() {
let (sk, pk) = keypair();
let legacy = untagged_inv(&sk, "1", MAINNET_STD, "coffee", 42);
let tagged = pay::sign_invoice(&sk.to_bytes(), "1", MAINNET_STD, "coffee", 42).unwrap();
pay::with_legacy_sigs(false, || {
assert!(
!pay::verify_invoice(&pk, &legacy),
"untagged inv must be rejected with legacy off"
);
assert!(
pay::verify_invoice(&pk, &tagged),
"tagged inv must still verify with legacy off"
);
});
assert!(pay::verify_invoice(&pk, &legacy));
}
#[test]
fn legacy_off_rejects_untagged_rcp() {
let (sk, pk) = keypair();
let legacy = untagged_rcp(&sk, "deadbeef", "1", MAINNET_STD, 99);
let tagged = pay::sign_receipt(&sk.to_bytes(), "deadbeef", "1", MAINNET_STD, 99).unwrap();
pay::with_legacy_sigs(false, || {
assert!(
!pay::verify_receipt(&pk, &legacy),
"untagged rcp must be rejected with legacy off"
);
assert!(
pay::verify_receipt(&pk, &tagged),
"tagged rcp must still verify with legacy off"
);
});
assert!(pay::verify_receipt(&pk, &legacy));
}
#[test]
fn legacy_off_rejects_untagged_tip() {
let (sk, pk) = keypair();
let legacy = untagged_tip(&sk, "abc123", "1", MAINNET_STD, "coffee", 42);
let tagged = pay::sign_tip(&sk.to_bytes(), "abc123", "1", MAINNET_STD, "coffee", 42).unwrap();
pay::with_legacy_sigs(false, || {
assert!(
!pay::verify_tip(&pk, &legacy),
"untagged tip must be rejected with legacy off"
);
assert!(
pay::verify_tip(&pk, &tagged),
"tagged tip must still verify with legacy off"
);
});
assert!(pay::verify_tip(&pk, &legacy));
}
/// `sign_tip` emits the tagged form only: its signature must not verify over
/// the untagged LF layout.
#[test]
fn tip_emits_tagged_form_only() {
use ed25519_dalek::{Signature, Verifier};
let (sk, pk) = keypair();
let tip = pay::sign_tip(&sk.to_bytes(), "abc123", "1", MAINNET_STD, "coffee", 42).unwrap();
assert!(pay::verify_tip(&pk, &tip));
let sig: [u8; 64] = tip.sig.as_slice().try_into().expect("64-byte sig");
let mut msg = Vec::from(b"abc123".as_slice());
for f in ["1", MAINNET_STD, "coffee"] {
msg.push(b'\n');
msg.extend_from_slice(f.as_bytes());
}
msg.push(b'\n');
msg.extend_from_slice(b"42");
assert!(
sk.verifying_key()
.verify(&msg, &Signature::from_bytes(&sig))
.is_err(),
"sign_tip must not sign the untagged layout"
);
// And the tagged signature covers the memo: changing it fails.
let mut tampered = tip.clone();
tampered.memo = String::new();
assert!(!pay::verify_tip(&pk, &tampered));
}

View file

@ -312,3 +312,25 @@ fn huge_hex_is_err_quickly() {
"decode must fail closed before a multi-MB alloc" "decode must fail closed before a multi-MB alloc"
); );
} }
#[test]
fn legacy_off_rejects_v1_invite_but_v2_still_decodes() {
let _home = TempHome::new();
let store = Store::open().expect("open");
let me = store.self_identity().expect("self");
let sk: [u8; 32] = me.identity_sk.as_slice().try_into().expect("32-byte sk");
let onion = v3onion("switch");
let raw_v1 = legacy_v1(&sk, &onion, &[8u8; 32]);
let raw_v2 = qr::encode(&me.identity_sk, &onion, &[8u8; 32], &me.kem_pk).expect("encode v2");
onionwire::pay::with_legacy_sigs(false, || {
assert!(
qr::decode(&raw_v1).is_err(),
"a v1 invite must be rejected with legacy off"
);
let p = qr::decode(&raw_v2).expect("v2 invite still decodes with legacy off");
assert!(p.kem_pk.is_some(), "v2 invite keeps its PQ key");
});
// Legacy acceptance returns with the default switch state.
assert!(qr::decode(&raw_v1).is_ok());
}

View file

@ -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] #[tokio::test]
async fn mock_get_address_parses_string() { async fn mock_get_address_parses_string() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();