transport: ML-KEM-768 hybrid prelude and onionwire:v2 invites
All checks were successful
ci / test (pull_request) Successful in 18m32s
android-ci / android (pull_request) Successful in 20m14s
ci / sdk (pull_request) Successful in 3m11s

Adds an ML-KEM-768 install key beside the ed25519 identity and x25519
prekey. A friend added from a v2 invite always gets a version-2 PQ
prelude before Noise msg 1, and both sides bind (ct, ss_kem) into the
Noise prologue (onionwire-v2 \0 ct \0 ss_kem). The row decides: a
kem_pk friend without a prelude is rejected with 'prelude required',
a prelude for a classical row with 'unexpected prelude'.

Invites are now onionwire:v2 with kem=<base64url pk>; decode still
accepts v1 (no kem) and yields a classical friend. F8 rotates the
KEM key with the prekey and hard-cuts stored ratchet state. The TUI
labels a legacy friend 'classical'.

Docs: PROTOCOL (keys, framing, prologues, no-downgrade, invite v2),
THREAT_MODEL (what PQ transport does and does not buy; epoch 0 stays
classical), README (invite size, F8, legacy caveat). SDK exposes pq on
InviteInfo/FriendInfo and gains a v2 decode round-trip test.
This commit is contained in:
agent 2026-10-20 11:15:46 -04:00
commit c741b660e4
No known key found for this signature in database
26 changed files with 1637 additions and 177 deletions

113
Cargo.lock generated
View file

@ -1095,7 +1095,9 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [ dependencies = [
"getrandom 0.4.3",
"hybrid-array", "hybrid-array",
"rand_core 0.10.1",
] ]
[[package]] [[package]]
@ -1802,6 +1804,16 @@ dependencies = [
"zeroize", "zeroize",
] ]
[[package]]
name = "der"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"
dependencies = [
"const-oid 0.10.2",
"zeroize",
]
[[package]] [[package]]
name = "der-parser" name = "der-parser"
version = "10.0.0" version = "10.0.0"
@ -1998,12 +2010,12 @@ version = "0.16.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
dependencies = [ dependencies = [
"der", "der 0.7.10",
"digest 0.10.7", "digest 0.10.7",
"elliptic-curve", "elliptic-curve",
"rfc6979", "rfc6979",
"signature", "signature",
"spki", "spki 0.7.3",
] ]
[[package]] [[package]]
@ -2012,7 +2024,7 @@ version = "2.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
dependencies = [ dependencies = [
"pkcs8", "pkcs8 0.10.2",
"signature", "signature",
] ]
@ -2062,7 +2074,7 @@ dependencies = [
"ff", "ff",
"generic-array", "generic-array",
"group", "group",
"pkcs8", "pkcs8 0.10.2",
"rand_core 0.6.4", "rand_core 0.6.4",
"sec1", "sec1",
"subtle", "subtle",
@ -2714,6 +2726,7 @@ version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [ dependencies = [
"ctutils",
"typenum", "typenum",
"zeroize", "zeroize",
] ]
@ -3163,6 +3176,16 @@ dependencies = [
"cpufeatures 0.3.1", "cpufeatures 0.3.1",
] ]
[[package]]
name = "kem"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01737161ba802849cfd486b5bd209d38ba4943494c249a8126005170c7621edd"
dependencies = [
"crypto-common 0.2.2",
"rand_core 0.10.1",
]
[[package]] [[package]]
name = "konst" name = "konst"
version = "0.2.20" version = "0.2.20"
@ -3428,6 +3451,34 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "ml-kem"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9ba01ebcf90f6aff8e9b9f55bb69b19e6250e4ade5787d0040eaa27dd226238"
dependencies = [
"hybrid-array",
"kem",
"module-lattice",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha3 0.12.0",
"shake",
"zeroize",
]
[[package]]
name = "module-lattice"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c61b87c9683ab7cb1c6871d261ad5479b6b10ceb52c4352aaca3b5d35a8febe"
dependencies = [
"ctutils",
"hybrid-array",
"num-traits",
"zeroize",
]
[[package]] [[package]]
name = "monero-address" name = "monero-address"
version = "0.1.0" version = "0.1.0"
@ -3785,6 +3836,7 @@ dependencies = [
"hkdf", "hkdf",
"hmac", "hmac",
"md-5", "md-5",
"ml-kem",
"qrcode", "qrcode",
"rand 0.8.8", "rand 0.8.8",
"ratatui", "ratatui",
@ -4097,9 +4149,9 @@ version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
dependencies = [ dependencies = [
"der", "der 0.7.10",
"pkcs8", "pkcs8 0.10.2",
"spki", "spki 0.7.3",
] ]
[[package]] [[package]]
@ -4108,8 +4160,18 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
dependencies = [ dependencies = [
"der", "der 0.7.10",
"spki", "spki 0.7.3",
]
[[package]]
name = "pkcs8"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
dependencies = [
"der 0.8.2",
"spki 0.8.1",
] ]
[[package]] [[package]]
@ -4700,11 +4762,11 @@ dependencies = [
"num-integer", "num-integer",
"num-traits", "num-traits",
"pkcs1", "pkcs1",
"pkcs8", "pkcs8 0.10.2",
"rand_core 0.6.4", "rand_core 0.6.4",
"sha2", "sha2",
"signature", "signature",
"spki", "spki 0.7.3",
"subtle", "subtle",
"zeroize", "zeroize",
] ]
@ -4913,9 +4975,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
dependencies = [ dependencies = [
"base16ct", "base16ct",
"der", "der 0.7.10",
"generic-array", "generic-array",
"pkcs8", "pkcs8 0.10.2",
"subtle", "subtle",
"zeroize", "zeroize",
] ]
@ -5150,6 +5212,17 @@ dependencies = [
"sponge-cursor", "sponge-cursor",
] ]
[[package]]
name = "shake"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a"
dependencies = [
"digest 0.11.3",
"keccak 0.2.2",
"sponge-cursor",
]
[[package]] [[package]]
name = "sharded-slab" name = "sharded-slab"
version = "0.1.7" version = "0.1.7"
@ -5323,7 +5396,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
dependencies = [ dependencies = [
"base64ct", "base64ct",
"der", "der 0.7.10",
]
[[package]]
name = "spki"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
dependencies = [
"base64ct",
"der 0.8.2",
] ]
[[package]] [[package]]
@ -5544,7 +5627,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874"
dependencies = [ dependencies = [
"rustix", "rustix",
"windows-sys 0.59.0", "windows-sys 0.61.2",
] ]
[[package]] [[package]]

View file

@ -75,6 +75,10 @@ sha2 = "0.10"
md-5 = "0.10" md-5 = "0.10"
rpassword = "7" rpassword = "7"
zeroize = { version = "1", features = ["derive"] } zeroize = { version = "1", features = ["derive"] }
# ML-KEM-768 (FIPS 203). `zeroize` wipes the decapsulation key; `getrandom`
# is how 0.3's `generate_keypair` / `encapsulate` reach the OS RNG. This
# crate's `rand` 0.8 cannot: ml-kem speaks `rand_core` 0.10.
ml-kem = { version = "0.3", features = ["zeroize", "getrandom"] }
qrcode = { version = "0.14", default-features = false } qrcode = { version = "0.14", default-features = false }
cuprated = { git = "https://github.com/Cuprate/cuprate", rev = "4f8fcd1bf468f566fcd89c460d50de4adb6825bf", default-features = false, optional = true } cuprated = { git = "https://github.com/Cuprate/cuprate", rev = "4f8fcd1bf468f566fcd89c460d50de4adb6825bf", default-features = false, optional = true }
# `cuprated::config::Config` is deserialized, not built field by field: the # `cuprated::config::Config` is deserialized, not built field by field: the

View file

@ -4,9 +4,13 @@ Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process A
No hosted server. Identity is an ed25519 public key; the onion is only a locator. No hosted server. Identity is an ed25519 public key; the onion is only a locator.
Current tagged release: **v0.14.0**. Linux TUI + Android SDK/APK. Two people add Current tagged release: **v0.14.0**. Linux TUI + Android SDK/APK. Two people add
each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There each other with an `onionwire:v2:…` invite string (`F2` share / `F3` paste;
is no invite QR graphic. Chat is Noise IK over your own v3 onion; every chat ~1.9 KB because it carries an ML-KEM-768 key). There is no invite QR graphic.
message is ratcheted inside that session. Unreachable chat peers go to a **local Chat is Noise IK over your own v3 onion; when the friend was added from a v2
invite the session is **hybrid** (ML-KEM-768 prelude mixed into the Noise
prologue). A friend from a legacy `onionwire:v1` invite stays classical and the
roster labels them `classical`. Every chat message is ratcheted inside that
session. Unreachable chat peers go to a **local
outbox** (device-only retry queue — no relay). File transfer and payment frames outbox** (device-only retry queue — no relay). File transfer and payment frames
fail closed. Optional Monero: `/pay` invoices, `/tip` payments, and in-app wallet fail closed. Optional Monero: `/pay` invoices, `/tip` payments, and in-app wallet
create/import (`F6`). Arti onion services are still experimental. The store is create/import (`F6`). Arti onion services are still experimental. The store is
@ -216,13 +220,13 @@ payload can contain `?`).
| `j` `k` / `↑` `↓` | Move or scroll the focused pane | | `j` `k` / `↑` `↓` | Move or scroll the focused pane |
| `g` / `G` | Jump to top / bottom of the focused pane | | `g` / `G` | Jump to top / bottom of the focused pane |
| `?` | Keybinding help (`Esc` closes) | | `?` | Keybinding help (`Esc` closes) |
| `F2` | Share invite (`onionwire:v1:…`) | | `F2` | Share invite (`onionwire:v2:…`, ~1.9 KB) |
| `F3` | Paste a friend's invite | | `F3` | Paste a friend's invite |
| `F4` | Rotate **onion** (locator only) | | `F4` | Rotate **onion** (locator only) |
| `F5` | Selected friend's profile (`/who`) | | `F5` | Selected friend's profile (`/who`) |
| `F6` | Wallet (receive QR, balance, transfers, create/import) | | `F6` | Wallet (receive QR, balance, transfers, create/import) |
| `F7` | Node & wallet setup (wallet RPC endpoint, chain source, start/stop, live node state) | | `F7` | Node & wallet setup (wallet RPC endpoint, chain source, start/stop, live node state) |
| `F8` | Rotate **prekey** (hard cut: every friend re-pastes the invite) | | `F8` | Rotate **prekey and ML-KEM key** (hard cut: every friend re-pastes the invite) |
| `F9` | Wallets & settings menu (`/settings`) | | `F9` | Wallets & settings menu (`/settings`) |
| Enter | Send chat to the selected friend, or run a `/command` | | Enter | Send chat to the selected friend, or run a `/command` |
| `Esc` | Close overlay / back to Main / clear composer | | `Esc` | Close overlay / back to Main / clear composer |
@ -243,10 +247,22 @@ Composer `/commands` (`src/tui.rs` `parse_cmd`): `/wipe`, `/wipe-all`, `/profile
There is no invite QR. `F2` opens the share screen with truncated fingerprint, There is no invite QR. `F2` opens the share screen with truncated fingerprint,
current onion, and the full payload (wrapped, mouse-select to copy): current onion, and the full payload (wrapped, mouse-select to copy):
`onionwire:v1:k=…:o=…:spk=…:sig=…` `onionwire:v2:k=…:o=…:spk=…:kem=…:sig=…`
The `kem=` field is the 1184-byte ML-KEM-768 public key (base64url), so the
string is about 1.9 KB instead of a few hundred bytes; `C` copies the whole
payload even when the terminal is too short to display all of it. Decode still
accepts a legacy `onionwire:v1:…` invite (no `kem=`): that friend is added as a
**classical** peer and the roster says `classical` next to them. There is no
silent upgrade — only a new signed v2 invite changes that.
Give that string to a friend. They `F3` paste it. Unknown `k` asks for approval. Give that string to a friend. They `F3` paste it. Unknown `k` asks for approval.
Same `k` already in the roster updates `onion` (and prekey) only. Same `k` already in the roster updates `onion` (and prekey/KEM key) only.
No PQ for a legacy v1 peer: they have no `kem_pk`, so the session uses the old
`onionwire-v1` prologue with no ML-KEM secret. A v2 friend always sends the
prelude; a peer that omits it is hard-failed with `prelude required`. A v1-only
build cannot talk to a v2 friend, and that break is intentional.
## F4 rotate onion ## F4 rotate onion
@ -295,8 +311,13 @@ session carries. Wire format: [docs/PROTOCOL.md](docs/PROTOCOL.md).
stored). A queued chat message re-sends the *same* `rat ` frame. stored). A queued chat message re-sends the *same* `rat ` frame.
- `/wipe` clears chat, payments and outbox but **keeps** ratchet state. `/wipe-all` - `/wipe` clears chat, payments and outbox but **keeps** ratchet state. `/wipe-all`
removes the data dir. removes the data dir.
- There is no `/reset`. State drops when the friend's prekey changes (you - There is no `/reset`. State drops when the friend's prekey or ML-KEM key
`F3`-paste a refreshed invite). changes (you `F3`-paste a refreshed invite).
- **The ratchet is not post-quantum.** The hybrid prelude protects the one-shot
Noise transport. The chat bootstrap epoch is still derived from the two
long-lived X25519 prekeys, so a future quantum adversary holding a recorded
`rat ` chain and both prekeys can reconstruct epoch 0. PQ ratchet steps are a
separate follow-up; see [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
- An inbound `rat ` frame that does not authenticate is logged as - An inbound `rat ` frame that does not authenticate is logged as
`rat dropped (<reason>)` on stderr and dropped. There is no in-app desync banner. `rat dropped (<reason>)` on stderr and dropped. There is no in-app desync banner.

View file

@ -1181,7 +1181,9 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [ dependencies = [
"getrandom 0.4.3",
"hybrid-array", "hybrid-array",
"rand_core 0.10.1",
] ]
[[package]] [[package]]
@ -1888,6 +1890,16 @@ dependencies = [
"zeroize", "zeroize",
] ]
[[package]]
name = "der"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"
dependencies = [
"const-oid 0.10.2",
"zeroize",
]
[[package]] [[package]]
name = "der-parser" name = "der-parser"
version = "10.0.0" version = "10.0.0"
@ -2084,12 +2096,12 @@ version = "0.16.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
dependencies = [ dependencies = [
"der", "der 0.7.10",
"digest 0.10.7", "digest 0.10.7",
"elliptic-curve", "elliptic-curve",
"rfc6979", "rfc6979",
"signature", "signature",
"spki", "spki 0.7.3",
] ]
[[package]] [[package]]
@ -2098,7 +2110,7 @@ version = "2.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
dependencies = [ dependencies = [
"pkcs8", "pkcs8 0.10.2",
"signature", "signature",
] ]
@ -2148,7 +2160,7 @@ dependencies = [
"ff", "ff",
"generic-array", "generic-array",
"group", "group",
"pkcs8", "pkcs8 0.10.2",
"rand_core 0.6.4", "rand_core 0.6.4",
"sec1", "sec1",
"subtle", "subtle",
@ -2811,6 +2823,7 @@ version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [ dependencies = [
"ctutils",
"typenum", "typenum",
"zeroize", "zeroize",
] ]
@ -3260,6 +3273,16 @@ dependencies = [
"cpufeatures 0.3.1", "cpufeatures 0.3.1",
] ]
[[package]]
name = "kem"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01737161ba802849cfd486b5bd209d38ba4943494c249a8126005170c7621edd"
dependencies = [
"crypto-common 0.2.2",
"rand_core 0.10.1",
]
[[package]] [[package]]
name = "konst" name = "konst"
version = "0.2.20" version = "0.2.20"
@ -3525,6 +3548,34 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "ml-kem"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9ba01ebcf90f6aff8e9b9f55bb69b19e6250e4ade5787d0040eaa27dd226238"
dependencies = [
"hybrid-array",
"kem",
"module-lattice",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha3 0.12.0",
"shake",
"zeroize",
]
[[package]]
name = "module-lattice"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c61b87c9683ab7cb1c6871d261ad5479b6b10ceb52c4352aaca3b5d35a8febe"
dependencies = [
"ctutils",
"hybrid-array",
"num-traits",
"zeroize",
]
[[package]] [[package]]
name = "monero-address" name = "monero-address"
version = "0.1.0" version = "0.1.0"
@ -3865,6 +3916,7 @@ dependencies = [
"hkdf", "hkdf",
"hmac", "hmac",
"md-5", "md-5",
"ml-kem",
"qrcode", "qrcode",
"rand 0.8.8", "rand 0.8.8",
"ratatui", "ratatui",
@ -4156,9 +4208,9 @@ version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
dependencies = [ dependencies = [
"der", "der 0.7.10",
"pkcs8", "pkcs8 0.10.2",
"spki", "spki 0.7.3",
] ]
[[package]] [[package]]
@ -4167,8 +4219,18 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
dependencies = [ dependencies = [
"der", "der 0.7.10",
"spki", "spki 0.7.3",
]
[[package]]
name = "pkcs8"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
dependencies = [
"der 0.8.2",
"spki 0.8.1",
] ]
[[package]] [[package]]
@ -4765,11 +4827,11 @@ dependencies = [
"num-integer", "num-integer",
"num-traits", "num-traits",
"pkcs1", "pkcs1",
"pkcs8", "pkcs8 0.10.2",
"rand_core 0.6.4", "rand_core 0.6.4",
"sha2", "sha2",
"signature", "signature",
"spki", "spki 0.7.3",
"subtle", "subtle",
"zeroize", "zeroize",
] ]
@ -4989,9 +5051,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
dependencies = [ dependencies = [
"base16ct", "base16ct",
"der", "der 0.7.10",
"generic-array", "generic-array",
"pkcs8", "pkcs8 0.10.2",
"subtle", "subtle",
"zeroize", "zeroize",
] ]
@ -5207,6 +5269,17 @@ dependencies = [
"sponge-cursor", "sponge-cursor",
] ]
[[package]]
name = "shake"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a"
dependencies = [
"digest 0.11.3",
"keccak 0.2.2",
"sponge-cursor",
]
[[package]] [[package]]
name = "sharded-slab" name = "sharded-slab"
version = "0.1.7" version = "0.1.7"
@ -5386,7 +5459,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
dependencies = [ dependencies = [
"base64ct", "base64ct",
"der", "der 0.7.10",
]
[[package]]
name = "spki"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
dependencies = [
"base64ct",
"der 0.8.2",
] ]
[[package]] [[package]]
@ -5607,7 +5690,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874"
dependencies = [ dependencies = [
"rustix", "rustix",
"windows-sys 0.59.0", "windows-sys 0.61.2",
] ]
[[package]] [[package]]

View file

@ -103,6 +103,10 @@ pub struct FriendInfo {
/// Current locator. May be stale if the peer rotated while you were down. /// Current locator. May be stale if the peer rotated while you were down.
pub onion: String, pub onion: String,
pub last_connect_ok: bool, pub last_connect_ok: bool,
/// True when the friend was added from `onionwire:v2` (has an ML-KEM key),
/// so sessions are hybrid. False is a legacy v1 friend: classical
/// transport, and the UI must say so.
pub pq: bool,
} }
/// What `send()` did with the message. /// What `send()` did with the message.
@ -190,6 +194,8 @@ pub struct RotateOutcome {
pub struct InviteInfo { pub struct InviteInfo {
pub pubkey_hex: String, pub pubkey_hex: String,
pub onion: String, pub onion: String,
/// `onionwire:v2` (ML-KEM key present) vs a legacy v1 invite.
pub pq: bool,
} }
/// Observable lifecycle state of the node's onion service. /// Observable lifecycle state of the node's onion service.
@ -300,6 +306,7 @@ pub fn decode_invite(invite: String) -> WResult<InviteInfo> {
Ok(InviteInfo { Ok(InviteInfo {
pubkey_hex: hex(&p.pubkey), pubkey_hex: hex(&p.pubkey),
onion: p.onion, onion: p.onion,
pq: p.kem_pk.is_some(),
}) })
} }
@ -388,6 +395,7 @@ impl Wire {
petname: f.petname, petname: f.petname,
onion: f.onion, onion: f.onion,
last_connect_ok: f.last_connect_ok, last_connect_ok: f.last_connect_ok,
pq: f.kem_pk.is_some(),
}) })
.collect()) .collect())
} }
@ -405,6 +413,7 @@ impl Wire {
petname: f.petname, petname: f.petname,
onion: f.onion, onion: f.onion,
last_connect_ok: f.last_connect_ok, last_connect_ok: f.last_connect_ok,
pq: f.kem_pk.is_some(),
}) })
} }
@ -1656,6 +1665,17 @@ mod tests {
.block_on(f) .block_on(f)
} }
#[test]
fn a_v2_invite_round_trips_through_decode_invite() {
let onion = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion";
let invite = onionwire::qr::encode(&[7u8; 32], onion, &[1u8; 32], &[9u8; 1184])
.expect("encode v2");
let info = decode_invite(invite).expect("decode v2");
assert_eq!(info.onion, onion);
assert_eq!(info.pubkey_hex.len(), 64);
assert!(info.pq, "a v2 invite carries the ML-KEM key");
}
#[test] #[test]
fn tor_state_of_a_stopped_handle_is_stopped() { fn tor_state_of_a_stopped_handle_is_stopped() {
assert_eq!(stopped_wire().tor_state(), TorState::Stopped); assert_eq!(stopped_wire().tor_state(), TorState::Stopped);

View file

@ -4,8 +4,9 @@ This is the wire protocol. A second implementation should be able to
interoperate from this document without reading the Rust. interoperate from this document without reading the Rust.
It is **not** an IETF RFC. It describes what this repository speaks today It is **not** an IETF RFC. It describes what this repository speaks today
(frame version 1, invite scheme `onionwire:v1`). There has been no public (frame versions 1 and 2, invite schemes `onionwire:v2` (emit) and
third-party audit. Arti onion services are experimental upstream. `onionwire:v1` (decode only)). There has been no public third-party audit.
Arti onion services are experimental upstream.
Related: [threat model](THREAT_MODEL.md), [audit notes](SECURITY_AUDIT.md). Related: [threat model](THREAT_MODEL.md), [audit notes](SECURITY_AUDIT.md).
@ -32,13 +33,20 @@ Each install holds:
- **Identity** — ed25519 keypair. The 32-byte public key **is** the person. - **Identity** — ed25519 keypair. The 32-byte public key **is** the person.
Roster primary key. Displayed as 64 lowercase hex chars (the fingerprint). Roster primary key. Displayed as 64 lowercase hex chars (the fingerprint).
- **Prekey** — x25519 keypair. This is the Noise IK *static*. It is long-lived - **Prekey** — x25519 keypair. This is the Noise IK *static*. It is long-lived
in v1 — rotate it with `F8`, which hard-cuts every stored session. Rotating — rotate it with `F8`, which hard-cuts every stored session. Rotating the
the onion (`F4`) does **not** rotate it. onion (`F4`) does **not** rotate it.
- **KEM key** — ML-KEM-768 (FIPS 203) keypair. The 1184-byte encapsulation key
travels in a v2 invite as `kem=`; the 64-byte decapsulation seed lives in the
SQLCipher store beside `identity_sk`. `F8` rotates it together with the
prekey, with the same hard cut (stored ratchet state is dropped and every
friend re-pastes the invite).
- **Onion** — Tor v3 address. Locator only. Disposable. - **Onion** — Tor v3 address. Locator only. Disposable.
A friend is `{identity_pk, current_onion, current_prekey_pk}`. Pasting the same A friend is `{identity_pk, current_onion, current_prekey_pk, kem_pk?}`. Pasting
identity `k` updates the locator (and prekey) on that row. It never creates a the same identity `k` updates the locator, prekey and KEM key on that row. It
second person. never creates a second person. `kem_pk` is absent only for a friend added from
a legacy `onionwire:v1` invite; such a friend is **classical** (see
[No downgrade](#no-downgrade)).
Petnames, chat history, and the optional Monero wallet RPC are local. They are Petnames, chat history, and the optional Monero wallet RPC are local. They are
not on the wire. not on the wire.
@ -72,11 +80,18 @@ Excess is dropped before handshake. That is availability, not anonymity.
Every Noise handshake message and every ciphertext is wrapped: Every Noise handshake message and every ciphertext is wrapped:
``` ```
uint8 version = 1 uint8 version = 1 (normal) | 2 (PQ handshake prelude)
uint32 length = big-endian body length uint32 length = big-endian body length
uint8 body[length] uint8 body[length]
``` ```
- `version = 1` is Noise msg 1, msg 2, an identity proof, or one application
ciphertext. It is unchanged from v1 of this document.
- `version = 2` is the **PQ handshake prelude**. Its body is `uint16 ct_len`
(big-endian) followed by exactly `ct_len` bytes of ML-KEM-768 ciphertext.
`ct_len` MUST be 1088. The prelude may only be the first frame of a session;
the initiator sends exactly one, then Noise msg 1 with `version = 1`.
`read_frame` (used after the opening frame) rejects `version = 2`.
- `length` MUST be ≤ 65535. Check the length **before** allocating the body. - `length` MUST be ≤ 65535. Check the length **before** allocating the body.
- Other `version` values are a hard fail (close the stream). - Other `version` values are a hard fail (close the stream).
- Length that does not match the bytes on the wire is a hard fail. - Length that does not match the bytes on the wire is a hard fail.
@ -85,21 +100,42 @@ uint8 body[length]
Noise pattern: `Noise_IK_25519_ChaChaPoly_BLAKE2s` Noise pattern: `Noise_IK_25519_ChaChaPoly_BLAKE2s`
Prologue (both sides, before the first handshake message): `onionwire-v1` Prologue (both sides, before the first Noise handshake message):
(13 ASCII bytes, no NUL).
- **Classical** (no PQ prelude, friend row has no `kem_pk`): `onionwire-v1`
(12 ASCII bytes, no NUL).
- **Hybrid** (a PQ prelude was sent/received): the exact byte layout
```
"onionwire-v2" || 0x00 || ct || 0x00 || ss_kem
```
where `onionwire-v2` is 12 ASCII bytes, `ct` is the 1088-byte ML-KEM-768
ciphertext from the prelude, and `ss_kem` is the 32-byte shared secret.
Initiator: `(ct, ss_kem) = ML-KEM-768.Encapsulate(friend.kem_pk)`.
Responder: `ss_kem = ML-KEM-768.Decapsulate(own_dk, ct)`. Both therefore
commit to the ciphertext and to the PQ secret: a modified `ct` changes the
prologue (and decapsulates to implicit-rejection garbage), so the Noise
handshake fails before msg 2.
Handshake payloads are empty. A non-empty decrypted handshake payload is a Handshake payloads are empty. A non-empty decrypted handshake payload is a
hard fail. hard fail.
### Sequence ### Sequence
Initiator knows the responder’s identity pubkey (pinned) and x25519 prekey Initiator knows the responder’s identity pubkey (pinned), x25519 prekey and
from the invite (or roster). (if `kem_pk` is present) ML-KEM key from the invite (or roster).
1. **IK msg 1** — initiator → responder (framed). Responder’s Noise static is 0. **PQ prelude** — only when the responder’s roster row has `kem_pk`:
the invite `spk`. initiator → responder, one `version = 2` frame carrying the ML-KEM
ciphertext. If the row has no `kem_pk`, no prelude is sent and the prologue
is `onionwire-v1`.
1. **IK msg 1** — initiator → responder (framed, `version = 1`). Responder’s
Noise static is the invite `spk`.
2. Responder looks up the remote static in the roster **by prekey**. 2. Responder looks up the remote static in the roster **by prekey**.
Unknown prekey → close. This is how the answerer learns who is calling. Unknown prekey → close. This is how the answerer learns who is calling.
It then compares the friend row with how the session opened (see
[No downgrade](#no-downgrade)) and only then sends msg 2.
3. **IK msg 2** — responder → initiator (framed). 3. **IK msg 2** — responder → initiator (framed).
4. Both sides enter transport mode. Handshake hash `h` is 32 bytes (BLAKE2s). 4. Both sides enter transport mode. Handshake hash `h` is 32 bytes (BLAKE2s).
5. **Identity proof, initiator first** — transport-encrypt a 96-byte proof, 5. **Identity proof, initiator first** — transport-encrypt a 96-byte proof,
@ -129,6 +165,27 @@ ciphertext and closes. The responder decrypts that one frame and closes.
Compromise of the long-term x25519 prekey does not decrypt past transport Compromise of the long-term x25519 prekey does not decrypt past transport
(IK + ephemeral). It does allow future impersonation at the Noise layer until (IK + ephemeral). It does allow future impersonation at the Noise layer until
the peer notices the identity proof failing — so the proof is not optional. the peer notices the identity proof failing — so the proof is not optional.
With a PQ prelude, the transport secrets also mix `ss_kem`; a later
cryptographically relevant quantum adversary that recorded the session still
needs ML-KEM-768 broken to recover the Noise transport keys.
### No downgrade
The rule comes from the roster row, never from what arrives on the wire:
- friend row has `kem_pk` → **always** send the prelude; the responder requires
one. A `version = 1` opening from that peer is rejected with `prelude
required` before msg 2, the identity proofs, and any application frame.
- friend row has no `kem_pk` (added from a legacy v1 invite) → classical
session with the `onionwire-v1` prologue. The UI labels the friend as lacking
PQ protection.
- A prelude is not accepted for a friend row with no `kem_pk`: the responder
rejects it with `unexpected prelude` before msg 2, so the wire cannot upgrade
a classical row. `kem_pk` only enters a row from a signed v2 invite.
A v1-only build dialling a v2 install cannot parse `version = 2` as an opening
frame and hard-fails, and a v2 build will not send a prelude to a v1 peer.
That mixed-fleet break is accepted; there is no fallback path.
## Application plaintext ## Application plaintext
@ -566,28 +623,39 @@ the new invite is the signal.
Not a QR graphic. A single ASCII string, max 4096 characters: Not a QR graphic. A single ASCII string, max 4096 characters:
``` ```
onionwire:v1:k=<64 hex>:o=<v3 onion>:spk=<64 hex>:sig=<128 hex> onionwire:v2:k=<64 hex>:o=<v3 onion>:spk=<64 hex>:kem=<base64url pk>:sig=<128 hex>
``` ```
Field order in the string is not significant; duplicate or unknown fields are Field order in the string is not significant; duplicate or unknown fields are
rejected. `k` is the identity pubkey, `spk` the x25519 prekey, `o` the current rejected. `k` is the identity pubkey, `spk` the x25519 prekey, `o` the current
locator. locator, and `kem` the ML-KEM-768 encapsulation key (1184 bytes) encoded as
unpadded base64url (1579 characters). A v2 invite is about 1.9 KB, still well
under the 4096-character cap.
**Current signature (encode this):** **Current signature (encode this):**
``` ```
ed25519_sign(identity_sk, ed25519_sign(identity_sk,
"onionwire-invite-v1" || 0x00 || k_ascii || 0x00 || o_ascii || 0x00 || spk_ascii) "onionwire-invite-v2" || 0x00 || k_ascii || 0x00 || o_ascii || 0x00 ||
spk_ascii || 0x00 || kem_ascii)
``` ```
`k_ascii` / `spk_ascii` are the hex strings as they appear in the invite `k_ascii` / `spk_ascii` are the hex strings as they appear in the invite
(lowercase). (lowercase); `kem_ascii` is the base64url field value after `kem=`. Because the
signature covers `kem_ascii`, removing the field or substituting a different
key fails verification — that is the anti-strip/anti-substitution property.
**Legacy accept:** a signature over the raw concatenation `k || o || spk` **Legacy accept (`onionwire:v1`):** a v1 invite has no `kem` field. Decode
(no domain tag, no separators) is still accepted on decode so old invites accepts it and yields a friend with no `kem_pk`, i.e. a classical peer. A v1
verify. New invites MUST use the domain-separated form. Do not emit legacy. signature is accepted in either historical form: the tagged
`"onionwire-invite-v1" || 0x00 || k || 0x00 || o || 0x00 || spk` or the raw
concatenation `k || o || spk` (no tag, no separators), so old invites keep
verifying. `onionwire:v2` MUST have `kem=` and MUST verify over the v2 domain;
a v2 body relabelled v1 does not verify.
Unknown `k`: prompt. Same `k`: update onion and prekey only. Encode MUST emit `onionwire:v2` only. Unknown `k`: prompt. Same `k`: update
locator, prekey and KEM key on that row (never a second friend), and drop the
stored ratchet state if either key changed.
## What v1 will not grow into ## What v1 will not grow into
@ -604,8 +672,12 @@ path”). They are out of scope, not postponed.
## Versioning ## Versioning
- Frame `version` 1 and invite `onionwire:v1` are this document. - Frame `version` 1 (normal), frame `version` 2 (PQ prelude), invite
- A new handshake prologue or a new invite scheme is a breaking change. `onionwire:v2` (emit) and invite `onionwire:v1` (decode only) are this
document.
- A new handshake prologue or a new invite scheme is a breaking change. The
hybrid prologue and the prelude are exactly that: v1 peers cannot talk to a
friend that has a `kem_pk`.
- New typed prefixes (`xyz `) are backward compatible if old peers drop them. - New typed prefixes (`xyz `) are backward compatible if old peers drop them.
- The `rat ` frame has its own version byte (`0x01`). A different ratchet frame - The `rat ` frame has its own version byte (`0x01`). A different ratchet frame
layout or a different KDF is a breaking change for chat only: peers that layout or a different KDF is a breaking change for chat only: peers that

View file

@ -20,7 +20,41 @@ A signed `loc` frame (`onion`, `ts`, `sig`) rewrites a friend’s locator **only
## Rotating the prekey is a hard cut, and it is wider than F4 ## Rotating the prekey is a hard cut, and it is wider than F4
`F8` rotates the long-lived signed prekey. The identity key and the onion are unchanged, but the prekey is our Noise static **and** the seed of the bootstrap ratchet epoch, so once it moves nothing is reachable any more: a friend's dial uses the prekey they pinned from your invite, and their stored epoch is derived from the old one. There is no push path for a prekey — it only travels inside a signed invite — so every friend, online or offline, has to F3-paste the new invite before chat works in either direction again. F8 therefore also drops the local ratchet state for every friend, exactly as a peer's own prekey change does. Rotating the prekey shrinks the forward-secrecy window of the long-lived static; it is not a revocation (the old invite holder still learns nothing new, but they also cannot talk to you). `F8` rotates the long-lived signed prekey **and the ML-KEM-768 install key**. The identity key and the onion are unchanged, but the prekey is our Noise static **and** the seed of the bootstrap ratchet epoch, and the KEM key is what peers encapsulate to, so once either moves nothing is reachable any more: a friend's dial uses the prekey and `kem=` they pinned from your invite, and their stored epoch is derived from the old prekey. There is no push path for either key — they only travel inside a signed invite — so every friend, online or offline, has to F3-paste the new invite before chat works in either direction again. F8 therefore also drops the local ratchet state for every friend, exactly as a peer's own prekey change does. Rotating the prekey shrinks the forward-secrecy window of the long-lived static; it is not a revocation (the old invite holder still learns nothing new, but they also cannot talk to you).
## Post-quantum transport does not make messaging post-quantum
Every Noise session to a v2 friend carries an ML-KEM-768 secret. The
initiator sends a `version = 2` prelude with `ct = Encapsulate(friend.kem_pk)`
before Noise msg 1, and both sides mix `(ct, ss_kem)` into the Noise prologue
(`"onionwire-v2" || 0x00 || ct || 0x00 || ss_kem`). A recorded handshake
therefore exposes an X25519 DH and an ML-KEM-768 encapsulation; a future
cryptographically relevant quantum adversary has to break ML-KEM-768 as well as
X25519 to recover the Noise transport keys. That removes the
harvest-now-decrypt-later exposure of the **one-shot transport**.
What this does **not** buy:
- **The chat ratchet stays classical.** Chat messages are `rat ` frames
(Double Ratchet, `docs/PROTOCOL.md`). The **bootstrap epoch is derived only
from the two long-lived X25519 prekeys** (HKDF over their DH, with the
identity pubkeys mixed in), so an adversary who records a `rat ` chain and
later obtains both prekeys can reconstruct epoch 0 even though the Noise
session that carried it was hybrid. Later epoch chains use fresh X25519 DH
steps, which are equally quantum-vulnerable. PQ ratchet steps are a separate
follow-up, not part of this transport work.
- **Identity and invite signatures are ed25519**, still classical. The KEM key
is authenticated by a v1-style ed25519 invite signature; an adversary who can
forge it can also swap `kem=`. Hybrid transport protects confidentiality, not
the long-term authentication root.
- **Legacy friends get nothing.** A friend added from an `onionwire:v1` invite
has no `kem_pk`; sessions to them are the old classical `onionwire-v1`
prologue, and the UI labels that friend as lacking PQ protection. The choice
is derived from the roster row, never from the wire: a `kem_pk` friend
rejects a prelude-less session with `prelude required` before any application
frame, so an active attacker cannot downgrade it.
- **Mixed-version fleets break.** A v1-only build cannot open a session with a
v2 friend; that is accepted rather than adding a fallback path.
## Your store is encrypted ## Your store is encrypted

View file

@ -1,6 +1,9 @@
use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
pub const VERSION: u8 = 1; pub const VERSION: u8 = 1;
/// PQ handshake prelude. Body is `uint16 ct_len` (big-endian) followed by
/// exactly `ct_len` bytes. Only the opening frame of a session may use it.
pub const VERSION_PRELUDE: u8 = 2;
pub const MAX_FRAME: usize = 65535; pub const MAX_FRAME: usize = 65535;
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
@ -53,11 +56,65 @@ pub async fn write_frame<W: AsyncWrite + Unpin>(w: &mut W, body: &[u8]) -> Resul
} }
pub async fn read_frame<R: AsyncRead + Unpin>(r: &mut R) -> Result<Vec<u8>> { pub async fn read_frame<R: AsyncRead + Unpin>(r: &mut R) -> Result<Vec<u8>> {
let (version, body) = read_versioned(r).await?;
if version != VERSION {
return Err(Error("bad version".into()));
}
Ok(body)
}
/// First frame of a handshake. Version 1 is Noise msg 1 (classical). Version 2
/// is the PQ prelude; the ciphertext is exactly `ct_len` bytes and must be the
/// ML-KEM-768 ciphertext length.
pub enum Opening {
Classical(Vec<u8>),
Prelude(Vec<u8>),
}
pub async fn read_opening<R: AsyncRead + Unpin>(r: &mut R) -> Result<Opening> {
let (version, body) = read_versioned(r).await?;
match version {
VERSION => Ok(Opening::Classical(body)),
VERSION_PRELUDE => Ok(Opening::Prelude(parse_prelude(&body)?)),
_ => Err(Error("bad version".into())),
}
}
pub async fn write_prelude<W: AsyncWrite + Unpin>(w: &mut W, ct: &[u8]) -> Result<()> {
if ct.len() > u16::MAX as usize {
return Err(Error("frame too large".into()));
}
let mut body = Vec::with_capacity(2 + ct.len());
body.extend_from_slice(&(ct.len() as u16).to_be_bytes());
body.extend_from_slice(ct);
let framed = encode_version(VERSION_PRELUDE, &body)?;
w.write_all(&framed)
.await
.map_err(|e| Error(e.to_string()))?;
w.flush().await.map_err(|e| Error(e.to_string()))
}
pub fn parse_prelude(body: &[u8]) -> Result<Vec<u8>> {
if body.len() < 2 {
return Err(Error("short frame".into()));
}
let ct_len = u16::from_be_bytes(body[..2].try_into().expect("2 bytes")) as usize;
if body.len() != 2 + ct_len {
return Err(Error("length mismatch".into()));
}
if ct_len != crate::kem::CT_LEN {
return Err(Error("bad prelude".into()));
}
Ok(body[2..].to_vec())
}
async fn read_versioned<R: AsyncRead + Unpin>(r: &mut R) -> Result<(u8, Vec<u8>)> {
let mut hdr = [0u8; 5]; let mut hdr = [0u8; 5];
r.read_exact(&mut hdr) r.read_exact(&mut hdr)
.await .await
.map_err(|e| Error(e.to_string()))?; .map_err(|e| Error(e.to_string()))?;
if hdr[0] != VERSION { let version = hdr[0];
if version != VERSION && version != VERSION_PRELUDE {
return Err(Error("bad version".into())); return Err(Error("bad version".into()));
} }
let len = u32::from_be_bytes(hdr[1..5].try_into().expect("4 bytes")) as usize; let len = u32::from_be_bytes(hdr[1..5].try_into().expect("4 bytes")) as usize;
@ -68,5 +125,16 @@ pub async fn read_frame<R: AsyncRead + Unpin>(r: &mut R) -> Result<Vec<u8>> {
r.read_exact(&mut body) r.read_exact(&mut body)
.await .await
.map_err(|e| Error(e.to_string()))?; .map_err(|e| Error(e.to_string()))?;
Ok(body) Ok((version, body))
}
fn encode_version(version: u8, body: &[u8]) -> Result<Vec<u8>> {
if body.len() > MAX_FRAME {
return Err(Error("frame too large".into()));
}
let mut out = Vec::with_capacity(5 + body.len());
out.push(version);
out.extend_from_slice(&(body.len() as u32).to_be_bytes());
out.extend_from_slice(body);
Ok(out)
} }

96
src/kem.rs Normal file
View file

@ -0,0 +1,96 @@
//! ML-KEM-768 (FIPS 203) install key.
//!
//! The decapsulation key is stored as the 64-byte seed (`DecapsulationKey::to_seed`),
//! the form the crate prefers. The 1184-byte encapsulation key is what an invite
//! carries. Ciphertext is 1088 bytes; the shared secret is 32.
use ml_kem::kem::{Decapsulate, Encapsulate, Kem};
use ml_kem::{DecapsulationKey768, EncapsulationKey768, KeyExport, MlKem768, Seed};
use zeroize::Zeroizing;
pub const PK_LEN: usize = 1184;
pub const CT_LEN: usize = 1088;
pub const SS_LEN: usize = 32;
pub const SEED_LEN: usize = 64;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub struct Error(String);
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for Error {}
/// A freshly generated install key. `seed` wipes on drop.
pub struct Keypair {
pub seed: Zeroizing<[u8; SEED_LEN]>,
pub pk: [u8; PK_LEN],
}
pub fn generate() -> Keypair {
let (dk, ek) = MlKem768::generate_keypair();
let seed_arr = dk.to_seed().expect("generate_keypair yields a seed");
let pk_arr = ek.to_bytes();
let mut seed = Zeroizing::new([0u8; SEED_LEN]);
let mut pk = [0u8; PK_LEN];
seed.copy_from_slice(seed_arr.as_slice());
pk.copy_from_slice(pk_arr.as_slice());
Keypair { seed, pk }
}
/// Canonical encapsulation-key bytes. Rejects a length or a key the crate
/// will not load, so a garbage `kem=` never becomes a friend row.
pub fn encode_pk(pk: &[u8]) -> Result<Vec<u8>> {
let ek = encapsulation_key(pk)?;
Ok(ek.to_bytes().as_slice().to_vec())
}
pub fn decode_pk(bytes: &[u8]) -> Result<Vec<u8>> {
encode_pk(bytes)
}
pub fn encapsulate(pk: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
let ek = encapsulation_key(pk)?;
let (ct, ss) = ek.encapsulate();
Ok((ct.as_slice().to_vec(), ss.as_slice().to_vec()))
}
/// Ciphertext bytes. Length is the only check: ML-KEM decapsulation of a
/// wrong ciphertext does not error (implicit rejection), so a bad ct is
/// caught by the handshake prologue, not here.
pub fn encode_ct(ct: &[u8]) -> Result<Vec<u8>> {
if ct.len() != CT_LEN {
return Err(Error("ct length".into()));
}
Ok(ct.to_vec())
}
pub fn decode_ct(bytes: &[u8]) -> Result<Vec<u8>> {
encode_ct(bytes)
}
pub fn decapsulate(seed: &[u8], ct: &[u8]) -> Result<Vec<u8>> {
if ct.len() != CT_LEN {
return Err(Error("ct length".into()));
}
let seed_arr = Seed::try_from(seed).map_err(|_| Error("seed length".into()))?;
let dk = DecapsulationKey768::from_seed(seed_arr);
let ss = dk
.decapsulate_slice(ct)
.map_err(|_| Error("ct length".into()))?;
Ok(ss.as_slice().to_vec())
}
fn encapsulation_key(pk: &[u8]) -> Result<EncapsulationKey768> {
if pk.len() != PK_LEN {
return Err(Error("pk length".into()));
}
let key = ml_kem::kem::Key::<EncapsulationKey768>::try_from(pk)
.map_err(|_| Error("pk length".into()))?;
EncapsulationKey768::new(&key).map_err(|_| Error("invalid encapsulation key".into()))
}

View file

@ -4,6 +4,7 @@ pub mod dispatch;
pub mod file; pub mod file;
pub mod frame; pub mod frame;
pub mod hs; pub mod hs;
pub mod kem;
pub mod loc; pub mod loc;
pub mod node; pub mod node;
pub mod outbox; pub mod outbox;

View file

@ -427,7 +427,7 @@ impl Node {
pub fn qr_payload(&self) -> Result<String, String> { pub fn qr_payload(&self) -> Result<String, String> {
let k = self.keys()?; let k = self.keys()?;
qr::encode(&k.identity_sk, &self.onion(), &k.prekey_pk).map_err(|e| e.to_string()) qr::encode(&k.identity_sk, &self.onion(), &k.prekey_pk, &k.kem_pk).map_err(|e| e.to_string())
} }
pub fn write_backup(&self, path: &str, passphrase: &str) -> Result<(), String> { pub fn write_backup(&self, path: &str, passphrase: &str) -> Result<(), String> {
@ -456,6 +456,10 @@ impl Node {
pub fn restore_backup(&self, path: &str, passphrase: &str) -> Result<(), String> { pub fn restore_backup(&self, path: &str, passphrase: &str) -> Result<(), String> {
let blob = std::fs::read(path).map_err(|e| e.to_string())?; let blob = std::fs::read(path).map_err(|e| e.to_string())?;
let k = crate::backup::open(passphrase, &blob)?; let k = crate::backup::open(passphrase, &blob)?;
let (kem_seed, kem_pk) = {
let cur = self.keys()?;
(cur.kem_seed, cur.kem_pk)
};
self.store self.store
.lock() .lock()
.map_err(|e| e.to_string())? .map_err(|e| e.to_string())?
@ -466,6 +470,11 @@ impl Node {
identity_pk: k.identity_pk, identity_pk: k.identity_pk,
prekey_sk: k.prekey_sk, prekey_sk: k.prekey_sk,
prekey_pk: k.prekey_pk, prekey_pk: k.prekey_pk,
// Backup blob is still the classical identity+prekey bundle. The
// KEM seed stays the one already in this store; friends who pinned
// a different encapsulation key have to re-paste.
kem_seed,
kem_pk,
}; };
Ok(()) Ok(())
} }
@ -477,21 +486,30 @@ impl Node {
pub fn add_friend_payload(&self, p: &qr::QrPayload) -> Result<(), String> { pub fn add_friend_payload(&self, p: &qr::QrPayload) -> Result<(), String> {
let store = self.store.lock().map_err(|e| e.to_string())?; let store = self.store.lock().map_err(|e| e.to_string())?;
let prekey_changed = store let existing = store
.get_friend(&p.pubkey) .get_friend(&p.pubkey)
.map_err(|e| e.to_string())? .map_err(|e| e.to_string())?;
let prekey_changed = existing
.as_ref()
.map(|f| f.prekey != p.signed_prekey) .map(|f| f.prekey != p.signed_prekey)
.unwrap_or(false); .unwrap_or(false);
let kem_changed = existing
.as_ref()
.map(|f| f.kem_pk.as_deref() != p.kem_pk.as_deref())
.unwrap_or(false);
store store
.upsert_friend(&p.pubkey, &p.onion, None) .upsert_friend(&p.pubkey, &p.onion, None)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
store store
.set_friend_prekey(&p.pubkey, &p.signed_prekey) .set_friend_prekey(&p.pubkey, &p.signed_prekey)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
if prekey_changed { store
.set_friend_kem(&p.pubkey, p.kem_pk.as_deref())
.map_err(|e| e.to_string())?;
if prekey_changed || kem_changed {
// The bootstrap epoch is derived from the peers' static prekey DH, // The bootstrap epoch is derived from the peers' static prekey DH,
// so a refreshed invite makes the stored ratchet state unusable on // and a new KEM key is the same hard cut as F8: the stored ratchet
// both sides. Drop it: the next frame rebuilds a fresh state. // state is unusable. Drop it; the next frame rebuilds a fresh state.
store.clear_ratchet(&p.pubkey).map_err(|e| e.to_string())?; store.clear_ratchet(&p.pubkey).map_err(|e| e.to_string())?;
} }
Ok(()) Ok(())
@ -1216,14 +1234,15 @@ impl Node {
) )
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
let pt = profile::encode(&prf); let pt = profile::encode(&prf);
let (onion, prekey) = { let (onion, prekey, kem) = {
let f = self.friend(friend_pk)?; let f = self.friend(friend_pk)?;
if f.prekey.len() != 32 { if f.prekey.len() != 32 {
return Err("friend missing prekey".into()); return Err("friend missing prekey".into());
} }
(f.onion, f.prekey) (f.onion, f.prekey, f.kem_pk)
}; };
self.try_send(&onion, friend_pk, &prekey, &pt).await self.try_send(&onion, friend_pk, &prekey, &pt, kem.as_deref())
.await
} }
/// Sign an invoice with this node's identity key. /// Sign an invoice with this node's identity key.
@ -1719,14 +1738,15 @@ impl Node {
async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> { async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
self.ensure_running()?; self.ensure_running()?;
let (onion, prekey) = { let (onion, prekey, kem) = {
let f = self.friend(friend_pk)?; let f = self.friend(friend_pk)?;
if f.prekey.len() != 32 { if f.prekey.len() != 32 {
return Err("friend missing prekey".into()); return Err("friend missing prekey".into());
} }
(f.onion, f.prekey) (f.onion, f.prekey, f.kem_pk)
}; };
self.try_send(&onion, friend_pk, &prekey, plaintext).await self.try_send(&onion, friend_pk, &prekey, plaintext, kem.as_deref())
.await
} }
/// Dial a peer's onion. Success is evidence the peer is up, which is one of /// Dial a peer's onion. Success is evidence the peer is up, which is one of
@ -1801,7 +1821,7 @@ impl Node {
let mut notified = 0; let mut notified = 0;
for f in &friends { for f in &friends {
if self if self
.push_loc(&f.pubkey, &f.onion, &f.prekey, &loc_pt) .push_loc(&f.pubkey, &f.onion, &f.prekey, f.kem_pk.as_deref(), &loc_pt)
.await .await
.is_ok() .is_ok()
{ {
@ -1815,17 +1835,18 @@ impl Node {
}) })
} }
/// Rotate the long-lived signed prekey (F8). Hard cut, like the locator /// Rotate the long-lived signed prekey and the ML-KEM-768 key together (F8).
/// rotate: the prekey is our Noise static and the bootstrap ratchet epoch is /// Hard cut, like the locator rotate: the prekey is our Noise static, the
/// KEM key is what peers encapsulate to, and the bootstrap ratchet epoch is
/// derived from the prekey DH, so every stored session is dead the moment /// derived from the prekey DH, so every stored session is dead the moment
/// this returns and every friend has to F3-paste the new invite. Nothing is /// this returns and every friend has to F3-paste the new invite. Nothing is
/// pushed to peers — a new prekey only travels inside a signed invite. The /// pushed to peers — a new prekey or KEM key only travels inside a signed
/// identity key (and therefore the fingerprint) does not move; the caller /// invite. The identity key (and therefore the fingerprint) does not move.
/// re-encodes the F2 invite around the returned pubkey.
pub fn rotate_prekey(&self) -> Result<[u8; 32], String> { pub fn rotate_prekey(&self) -> Result<[u8; 32], String> {
let mut k = self.keys()?; let mut k = self.keys()?;
let sk = StaticSecret::random_from_rng(OsRng); let sk = StaticSecret::random_from_rng(OsRng);
let pk = X25519Public::from(&sk).to_bytes(); let pk = X25519Public::from(&sk).to_bytes();
let kem_kp = crate::kem::generate();
{ {
let store = self.store.lock().map_err(|e| e.to_string())?; let store = self.store.lock().map_err(|e| e.to_string())?;
// `replace_identity_keys` rewrites the prekey columns too; the // `replace_identity_keys` rewrites the prekey columns too; the
@ -1833,12 +1854,17 @@ impl Node {
store store
.replace_identity_keys(&k.identity_sk, &k.identity_pk, &sk.to_bytes(), &pk) .replace_identity_keys(&k.identity_sk, &k.identity_pk, &sk.to_bytes(), &pk)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
store
.set_kem_keys(&kem_kp.seed[..], &kem_kp.pk)
.map_err(|e| e.to_string())?;
for f in store.list_friends().map_err(|e| e.to_string())? { for f in store.list_friends().map_err(|e| e.to_string())? {
store.clear_ratchet(&f.pubkey).map_err(|e| e.to_string())?; store.clear_ratchet(&f.pubkey).map_err(|e| e.to_string())?;
} }
} }
k.prekey_sk = sk.to_bytes(); k.prekey_sk = sk.to_bytes();
k.prekey_pk = pk; k.prekey_pk = pk;
k.kem_seed = *kem_kp.seed;
k.kem_pk = kem_kp.pk;
*self.keys.lock().map_err(|e| e.to_string())? = k; *self.keys.lock().map_err(|e| e.to_string())? = k;
Ok(pk) Ok(pk)
} }
@ -1907,6 +1933,7 @@ impl Node {
friend_pk: &[u8], friend_pk: &[u8],
onion: &str, onion: &str,
prekey: &[u8], prekey: &[u8],
remote_kem: Option<&[u8]>,
loc_pt: &[u8], loc_pt: &[u8],
) -> Result<(), String> { ) -> Result<(), String> {
if prekey.len() != 32 { if prekey.len() != 32 {
@ -1915,7 +1942,10 @@ impl Node {
let deadline = Instant::now() + Duration::from_secs(180); let deadline = Instant::now() + Duration::from_secs(180);
let mut last = None::<String>; let mut last = None::<String>;
while Instant::now() < deadline { while Instant::now() < deadline {
match self.try_send(onion, friend_pk, prekey, loc_pt).await { match self
.try_send(onion, friend_pk, prekey, loc_pt, remote_kem)
.await
{
Ok(()) => return Ok(()), Ok(()) => return Ok(()),
Err(e) if e.contains("fingerprint mismatch") => return Err(e), Err(e) if e.contains("fingerprint mismatch") => return Err(e),
Err(e) => last = Some(e), Err(e) => last = Some(e),
@ -1931,10 +1961,11 @@ impl Node {
pinned_id: &[u8], pinned_id: &[u8],
remote_prekey: &[u8], remote_prekey: &[u8],
plaintext: &[u8], plaintext: &[u8],
remote_kem: Option<&[u8]>,
) -> Result<(), String> { ) -> Result<(), String> {
self.outbox self.outbox
.deliverer() .deliverer()
.deliver(onion, pinned_id, remote_prekey, plaintext) .deliver(onion, pinned_id, remote_prekey, plaintext, remote_kem)
.await .await
} }
@ -1948,7 +1979,10 @@ impl Node {
let Ok(g) = store.lock() else { let Ok(g) = store.lock() else {
return None; return None;
}; };
g.get_friend_by_prekey(spk).ok().flatten().map(|f| f.pubkey) g.get_friend_by_prekey(spk).ok().flatten().map(|f| session::PeerAuth {
identity: f.pubkey,
kem_pk: f.kem_pk,
})
}) })
.await .await
.map_err(session_err)?; .map_err(session_err)?;
@ -2577,6 +2611,7 @@ pub(crate) mod tests {
_pinned_id: &'a [u8], _pinned_id: &'a [u8],
_prekey: &'a [u8], _prekey: &'a [u8],
_payload: &'a [u8], _payload: &'a [u8],
_remote_kem: Option<&'a [u8]>,
) -> crate::outbox::BoxFut<'a, Result<(), String>> { ) -> crate::outbox::BoxFut<'a, Result<(), String>> {
Box::pin(async { Err("connect peer.onion:80: timed out".to_string()) }) Box::pin(async { Err("connect peer.onion:80: timed out".to_string()) })
} }
@ -2687,18 +2722,33 @@ pub(crate) mod tests {
node.keys.lock().unwrap().prekey_pk node.keys.lock().unwrap().prekey_pk
} }
fn node_kem_pk(node: &Node) -> [u8; crate::kem::PK_LEN] {
node.keys.lock().unwrap().kem_pk
}
/// One peer→node dial, end to end: a real Noise IK handshake and one /// One peer→node dial, end to end: a real Noise IK handshake and one
/// already-encoded frame over an in-memory stream, into `handle_incoming`. /// already-encoded frame over an in-memory stream, into `handle_incoming`.
async fn deliver_frame(node: &Node, peer: &Keys, frame: &[u8]) -> Result<(), String> { async fn deliver_frame(
node: &Node,
peer: &Keys,
frame: &[u8],
remote_kem: Option<&[u8]>,
) -> Result<(), String> {
let node_pk = node.identity_pk(); let node_pk = node.identity_pk();
let node_prekey = node_prekey(node); let node_prekey = node_prekey(node);
let (client_side, server_side) = tokio::io::duplex(64 * 1024); let (client_side, server_side) = tokio::io::duplex(64 * 1024);
let send = async { let send = async {
let mut stream = Duplex(client_side); let mut stream = Duplex(client_side);
let mut sess = session::handshake_initiator(&mut stream, peer, &node_pk, &node_prekey) let mut sess = session::handshake_initiator(
.await &mut stream,
.map_err(|e| e.into_message())?; peer,
&node_pk,
&node_prekey,
remote_kem,
)
.await
.map_err(|e| e.into_message())?;
let ct = sess.encrypt(frame).map_err(|e| e.into_message())?; let ct = sess.encrypt(frame).map_err(|e| e.into_message())?;
frame::write_frame(&mut stream, &ct) frame::write_frame(&mut stream, &ct)
.await .await
@ -2709,8 +2759,13 @@ pub(crate) mod tests {
node.handle_incoming(&mut stream).await node.handle_incoming(&mut stream).await
}; };
let (sent, received) = futures::join!(send, receive); let (sent, received) = futures::join!(send, receive);
sent?; // The responder's error is the diagnostic one (e.g. a downgrade
received // rejection); the initiator only sees the stream drop.
match (sent, received) {
(_, Err(e)) => Err(e),
(Err(e), Ok(())) => Err(e),
(Ok(()), Ok(())) => Ok(()),
}
} }
fn chat_lines(node: &Node, peer: &Keys) -> Vec<(String, String)> { fn chat_lines(node: &Node, peer: &Keys) -> Vec<(String, String)> {
@ -2792,7 +2847,9 @@ pub(crate) mod tests {
let frame = let frame =
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"hi bob").expect("encode"); encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"hi bob").expect("encode");
deliver_frame(&node, &peer, &frame).await.expect("receive"); deliver_frame(&node, &peer, &frame, None)
.await
.expect("receive");
assert_eq!( assert_eq!(
chat_lines(&node, &peer), chat_lines(&node, &peer),
@ -2801,6 +2858,74 @@ pub(crate) mod tests {
); );
} }
#[tokio::test]
async fn pq_prelude_session_round_trips_a_real_rat_frame() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
let peer = Keys::generate();
{
let store = node.store.lock().unwrap();
befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion");
store
.set_friend_kem(&peer.identity_pk, Some(&peer.kem_pk))
.expect("friend kem");
}
let peer_store =
Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store");
{
let nk = node_kem_pk(&node);
befriend(&peer_store, &node.identity_pk(), &node_prekey(&node), "node.onion");
peer_store
.set_friend_kem(&node.identity_pk(), Some(&nk))
.expect("node kem");
}
let frame =
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"pq hello").expect("encode");
let nk = node_kem_pk(&node);
deliver_frame(&node, &peer, &frame, Some(&nk))
.await
.expect("PQ handshake + rat frame");
assert_eq!(
chat_lines(&node, &peer),
vec![("in".to_string(), "pq hello".to_string())],
"a real ratchet frame survived the hybrid prelude"
);
}
#[tokio::test]
async fn a_prelude_less_session_against_a_kem_friend_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
let peer = Keys::generate();
{
let store = node.store.lock().unwrap();
befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion");
store
.set_friend_kem(&peer.identity_pk, Some(&peer.kem_pk))
.expect("friend kem");
}
let peer_store =
Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store");
befriend(&peer_store, &node.identity_pk(), &node_prekey(&node), "node.onion");
let frame =
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"downgrade").expect("encode");
let err = deliver_frame(&node, &peer, &frame, None)
.await
.expect_err("a classical session to a KEM friend must fail");
assert!(
err.contains(session::PRELUDE_REQUIRED),
"expected a hard downgrade rejection, got: {err}"
);
assert!(
chat_lines(&node, &peer).is_empty(),
"no application frame may be accepted after a downgrade"
);
}
#[tokio::test] #[tokio::test]
async fn the_receive_path_keeps_arrival_order_and_drops_replays_and_garbage() { async fn the_receive_path_keeps_arrival_order_and_drops_replays_and_garbage() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
@ -2830,17 +2955,17 @@ pub(crate) mod tests {
.collect(); .collect();
// Arrival order 2, 0, 1 — the ratchet holds the two it has not seen. // Arrival order 2, 0, 1 — the ratchet holds the two it has not seen.
deliver_frame(&node, &peer, &frames[2]).await.unwrap(); deliver_frame(&node, &peer, &frames[2], None).await.unwrap();
deliver_frame(&node, &peer, &frames[0]).await.unwrap(); deliver_frame(&node, &peer, &frames[0], None).await.unwrap();
deliver_frame(&node, &peer, &frames[1]).await.unwrap(); deliver_frame(&node, &peer, &frames[1], None).await.unwrap();
// A replay of an already-consumed frame, and a corrupted one: both are // A replay of an already-consumed frame, and a corrupted one: both are
// dropped inside `handle_incoming` without a chat row and without // dropped inside `handle_incoming` without a chat row and without
// wedging the session. // wedging the session.
deliver_frame(&node, &peer, &frames[0]).await.unwrap(); deliver_frame(&node, &peer, &frames[0], None).await.unwrap();
let mut corrupt = frames[1].clone(); let mut corrupt = frames[1].clone();
let last = corrupt.len() - 1; let last = corrupt.len() - 1;
corrupt[last] ^= 0x01; corrupt[last] ^= 0x01;
deliver_frame(&node, &peer, &corrupt).await.unwrap(); deliver_frame(&node, &peer, &corrupt, None).await.unwrap();
assert_eq!( assert_eq!(
chat_lines(&node, &peer), chat_lines(&node, &peer),
@ -2864,6 +2989,7 @@ pub(crate) mod tests {
_pinned_id: &'a [u8], _pinned_id: &'a [u8],
_prekey: &'a [u8], _prekey: &'a [u8],
_payload: &'a [u8], _payload: &'a [u8],
_remote_kem: Option<&'a [u8]>,
) -> crate::outbox::BoxFut<'a, Result<(), String>> { ) -> crate::outbox::BoxFut<'a, Result<(), String>> {
Box::pin(async { Ok(()) }) Box::pin(async { Ok(()) })
} }
@ -2997,6 +3123,7 @@ pub(crate) mod tests {
let peer = Keys::generate(); let peer = Keys::generate();
let old_identity = node.identity_pk(); let old_identity = node.identity_pk();
let old_prekey = node_prekey(&node); let old_prekey = node_prekey(&node);
let old_kem = node_kem_pk(&node);
*node.onion.lock().unwrap() = format!("{}.onion", "a".repeat(56)); *node.onion.lock().unwrap() = format!("{}.onion", "a".repeat(56));
{ {
let store = node.store.lock().unwrap(); let store = node.store.lock().unwrap();
@ -3010,6 +3137,11 @@ pub(crate) mod tests {
assert_ne!(new_prekey, old_prekey, "the prekey must actually change"); assert_ne!(new_prekey, old_prekey, "the prekey must actually change");
assert_eq!(node_prekey(&node), new_prekey, "the live keys follow"); assert_eq!(node_prekey(&node), new_prekey, "the live keys follow");
assert_ne!(
node_kem_pk(&node),
old_kem,
"F8 rotates the ML-KEM key with the prekey"
);
assert_eq!( assert_eq!(
node.identity_pk(), node.identity_pk(),
old_identity, old_identity,
@ -3022,6 +3154,11 @@ pub(crate) mod tests {
new_prekey.to_vec(), new_prekey.to_vec(),
"the self row carries the new prekey" "the self row carries the new prekey"
); );
assert_eq!(
store.self_identity().unwrap().kem_pk,
node_kem_pk(&node).to_vec(),
"the self row carries the rotated KEM key"
);
assert!( assert!(
store.load_ratchet(&peer.identity_pk).unwrap().is_none(), store.load_ratchet(&peer.identity_pk).unwrap().is_none(),
"the bootstrap epoch is prekey-bound, so the stored state is stale" "the bootstrap epoch is prekey-bound, so the stored state is stale"
@ -3030,6 +3167,11 @@ pub(crate) mod tests {
let payload = qr::decode(&node.qr_payload().expect("re-encode the invite")) let payload = qr::decode(&node.qr_payload().expect("re-encode the invite"))
.expect("the re-encoded invite decodes"); .expect("the re-encoded invite decodes");
assert_eq!(payload.signed_prekey, new_prekey.to_vec()); assert_eq!(payload.signed_prekey, new_prekey.to_vec());
assert_eq!(
payload.kem_pk.as_deref(),
Some(&node_kem_pk(&node)[..]),
"the new invite carries the rotated KEM key"
);
assert_eq!( assert_eq!(
payload.pubkey, payload.pubkey,
old_identity.to_vec(), old_identity.to_vec(),

View file

@ -21,6 +21,10 @@ use crate::store::Store;
pub use crate::store::{OutboxEntry, OutboxStatus}; pub use crate::store::{OutboxEntry, OutboxStatus};
/// Where one dial goes: locator, Noise static, and the friend's ML-KEM key
/// (`None` = legacy v1 friend, classical session).
type Target = (String, Vec<u8>, Option<Vec<u8>>);
/// First retry waits this long. /// First retry waits this long.
pub const BACKOFF_START_SECS: i64 = 30; pub const BACKOFF_START_SECS: i64 = 30;
/// Backoff never sleeps longer than this. /// Backoff never sleeps longer than this.
@ -50,6 +54,8 @@ const PERMANENT_ERRORS: &[&str] = &[
"fingerprint mismatch", "fingerprint mismatch",
"bad identity proof", "bad identity proof",
"unexpected handshake payload", "unexpected handshake payload",
"prelude required",
"unexpected prelude",
"frame too large", "frame too large",
"bad version", "bad version",
"length mismatch", "length mismatch",
@ -69,6 +75,7 @@ pub trait Deliverer: Send + Sync {
pinned_id: &'a [u8], pinned_id: &'a [u8],
prekey: &'a [u8], prekey: &'a [u8],
plaintext: &'a [u8], plaintext: &'a [u8],
remote_kem: Option<&'a [u8]>,
) -> BoxFut<'a, Result<(), String>>; ) -> BoxFut<'a, Result<(), String>>;
} }
@ -92,6 +99,7 @@ impl Deliverer for ArtiDeliverer {
pinned_id: &'a [u8], pinned_id: &'a [u8],
prekey: &'a [u8], prekey: &'a [u8],
plaintext: &'a [u8], plaintext: &'a [u8],
remote_kem: Option<&'a [u8]>,
) -> BoxFut<'a, Result<(), String>> { ) -> BoxFut<'a, Result<(), String>> {
Box::pin(async move { Box::pin(async move {
let mut stream = self let mut stream = self
@ -100,7 +108,7 @@ impl Deliverer for ArtiDeliverer {
.await .await
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?; .map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
let mut sess = let mut sess =
session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey) session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey, remote_kem)
.await .await
.map_err(|e| e.into_message())?; .map_err(|e| e.into_message())?;
let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?; let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?;
@ -172,9 +180,12 @@ impl Outbox {
plaintext: &[u8], plaintext: &[u8],
payload: Option<&[u8]>, payload: Option<&[u8]>,
) -> Result<OutboxStatus, String> { ) -> Result<OutboxStatus, String> {
let (onion, prekey) = self.target(friend_pk)?; let (onion, prekey, kem) = self.target(friend_pk)?;
let wire = payload.unwrap_or(plaintext); let wire = payload.unwrap_or(plaintext);
match self.deliverer.deliver(&onion, friend_pk, &prekey, wire).await { match self
.deliverer
.deliver(&onion, friend_pk, &prekey, wire, kem.as_deref())
.await {
Ok(()) => { Ok(()) => {
self.store()?.append_message(friend_pk, "out", plaintext)?; self.store()?.append_message(friend_pk, "out", plaintext)?;
Ok(OutboxStatus::Sent) Ok(OutboxStatus::Sent)
@ -266,7 +277,7 @@ impl Outbox {
let mut out = Vec::with_capacity(rows.len()); let mut out = Vec::with_capacity(rows.len());
for entry in rows { for entry in rows {
self.store()?.mark_outbox_sending(entry.id, now)?; self.store()?.mark_outbox_sending(entry.id, now)?;
let (onion, prekey) = match self.target(&entry.friend_pk) { let (onion, prekey, kem) = match self.target(&entry.friend_pk) {
Ok(t) => t, Ok(t) => t,
Err(e) => { Err(e) => {
self.store()?.mark_outbox_failed(entry.id, now, &e)?; self.store()?.mark_outbox_failed(entry.id, now, &e)?;
@ -282,6 +293,7 @@ impl Outbox {
&prekey, &prekey,
// Chat stores its frame here; everything else sends its body. // Chat stores its frame here; everything else sends its body.
entry.payload.as_deref().unwrap_or(&entry.body), entry.payload.as_deref().unwrap_or(&entry.body),
kem.as_deref(),
) )
.await; .await;
let status = match result { let status = match result {
@ -311,9 +323,10 @@ impl Outbox {
Ok(out) Ok(out)
} }
/// Friend's current locator + Noise static. Missing prekey means the invite /// Friend's current locator, Noise static, and KEM encapsulation key.
/// was never completed — retrying cannot fix that, so it is fatal. /// Missing prekey means the invite was never completed — retrying cannot
fn target(&self, friend_pk: &[u8]) -> Result<(String, Vec<u8>), String> { /// fix that, so it is fatal. `None` kem is a legacy v1 friend.
fn target(&self, friend_pk: &[u8]) -> Result<Target, String> {
let store = self.store()?; let store = self.store()?;
let f = store let f = store
.get_friend(friend_pk) .get_friend(friend_pk)
@ -322,7 +335,7 @@ impl Outbox {
if f.prekey.len() != 32 { if f.prekey.len() != 32 {
return Err("friend missing prekey".into()); return Err("friend missing prekey".into());
} }
Ok((f.onion, f.prekey)) Ok((f.onion, f.prekey, f.kem_pk))
} }
fn store(&self) -> Result<MutexGuard<'_, Store>, String> { fn store(&self) -> Result<MutexGuard<'_, Store>, String> {

193
src/qr.rs
View file

@ -1,6 +1,8 @@
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use zeroize::Zeroizing; use zeroize::Zeroizing;
use crate::kem;
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)] #[derive(Debug)]
@ -19,19 +21,33 @@ pub struct QrPayload {
pub pubkey: Vec<u8>, pub pubkey: Vec<u8>,
pub onion: String, pub onion: String,
pub signed_prekey: Vec<u8>, pub signed_prekey: Vec<u8>,
/// `None` for a legacy `onionwire:v1` invite (classical friend). `Some`
/// is the 1184-byte ML-KEM-768 encapsulation key from a v2 invite.
pub kem_pk: Option<Vec<u8>>,
} }
/// Cap invite text before hex decode. Honest v1 is a few hundred bytes. /// Cap invite text before decode. A v2 invite is ~1.9 KB; 4096 still holds.
const MAX_INVITE: usize = 4096; const MAX_INVITE: usize = 4096;
const HEX_K: usize = 64; const HEX_K: usize = 64;
const HEX_SPK: usize = 64; const HEX_SPK: usize = 64;
const HEX_SIG: usize = 128; const HEX_SIG: usize = 128;
/// `onionwire:v1:k={pubkey_hex}:o={v3onion}:spk={signed_prekey}:sig={sign(v2)}` /// Encode a v2 invite. v1 is decode-only.
pub fn encode(identity_sk: &[u8], onion: &str, signed_prekey: &[u8]) -> Result<String> { ///
/// `kem=` is base64url, unpadded, of the 1184-byte encapsulation key.
/// Signature domain: `onionwire-invite-v2 || 0x00 || k || 0x00 || o || 0x00 || spk || 0x00 || kem`.
pub fn encode(
identity_sk: &[u8],
onion: &str,
signed_prekey: &[u8],
kem_pk: &[u8],
) -> Result<String> {
if signed_prekey.len() != 32 { if signed_prekey.len() != 32 {
return Err(Error("spk must be 32 bytes".into())); return Err(Error("spk must be 32 bytes".into()));
} }
if kem_pk.len() != kem::PK_LEN {
return Err(Error("kem must be 1184 bytes".into()));
}
if !is_v3_onion(onion) { if !is_v3_onion(onion) {
return Err(Error("o must be a v3 onion".into())); return Err(Error("o must be a v3 onion".into()));
} }
@ -42,16 +58,19 @@ pub fn encode(identity_sk: &[u8], onion: &str, signed_prekey: &[u8]) -> Result<S
let sk = SigningKey::from_bytes(&sk_bytes); let sk = SigningKey::from_bytes(&sk_bytes);
let k = to_hex(&sk.verifying_key().to_bytes()); let k = to_hex(&sk.verifying_key().to_bytes());
let spk = to_hex(signed_prekey); let spk = to_hex(signed_prekey);
let msg = sign_msg_v2(&k, onion, &spk); let kem_ascii = b64url_encode(kem_pk);
let msg = sign_msg_invite_v2(&k, onion, &spk, &kem_ascii);
let sig = to_hex(&sk.sign(&msg).to_bytes()); let sig = to_hex(&sk.sign(&msg).to_bytes());
Ok(format!("onionwire:v1:k={k}:o={onion}:spk={spk}:sig={sig}")) Ok(format!(
"onionwire:v2:k={k}:o={onion}:spk={spk}:kem={kem_ascii}:sig={sig}"
))
} }
pub fn decode(raw: &str) -> Result<QrPayload> { pub fn decode(raw: &str) -> Result<QrPayload> {
if raw.len() > MAX_INVITE { if raw.len() > MAX_INVITE {
return Err(Error("invite too long".into())); return Err(Error("invite too long".into()));
} }
let (k, onion, spk, sig) = parse_fields(raw)?; let (version, k, onion, spk, kem_ascii, sig) = parse_fields(raw)?;
if !is_hex_len(&k, HEX_K) { if !is_hex_len(&k, HEX_K) {
return Err(Error("k must be 32 bytes".into())); return Err(Error("k must be 32 bytes".into()));
} }
@ -77,19 +96,46 @@ pub fn decode(raw: &str) -> Result<QrPayload> {
.map_err(|_| Error("sig must be 64 bytes".into()))?; .map_err(|_| Error("sig must be 64 bytes".into()))?;
let vk = VerifyingKey::from_bytes(&pk_arr).map_err(|e| Error(e.to_string()))?; let vk = VerifyingKey::from_bytes(&pk_arr).map_err(|e| Error(e.to_string()))?;
let signature = Signature::from_bytes(&sig_arr); let signature = Signature::from_bytes(&sig_arr);
let ok_v2 = vk let kem_pk = match version {
.verify(&sign_msg_v2(&k, &onion, &spk), &signature) 1 => {
.is_ok(); if kem_ascii.is_some() {
let ok_v1 = vk return Err(Error("unknown field".into()));
.verify(&sign_msg_v1(&k, &onion, &spk), &signature) }
.is_ok(); let ok_tagged = vk
if !ok_v2 && !ok_v1 { .verify(&sign_msg_v1_tagged(&k, &onion, &spk), &signature)
return Err(Error("bad signature".into())); .is_ok();
} let ok_legacy = vk
.verify(&sign_msg_v1_concat(&k, &onion, &spk), &signature)
.is_ok();
if !ok_tagged && !ok_legacy {
return Err(Error("bad signature".into()));
}
None
}
2 => {
let kem_ascii = kem_ascii.ok_or_else(|| Error("missing kem".into()))?;
if vk
.verify(
&sign_msg_invite_v2(&k, &onion, &spk, &kem_ascii),
&signature,
)
.is_err()
{
return Err(Error("bad signature".into()));
}
let pk = b64url_decode(&kem_ascii)?;
// Reject a kem= that is not a real encapsulation key. A stripped
// field never gets here: the signature above already covers it.
kem::decode_pk(&pk).map_err(|e| Error(e.to_string()))?;
Some(pk)
}
_ => return Err(Error("not an onionwire invite".into())),
};
Ok(QrPayload { Ok(QrPayload {
pubkey, pubkey,
onion, onion,
signed_prekey, signed_prekey,
kem_pk,
}) })
} }
@ -104,7 +150,23 @@ fn is_hex_len(s: &str, n: usize) -> bool {
s.len() == n && s.bytes().all(|c| c.is_ascii_hexdigit()) s.len() == n && s.bytes().all(|c| c.is_ascii_hexdigit())
} }
fn sign_msg_v2(k: &str, onion: &str, spk: &str) -> Vec<u8> { fn sign_msg_invite_v2(k: &str, onion: &str, spk: &str, kem_ascii: &str) -> Vec<u8> {
let mut msg = Vec::with_capacity(19 + 4 + k.len() + onion.len() + spk.len() + kem_ascii.len());
msg.extend_from_slice(b"onionwire-invite-v2");
msg.push(0);
msg.extend_from_slice(k.as_bytes());
msg.push(0);
msg.extend_from_slice(onion.as_bytes());
msg.push(0);
msg.extend_from_slice(spk.as_bytes());
msg.push(0);
msg.extend_from_slice(kem_ascii.as_bytes());
msg
}
/// Tagged v1 domain. Named for the historical `sign_msg_v2` (the tag is
/// `onionwire-invite-v1`); encode no longer emits it.
fn sign_msg_v1_tagged(k: &str, onion: &str, spk: &str) -> Vec<u8> {
let mut msg = Vec::with_capacity(19 + 3 + k.len() + onion.len() + spk.len()); let mut msg = Vec::with_capacity(19 + 3 + k.len() + onion.len() + spk.len());
msg.extend_from_slice(b"onionwire-invite-v1"); msg.extend_from_slice(b"onionwire-invite-v1");
msg.push(0); msg.push(0);
@ -116,7 +178,7 @@ fn sign_msg_v2(k: &str, onion: &str, spk: &str) -> Vec<u8> {
msg msg
} }
fn sign_msg_v1(k: &str, onion: &str, spk: &str) -> Vec<u8> { fn sign_msg_v1_concat(k: &str, onion: &str, spk: &str) -> Vec<u8> {
let mut msg = Vec::with_capacity(k.len() + onion.len() + spk.len()); let mut msg = Vec::with_capacity(k.len() + onion.len() + spk.len());
msg.extend_from_slice(k.as_bytes()); msg.extend_from_slice(k.as_bytes());
msg.extend_from_slice(onion.as_bytes()); msg.extend_from_slice(onion.as_bytes());
@ -124,13 +186,18 @@ fn sign_msg_v1(k: &str, onion: &str, spk: &str) -> Vec<u8> {
msg msg
} }
fn parse_fields(raw: &str) -> Result<(String, String, String, String)> { fn parse_fields(raw: &str) -> Result<(u8, String, String, String, Option<String>, String)> {
let rest = raw let (version, rest) = if let Some(rest) = raw.strip_prefix("onionwire:v2:") {
.strip_prefix("onionwire:v1:") (2u8, rest)
.ok_or_else(|| Error("not onionwire:v1".into()))?; } else if let Some(rest) = raw.strip_prefix("onionwire:v1:") {
(1u8, rest)
} else {
return Err(Error("not an onionwire invite".into()));
};
let mut k = None; let mut k = None;
let mut o = None; let mut o = None;
let mut spk = None; let mut spk = None;
let mut kem_f = None;
let mut sig = None; let mut sig = None;
for part in rest.split(':') { for part in rest.split(':') {
if let Some(v) = part.strip_prefix("k=") { if let Some(v) = part.strip_prefix("k=") {
@ -148,6 +215,14 @@ fn parse_fields(raw: &str) -> Result<(String, String, String, String)> {
return Err(Error("duplicate spk".into())); return Err(Error("duplicate spk".into()));
} }
spk = Some(v.to_string()); spk = Some(v.to_string());
} else if let Some(v) = part.strip_prefix("kem=") {
if version != 2 {
return Err(Error("unknown field".into()));
}
if kem_f.is_some() {
return Err(Error("duplicate kem".into()));
}
kem_f = Some(v.to_string());
} else if let Some(v) = part.strip_prefix("sig=") { } else if let Some(v) = part.strip_prefix("sig=") {
if sig.is_some() { if sig.is_some() {
return Err(Error("duplicate sig".into())); return Err(Error("duplicate sig".into()));
@ -158,9 +233,11 @@ fn parse_fields(raw: &str) -> Result<(String, String, String, String)> {
} }
} }
Ok(( Ok((
version,
k.ok_or_else(|| Error("missing k".into()))?, k.ok_or_else(|| Error("missing k".into()))?,
o.ok_or_else(|| Error("missing o".into()))?, o.ok_or_else(|| Error("missing o".into()))?,
spk.ok_or_else(|| Error("missing spk".into()))?, spk.ok_or_else(|| Error("missing spk".into()))?,
kem_f,
sig.ok_or_else(|| Error("missing sig".into()))?, sig.ok_or_else(|| Error("missing sig".into()))?,
)) ))
} }
@ -182,6 +259,77 @@ fn from_hex(s: &str) -> Result<Vec<u8>> {
.collect() .collect()
} }
fn b64url_encode(data: &[u8]) -> String {
const T: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
let mut i = 0;
while i + 3 <= data.len() {
let n = ((data[i] as u32) << 16) | ((data[i + 1] as u32) << 8) | data[i + 2] as u32;
out.push(T[((n >> 18) & 63) as usize] as char);
out.push(T[((n >> 12) & 63) as usize] as char);
out.push(T[((n >> 6) & 63) as usize] as char);
out.push(T[(n & 63) as usize] as char);
i += 3;
}
if i < data.len() {
let rem = data.len() - i;
let mut n = (data[i] as u32) << 16;
if rem == 2 {
n |= (data[i + 1] as u32) << 8;
}
out.push(T[((n >> 18) & 63) as usize] as char);
out.push(T[((n >> 12) & 63) as usize] as char);
if rem == 2 {
out.push(T[((n >> 6) & 63) as usize] as char);
}
}
out
}
fn b64url_decode(s: &str) -> Result<Vec<u8>> {
if s.is_empty() || s.len() % 4 == 1 || s.bytes().any(|b| b == b'=') {
return Err(Error("invalid kem".into()));
}
fn val(b: u8) -> Result<u8> {
Ok(match b {
b'A'..=b'Z' => b - b'A',
b'a'..=b'z' => b - b'a' + 26,
b'0'..=b'9' => b - b'0' + 52,
b'-' => 62,
b'_' => 63,
_ => return Err(Error("invalid kem".into())),
})
}
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len() * 3 / 4);
let mut i = 0;
while i + 4 <= bytes.len() {
let n = ((val(bytes[i])? as u32) << 18)
| ((val(bytes[i + 1])? as u32) << 12)
| ((val(bytes[i + 2])? as u32) << 6)
| val(bytes[i + 3])? as u32;
out.push((n >> 16) as u8);
out.push((n >> 8) as u8);
out.push(n as u8);
i += 4;
}
let rem = bytes.len() - i;
if rem == 2 {
let n = ((val(bytes[i])? as u32) << 18) | ((val(bytes[i + 1])? as u32) << 12);
out.push((n >> 16) as u8);
} else if rem == 3 {
let n = ((val(bytes[i])? as u32) << 18)
| ((val(bytes[i + 1])? as u32) << 12)
| ((val(bytes[i + 2])? as u32) << 6);
out.push((n >> 16) as u8);
out.push((n >> 8) as u8);
}
if out.len() != kem::PK_LEN {
return Err(Error("kem must be 1184 bytes".into()));
}
Ok(out)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -196,10 +344,11 @@ mod tests {
let k = to_hex(&sk.verifying_key().to_bytes()); let k = to_hex(&sk.verifying_key().to_bytes());
let onion = v3(); let onion = v3();
let spk = to_hex(&[9u8; 32]); let spk = to_hex(&[9u8; 32]);
let sig = to_hex(&sk.sign(&sign_msg_v1(&k, &onion, &spk)).to_bytes()); let sig = to_hex(&sk.sign(&sign_msg_v1_concat(&k, &onion, &spk)).to_bytes());
let raw = format!("onionwire:v1:k={k}:o={onion}:spk={spk}:sig={sig}"); let raw = format!("onionwire:v1:k={k}:o={onion}:spk={spk}:sig={sig}");
let p = decode(&raw).expect("legacy concat"); let p = decode(&raw).expect("legacy concat");
assert_eq!(p.onion, onion); assert_eq!(p.onion, onion);
assert_eq!(p.signed_prekey, vec![9u8; 32]); assert_eq!(p.signed_prekey, vec![9u8; 32]);
assert!(p.kem_pk.is_none(), "v1 invite is a classical friend");
} }
} }

View file

@ -8,8 +8,34 @@ use crate::store::SelfIdentity;
const PATTERN: &str = "Noise_IK_25519_ChaChaPoly_BLAKE2s"; const PATTERN: &str = "Noise_IK_25519_ChaChaPoly_BLAKE2s";
const PROLOGUE: &[u8] = b"onionwire-v1"; const PROLOGUE: &[u8] = b"onionwire-v1";
/// Returned when a friend row has a KEM key and the session had no prelude.
/// Stable: the outbox treats it as a permanent protocol error.
pub const PRELUDE_REQUIRED: &str = "prelude required";
/// Returned when a prelude arrives for a friend row with no KEM key: the row,
/// not the wire, decides whether a session is hybrid.
pub const UNEXPECTED_PRELUDE: &str = "unexpected prelude";
const MSG_BUF: usize = 65535; const MSG_BUF: usize = 65535;
/// Who the responder just authenticated, plus whether that friend row requires
/// a PQ prelude. The rule is the row, not the bytes that arrived.
pub struct PeerAuth {
pub identity: Vec<u8>,
pub kem_pk: Option<Vec<u8>>,
}
/// Hybrid Noise prologue. Exact layout:
/// `onionwire-v2 || 0x00 || ct || 0x00 || ss_kem`
/// (`onionwire-v2` is 12 bytes, `ct` is the ML-KEM-768 ciphertext, `ss_kem` is 32 bytes).
pub fn hybrid_prologue(ct: &[u8], ss: &[u8]) -> Vec<u8> {
let mut p = Vec::with_capacity(12 + 1 + ct.len() + 1 + ss.len());
p.extend_from_slice(b"onionwire-v2");
p.push(0);
p.extend_from_slice(ct);
p.push(0);
p.extend_from_slice(ss);
p
}
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)] #[derive(Debug)]
@ -72,6 +98,10 @@ pub struct Keys {
pub prekey_sk: [u8; 32], pub prekey_sk: [u8; 32],
#[zeroize(skip)] #[zeroize(skip)]
pub prekey_pk: [u8; 32], pub prekey_pk: [u8; 32],
/// 64-byte ML-KEM-768 seed. The decapsulation key.
pub kem_seed: [u8; crate::kem::SEED_LEN],
#[zeroize(skip)]
pub kem_pk: [u8; crate::kem::PK_LEN],
} }
impl Keys { impl Keys {
@ -79,11 +109,14 @@ impl Keys {
let signing = SigningKey::generate(&mut OsRng); let signing = SigningKey::generate(&mut OsRng);
let xsk = StaticSecret::random_from_rng(OsRng); let xsk = StaticSecret::random_from_rng(OsRng);
let xpk = X25519Public::from(&xsk); let xpk = X25519Public::from(&xsk);
let kem_kp = crate::kem::generate();
Self { Self {
identity_sk: signing.to_bytes(), identity_sk: signing.to_bytes(),
identity_pk: signing.verifying_key().to_bytes(), identity_pk: signing.verifying_key().to_bytes(),
prekey_sk: xsk.to_bytes(), prekey_sk: xsk.to_bytes(),
prekey_pk: xpk.to_bytes(), prekey_pk: xpk.to_bytes(),
kem_seed: *kem_kp.seed,
kem_pk: kem_kp.pk,
} }
} }
@ -93,6 +126,8 @@ impl Keys {
identity_pk: to_32(&me.identity_pk)?, identity_pk: to_32(&me.identity_pk)?,
prekey_sk: to_32(&me.prekey_sk)?, prekey_sk: to_32(&me.prekey_sk)?,
prekey_pk: to_32(&me.prekey_pk)?, prekey_pk: to_32(&me.prekey_pk)?,
kem_seed: to_64(&me.kem_sk)?,
kem_pk: to_pk(&me.kem_pk)?,
}) })
} }
} }
@ -192,17 +227,30 @@ pub async fn handshake_initiator<S>(
local: &Keys, local: &Keys,
pinned_id: &[u8], pinned_id: &[u8],
remote_prekey: &[u8], remote_prekey: &[u8],
remote_kem_pk: Option<&[u8]>,
) -> Result<Session> ) -> Result<Session>
where where
S: futures::io::AsyncRead + futures::io::AsyncWrite + Unpin, S: futures::io::AsyncRead + futures::io::AsyncWrite + Unpin,
{ {
let prologue = if let Some(pk) = remote_kem_pk {
let (ct, ss) = crate::kem::encapsulate(pk).map_err(|e| Error::new(e.to_string()))?;
crate::frame::write_prelude(stream, &ct)
.await
.map_err(|e| Error::new(e.to_string()))?;
let mut ss = ss;
let prologue = hybrid_prologue(&ct, &ss);
ss.zeroize();
prologue
} else {
PROLOGUE.to_vec()
};
let params: snow::params::NoiseParams = PATTERN let params: snow::params::NoiseParams = PATTERN
.parse() .parse()
.map_err(|e: snow::Error| Error::new(e.to_string()))?; .map_err(|e: snow::Error| Error::new(e.to_string()))?;
let mut hs = Builder::new(params) let mut hs = Builder::new(params)
.local_private_key(&local.prekey_sk)? .local_private_key(&local.prekey_sk)?
.remote_public_key(remote_prekey)? .remote_public_key(remote_prekey)?
.prologue(PROLOGUE)? .prologue(&prologue)?
.build_initiator()?; .build_initiator()?;
let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]); let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
@ -249,20 +297,33 @@ pub async fn handshake_responder<S, F>(
) -> Result<Session> ) -> Result<Session>
where where
S: futures::io::AsyncRead + futures::io::AsyncWrite + Unpin, S: futures::io::AsyncRead + futures::io::AsyncWrite + Unpin,
F: FnOnce(&[u8]) -> Option<Vec<u8>>, F: FnOnce(&[u8]) -> Option<PeerAuth>,
{ {
let opening = crate::frame::read_opening(stream)
.await
.map_err(|e| Error::new(e.to_string()))?;
let (saw_prelude, prologue, msg1) = match opening {
crate::frame::Opening::Prelude(ct) => {
let mut ss = crate::kem::decapsulate(&local.kem_seed[..], &ct)
.map_err(|e| Error::new(e.to_string()))?;
let prologue = hybrid_prologue(&ct, &ss);
ss.zeroize();
let msg1 = crate::frame::read_frame(stream)
.await
.map_err(|e| Error::new(e.to_string()))?;
(true, prologue, msg1)
}
crate::frame::Opening::Classical(body) => (false, PROLOGUE.to_vec(), body),
};
let params: snow::params::NoiseParams = PATTERN let params: snow::params::NoiseParams = PATTERN
.parse() .parse()
.map_err(|e: snow::Error| Error::new(e.to_string()))?; .map_err(|e: snow::Error| Error::new(e.to_string()))?;
let mut hs = Builder::new(params) let mut hs = Builder::new(params)
.local_private_key(&local.prekey_sk)? .local_private_key(&local.prekey_sk)?
.prologue(PROLOGUE)? .prologue(&prologue)?
.build_responder()?; .build_responder()?;
let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]); let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
let msg1 = crate::frame::read_frame(stream)
.await
.map_err(|e| Error::new(e.to_string()))?;
let n = hs.read_message(&msg1, &mut buf)?; let n = hs.read_message(&msg1, &mut buf)?;
if n != 0 { if n != 0 {
return Err(Error::new("unexpected handshake payload")); return Err(Error::new("unexpected handshake payload"));
@ -271,8 +332,18 @@ where
.get_remote_static() .get_remote_static()
.ok_or_else(|| Error::new("missing remote static"))? .ok_or_else(|| Error::new("missing remote static"))?
.to_vec(); .to_vec();
let expected_id = let peer = lookup_identity(&remote_static).ok_or_else(|| Error::new("unknown prekey"))?;
lookup_identity(&remote_static).ok_or_else(|| Error::new("unknown prekey"))?; // Friend row has a KEM key and this session did not open with a prelude.
// Fail before msg 2, the identity proofs, and any application frame.
if peer.kem_pk.is_some() && !saw_prelude {
return Err(Error::new(PRELUDE_REQUIRED));
}
// The other direction of the same rule: a legacy friend row is classical,
// and a prelude cannot upgrade it from the wire.
if peer.kem_pk.is_none() && saw_prelude {
return Err(Error::new(UNEXPECTED_PRELUDE));
}
let expected_id = peer.identity;
let n = hs.write_message(&[], &mut buf)?; let n = hs.write_message(&[], &mut buf)?;
crate::frame::write_frame(stream, &buf[..n]) crate::frame::write_frame(stream, &buf[..n])
.await .await
@ -328,3 +399,11 @@ fn verify_proof(proof: &[u8], expected_pk: &[u8], hash: &[u8]) -> Result<()> {
fn to_32(v: &[u8]) -> Result<[u8; 32]> { fn to_32(v: &[u8]) -> Result<[u8; 32]> {
v.try_into().map_err(|_| Error::new("need 32 bytes")) v.try_into().map_err(|_| Error::new("need 32 bytes"))
} }
fn to_64(v: &[u8]) -> Result<[u8; crate::kem::SEED_LEN]> {
v.try_into().map_err(|_| Error::new("need 64 bytes"))
}
fn to_pk(v: &[u8]) -> Result<[u8; crate::kem::PK_LEN]> {
v.try_into().map_err(|_| Error::new("need 1184 bytes"))
}

View file

@ -63,6 +63,10 @@ pub struct SelfIdentity {
pub onion: String, pub onion: String,
pub prekey_sk: Zeroizing<Vec<u8>>, pub prekey_sk: Zeroizing<Vec<u8>>,
pub prekey_pk: Vec<u8>, pub prekey_pk: Vec<u8>,
/// 64-byte ML-KEM-768 seed. Same sealing as `identity_sk`: raw bytes inside
/// the SQLCipher file, wiped when this value drops.
pub kem_sk: Zeroizing<Vec<u8>>,
pub kem_pk: Vec<u8>,
} }
pub struct Friend { pub struct Friend {
@ -72,6 +76,9 @@ pub struct Friend {
pub onion: String, pub onion: String,
pub last_connect_ok: bool, pub last_connect_ok: bool,
pub prekey: Vec<u8>, pub prekey: Vec<u8>,
/// ML-KEM-768 encapsulation key from a v2 invite. `None` is a legacy v1
/// friend: outbound sessions stay classical and the UI must say so.
pub kem_pk: Option<Vec<u8>>,
} }
pub struct FriendProfile { pub struct FriendProfile {
@ -247,7 +254,8 @@ impl Store {
onion_updated_at INTEGER NOT NULL, onion_updated_at INTEGER NOT NULL,
added_at INTEGER NOT NULL, added_at INTEGER NOT NULL,
last_connect_ok INTEGER NOT NULL DEFAULT 1, last_connect_ok INTEGER NOT NULL DEFAULT 1,
prekey BLOB NOT NULL DEFAULT x'' prekey BLOB NOT NULL DEFAULT x'',
kem_pk BLOB
); );
CREATE TABLE IF NOT EXISTS messages ( CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
@ -264,6 +272,8 @@ impl Store {
onion_rotated_at INTEGER NOT NULL, onion_rotated_at INTEGER NOT NULL,
prekey_sk BLOB NOT NULL, prekey_sk BLOB NOT NULL,
prekey_pk BLOB NOT NULL, prekey_pk BLOB NOT NULL,
kem_sk BLOB NOT NULL DEFAULT x'',
kem_pk BLOB NOT NULL DEFAULT x'',
hs_nickname TEXT NOT NULL DEFAULT 'ow0' hs_nickname TEXT NOT NULL DEFAULT 'ow0'
); );
CREATE TABLE IF NOT EXISTS self_profile ( CREATE TABLE IF NOT EXISTS self_profile (
@ -611,6 +621,20 @@ impl Store {
Ok(()) Ok(())
} }
/// Replace the install KEM key. F8 calls this with the prekey rotate.
/// Identity columns are untouched, and so is a backup restore that only
/// rewrites the classical keys.
pub fn set_kem_keys(&self, seed: &[u8], pk: &[u8]) -> Result<()> {
if seed.len() != crate::kem::SEED_LEN || pk.len() != crate::kem::PK_LEN {
return Err(Error("kem key length".into()));
}
self.conn.execute(
"UPDATE self SET kem_sk = ?1, kem_pk = ?2 WHERE id = 1",
params![seed, pk],
)?;
Ok(())
}
fn migrate(&self) -> Result<()> { fn migrate(&self) -> Result<()> {
self.add_column_if_missing( self.add_column_if_missing(
"friends", "friends",
@ -637,6 +661,21 @@ impl Store {
"hs_nickname", "hs_nickname",
"ALTER TABLE self ADD COLUMN hs_nickname TEXT NOT NULL DEFAULT 'ow0'", "ALTER TABLE self ADD COLUMN hs_nickname TEXT NOT NULL DEFAULT 'ow0'",
)?; )?;
self.add_column_if_missing(
"self",
"kem_sk",
"ALTER TABLE self ADD COLUMN kem_sk BLOB NOT NULL DEFAULT x''",
)?;
self.add_column_if_missing(
"self",
"kem_pk",
"ALTER TABLE self ADD COLUMN kem_pk BLOB NOT NULL DEFAULT x''",
)?;
self.add_column_if_missing(
"friends",
"kem_pk",
"ALTER TABLE friends ADD COLUMN kem_pk BLOB",
)?;
// The wallet file's passphrase (sealed). NULL on an install that has // The wallet file's passphrase (sealed). NULL on an install that has
// never been told one — a wallet created before this column, or a // never been told one — a wallet created before this column, or a
// remote-mode wallet the user opens themselves. // remote-mode wallet the user opens themselves.
@ -847,13 +886,32 @@ impl Store {
)?; )?;
} }
} }
self.ensure_kem()?;
Ok(())
}
/// Fill a missing ML-KEM-768 install key. New installs and upgraded v1
/// stores both land here; an existing 64/1184 pair is left alone.
fn ensure_kem(&self) -> Result<()> {
let missing: i64 = self.conn.query_row(
"SELECT CASE WHEN length(kem_sk) = 64 AND length(kem_pk) = 1184 THEN 0 ELSE 1 END FROM self WHERE id = 1",
[],
|row| row.get(0),
)?;
if missing != 0 {
let kp = crate::kem::generate();
self.conn.execute(
"UPDATE self SET kem_sk = ?1, kem_pk = ?2 WHERE id = 1",
params![&kp.seed[..], kp.pk.as_slice()],
)?;
}
Ok(()) Ok(())
} }
pub fn self_identity(&self) -> Result<SelfIdentity> { pub fn self_identity(&self) -> Result<SelfIdentity> {
self.conn self.conn
.query_row( .query_row(
"SELECT identity_sk, identity_pk, onion, prekey_sk, prekey_pk FROM self WHERE id = 1", "SELECT identity_sk, identity_pk, onion, prekey_sk, prekey_pk, kem_sk, kem_pk FROM self WHERE id = 1",
[], [],
|row| { |row| {
Ok(SelfIdentity { Ok(SelfIdentity {
@ -862,6 +920,8 @@ impl Store {
onion: row.get(2)?, onion: row.get(2)?,
prekey_sk: Zeroizing::new(row.get(3)?), prekey_sk: Zeroizing::new(row.get(3)?),
prekey_pk: row.get(4)?, prekey_pk: row.get(4)?,
kem_sk: Zeroizing::new(row.get(5)?),
kem_pk: row.get(6)?,
}) })
}, },
) )
@ -909,7 +969,7 @@ impl Store {
pub fn get_friend(&self, pubkey: &[u8]) -> Result<Option<Friend>> { pub fn get_friend(&self, pubkey: &[u8]) -> Result<Option<Friend>> {
self.conn self.conn
.query_row( .query_row(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE pubkey = ?1", "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey, kem_pk FROM friends WHERE pubkey = ?1",
params![pubkey], params![pubkey],
friend_from_row, friend_from_row,
) )
@ -923,7 +983,7 @@ impl Store {
pub fn friend_by_onion(&self, onion: &str) -> Result<Option<Friend>> { pub fn friend_by_onion(&self, onion: &str) -> Result<Option<Friend>> {
self.conn self.conn
.query_row( .query_row(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1", "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey, kem_pk FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1",
params![onion], params![onion],
friend_from_row, friend_from_row,
) )
@ -933,7 +993,7 @@ impl Store {
pub fn list_friends(&self) -> Result<Vec<Friend>> { pub fn list_friends(&self) -> Result<Vec<Friend>> {
let mut stmt = self.conn.prepare( let mut stmt = self.conn.prepare(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey, kem_pk FROM friends
ORDER BY COALESCE(petname, fingerprint) COLLATE NOCASE", ORDER BY COALESCE(petname, fingerprint) COLLATE NOCASE",
)?; )?;
let rows = stmt.query_map([], friend_from_row)?; let rows = stmt.query_map([], friend_from_row)?;
@ -1084,10 +1144,27 @@ impl Store {
Ok(()) Ok(())
} }
/// `None` stores NULL: a v1 invite, classical sessions from here on.
pub fn set_friend_kem(&self, pubkey: &[u8], kem_pk: Option<&[u8]>) -> Result<()> {
if let Some(pk) = kem_pk
&& pk.len() != crate::kem::PK_LEN
{
return Err(Error("kem pk length".into()));
}
let n = self.conn.execute(
"UPDATE friends SET kem_pk = ?1 WHERE pubkey = ?2",
params![kem_pk, pubkey],
)?;
if n == 0 {
return Err(Error("friend not found".into()));
}
Ok(())
}
pub fn get_friend_by_prekey(&self, prekey: &[u8]) -> Result<Option<Friend>> { pub fn get_friend_by_prekey(&self, prekey: &[u8]) -> Result<Option<Friend>> {
self.conn self.conn
.query_row( .query_row(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE prekey = ?1", "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey, kem_pk FROM friends WHERE prekey = ?1",
params![prekey], params![prekey],
friend_from_row, friend_from_row,
) )
@ -1560,6 +1637,8 @@ fn profile_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<FriendProfile>
} }
fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Friend> { fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Friend> {
let kem: Option<Vec<u8>> = row.get(6)?;
let kem_pk = kem.filter(|k| k.len() == crate::kem::PK_LEN);
Ok(Friend { Ok(Friend {
pubkey: row.get(0)?, pubkey: row.get(0)?,
fingerprint: row.get(1)?, fingerprint: row.get(1)?,
@ -1567,6 +1646,7 @@ fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Friend> {
onion: row.get(3)?, onion: row.get(3)?,
last_connect_ok: row.get::<_, i64>(4)? != 0, last_connect_ok: row.get::<_, i64>(4)? != 0,
prekey: row.get(5)?, prekey: row.get(5)?,
kem_pk,
}) })
} }
@ -1877,6 +1957,41 @@ mod at_rest {
use super::*; use super::*;
use zeroize::Zeroize; use zeroize::Zeroize;
/// An install that predates the KEM columns (or one whose pair was blanked)
/// must gain a fresh ML-KEM key on open, and keep it on the next open.
#[test]
fn a_store_without_a_kem_key_generates_one_once() {
let dir = tempfile::tempdir().unwrap();
let pass = "kem-migrate-pass";
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
store
.conn
.execute(
"UPDATE self SET kem_sk = x'', kem_pk = x'' WHERE id = 1",
[],
)
.unwrap();
store
.conn
.execute("UPDATE friends SET kem_pk = NULL WHERE 1 = 1", [])
.unwrap();
drop(store);
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
let me = store.self_identity().unwrap();
assert_eq!(me.kem_sk.len(), crate::kem::SEED_LEN);
assert_eq!(me.kem_pk.len(), crate::kem::PK_LEN);
let pk = me.kem_pk.clone();
drop(store);
let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap();
assert_eq!(
store.self_identity().unwrap().kem_pk,
pk,
"an existing pair is never silently replaced"
);
}
/// `Node::shutdown`/`flush` checkpoint the WAL through this method, so it has /// `Node::shutdown`/`flush` checkpoint the WAL through this method, so it has
/// to run on the store's own keyed connection: a second, unkeyed one cannot /// to run on the store's own keyed connection: a second, unkeyed one cannot
/// read a SQLCipher file at all (`SQLITE_NOTADB`) and the truncation silently /// read a SQLCipher file at all (`SQLITE_NOTADB`) and the truncation silently

View file

@ -3750,6 +3750,10 @@ pub struct FriendRow {
pub fingerprint: String, pub fingerprint: String,
/// Last dial to this peer's onion did not answer. /// Last dial to this peer's onion did not answer.
pub stale: bool, pub stale: bool,
/// Friend row has an ML-KEM key (v2 invite). `false` means sessions to
/// this friend are the classical `onionwire-v1` transport, and the roster
/// says so in words — no pretending it is hybrid.
pub pq: bool,
} }
/// The roster row for one friend, fitted to the pane's inner width in cells. /// The roster row for one friend, fitted to the pane's inner width in cells.
@ -3759,6 +3763,7 @@ pub fn friend_row(friend: &Friend) -> FriendRow {
label: sanitize::display_text(raw.as_bytes()).to_string(), label: sanitize::display_text(raw.as_bytes()).to_string(),
fingerprint: friend.fingerprint.clone(), fingerprint: friend.fingerprint.clone(),
stale: !friend.last_connect_ok, stale: !friend.last_connect_ok,
pq: friend.kem_pk.is_some(),
} }
} }
@ -5552,7 +5557,10 @@ fn truncate_fp(fp: &str) -> String {
fn roster_row_text(row: &FriendRow, inner_width: u16) -> String { fn roster_row_text(row: &FriendRow, inner_width: u16) -> String {
let budget = (inner_width as usize).saturating_sub(2); let budget = (inner_width as usize).saturating_sub(2);
let stale_s = if row.stale { " stale" } else { "" }; let stale_s = if row.stale { " stale" } else { "" };
let avail = budget.saturating_sub(cell_width(stale_s)); // A legacy v1 friend has no PQ transport; say the word rather than let the
// roster imply protection it does not have.
let pq_s = if row.pq { "" } else { " classical" };
let avail = budget.saturating_sub(cell_width(stale_s) + cell_width(pq_s));
// The name is what the reader is looking for. The fingerprint only // The name is what the reader is looking for. The fingerprint only
// disambiguates two friends with the same petname, so it gets what is left // disambiguates two friends with the same petname, so it gets what is left
// and is dropped entirely when the pane is too narrow to show a usable // and is dropped entirely when the pane is too narrow to show a usable
@ -5568,7 +5576,7 @@ fn roster_row_text(row: &FriendRow, inner_width: u16) -> String {
} else { } else {
(fit_cells(&row.label, avail), String::new()) (fit_cells(&row.label, avail), String::new())
}; };
fit_cells(&format!("{shown}{fp_part}{stale_s}"), budget) fit_cells(&format!("{shown}{fp_part}{pq_s}{stale_s}"), budget)
} }
fn to_hex(bytes: &[u8]) -> String { fn to_hex(bytes: &[u8]) -> String {

20
tests/kem.rs Normal file
View file

@ -0,0 +1,20 @@
//! ML-KEM-768 encaps/decaps through the byte encode/decode the invite and the
//! prelude actually use.
use onionwire::kem;
#[test]
fn kem_encaps_decaps_round_trip_through_encode_decode() {
let kp = kem::generate();
let pk = kem::encode_pk(&kp.pk).expect("encode pk");
let pk2 = kem::decode_pk(&pk).expect("decode pk");
assert_eq!(pk2.len(), kem::PK_LEN);
let (ct, ss_send) = kem::encapsulate(&pk2).expect("encapsulate");
let ct_bytes = kem::encode_ct(&ct).expect("encode ct");
let ct2 = kem::decode_ct(&ct_bytes).expect("decode ct");
let ss_recv = kem::decapsulate(&kp.seed[..], &ct2).expect("decapsulate");
assert_eq!(ss_send, ss_recv);
assert_eq!(ss_send.len(), kem::SS_LEN);
assert_eq!(ct2.len(), kem::CT_LEN);
}

249
tests/kem_transport.rs Normal file
View file

@ -0,0 +1,249 @@
//! PQ prelude at the wire level: the hybrid prologue layout, a tampered
//! ciphertext failing the handshake, and a classical opening to a friend that
//! has a KEM key being refused before any application frame.
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures::io::{AsyncRead, AsyncWrite};
use onionwire::frame;
use onionwire::kem;
use onionwire::session::{self, Keys, PRELUDE_REQUIRED, PeerAuth};
use tokio::io::{AsyncRead as TokioRead, AsyncWrite as TokioWrite};
/// `tokio::io::duplex` is the only in-memory two-way pipe available without a
/// new dependency; it speaks `tokio::io`, while the handshake is generic over
/// `futures::io`. One thin adapter per direction.
struct Duplex(tokio::io::DuplexStream);
impl AsyncRead for Duplex {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
let mut read_buf = tokio::io::ReadBuf::new(buf);
match Pin::new(&mut self.get_mut().0).poll_read(cx, &mut read_buf) {
Poll::Ready(Ok(())) => Poll::Ready(Ok(read_buf.filled().len())),
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
Poll::Pending => Poll::Pending,
}
}
}
impl AsyncWrite for Duplex {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.get_mut().0).poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().0).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().0).poll_shutdown(cx)
}
}
/// Flips one ciphertext byte in the initiator's single prelude frame as it is
/// written, leaving the Noise msg 1 that follows untouched.
struct TamperPrelude {
inner: Duplex,
done: bool,
}
impl AsyncRead for TamperPrelude {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
let this = self.get_mut();
Pin::new(&mut this.inner).poll_read(cx, buf)
}
}
impl AsyncWrite for TamperPrelude {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
let this = self.get_mut();
if !this.done {
this.done = true;
let mut mutated = buf.to_vec();
// version(1) | len(4) | ct_len(2) | ct...
if mutated.len() > 7 {
mutated[7] ^= 0x01;
}
let wanted = buf.len();
return Pin::new(&mut this.inner)
.poll_write(cx, &mutated)
.map(|r| r.map(|_| wanted));
}
Pin::new(&mut this.inner).poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().inner).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().inner).poll_close(cx)
}
}
fn responder_auth(peer: &Keys) -> impl FnOnce(&[u8]) -> Option<PeerAuth> + '_ {
move |spk: &[u8]| {
(spk == &peer.prekey_pk[..]).then(|| PeerAuth {
identity: peer.identity_pk.to_vec(),
kem_pk: Some(peer.kem_pk.to_vec()),
})
}
}
fn responder_auth_classical(peer: &Keys) -> impl FnOnce(&[u8]) -> Option<PeerAuth> + '_ {
move |spk: &[u8]| {
(spk == &peer.prekey_pk[..]).then(|| PeerAuth {
identity: peer.identity_pk.to_vec(),
kem_pk: None,
})
}
}
#[test]
fn hybrid_prologue_has_the_documented_layout() {
let ct = vec![0xABu8; kem::CT_LEN];
let ss = [0xCDu8; kem::SS_LEN];
let p = session::hybrid_prologue(&ct, &ss);
assert_eq!(p.len(), 12 + 1 + kem::CT_LEN + 1 + kem::SS_LEN);
assert_eq!(&p[..12], b"onionwire-v2");
assert_eq!(p[12], 0x00);
assert_eq!(&p[13..13 + kem::CT_LEN], &ct[..]);
assert_eq!(p[13 + kem::CT_LEN], 0x00);
assert_eq!(&p[14 + kem::CT_LEN..], &ss[..]);
}
#[test]
fn prelude_frame_is_version_two_with_a_u16_length_and_the_ct() {
let rt = tokio::runtime::Runtime::new().expect("runtime");
rt.block_on(async {
let (tx, mut rx) = tokio::io::duplex(4096);
let ct = vec![7u8; kem::CT_LEN];
frame::write_prelude(&mut Duplex(tx), &ct)
.await
.expect("write");
let mut head = [0u8; 7];
use tokio::io::AsyncReadExt;
rx.read_exact(&mut head).await.expect("head");
assert_eq!(head[0], frame::VERSION_PRELUDE);
assert_eq!(u32::from_be_bytes(head[1..5].try_into().unwrap()), 1090);
assert_eq!(u16::from_be_bytes(head[5..7].try_into().unwrap()), 1088);
});
}
#[tokio::test]
async fn tampered_prelude_fails_the_handshake() {
let node = Keys::generate();
let peer = Keys::generate();
let (client, server) = tokio::io::duplex(256 * 1024);
let send = async {
let mut stream = TamperPrelude {
inner: Duplex(client),
done: false,
};
session::handshake_initiator(
&mut stream,
&peer,
&node.identity_pk,
&node.prekey_pk,
Some(&node.kem_pk),
)
.await
};
let receive = async {
let mut stream = Duplex(server);
session::handshake_responder(&mut stream, &node, responder_auth(&peer)).await
};
let (sent, received) = futures::join!(send, receive);
let err = match received {
Ok(_) => panic!("a tampered ciphertext must not complete the handshake"),
Err(e) => e,
};
assert!(
!err.to_string().contains(PRELUDE_REQUIRED),
"the prelude was present, so this must fail in the prologue/Noise step: {err}"
);
assert!(sent.is_err(), "no initiator session can be established");
}
#[tokio::test]
async fn a_prelude_to_a_classical_friend_row_is_refused() {
use onionwire::session::UNEXPECTED_PRELUDE;
let node = Keys::generate();
let peer = Keys::generate();
let (client, server) = tokio::io::duplex(256 * 1024);
let send = async {
let mut stream = Duplex(client);
session::handshake_initiator(
&mut stream,
&peer,
&node.identity_pk,
&node.prekey_pk,
Some(&node.kem_pk),
)
.await
};
let receive = async {
let mut stream = Duplex(server);
session::handshake_responder(&mut stream, &node, responder_auth_classical(&peer)).await
};
let (sent, received) = futures::join!(send, receive);
let err = match received {
Ok(_) => panic!("the wire must not upgrade a classical friend row"),
Err(e) => e,
};
assert!(
err.to_string().contains(UNEXPECTED_PRELUDE),
"expected {UNEXPECTED_PRELUDE}, got: {err}"
);
assert!(sent.is_err());
}
#[tokio::test]
async fn a_classical_opening_to_a_kem_friend_is_refused() {
let node = Keys::generate();
let peer = Keys::generate();
let (client, server) = tokio::io::duplex(256 * 1024);
let send = async {
let mut stream = Duplex(client);
session::handshake_initiator(&mut stream, &peer, &node.identity_pk, &node.prekey_pk, None)
.await
};
let receive = async {
let mut stream = Duplex(server);
session::handshake_responder(&mut stream, &node, responder_auth(&peer)).await
};
let (sent, received) = futures::join!(send, receive);
let err = match received {
Ok(_) => panic!("a prelude-less session to a KEM friend is a hard fail"),
Err(e) => e,
};
assert!(
err.to_string().contains(PRELUDE_REQUIRED),
"expected {PRELUDE_REQUIRED}, got: {err}"
);
assert!(sent.is_err());
}

View file

@ -25,6 +25,7 @@ struct Flaky {
err: String, err: String,
calls: AtomicUsize, calls: AtomicUsize,
delivered: Mutex<Vec<Vec<u8>>>, delivered: Mutex<Vec<Vec<u8>>>,
kems: Mutex<Vec<Option<Vec<u8>>>>,
} }
impl Flaky { impl Flaky {
@ -34,6 +35,7 @@ impl Flaky {
err: err.into(), err: err.into(),
calls: AtomicUsize::new(0), calls: AtomicUsize::new(0),
delivered: Mutex::new(Vec::new()), delivered: Mutex::new(Vec::new()),
kems: Mutex::new(Vec::new()),
}) })
} }
@ -53,8 +55,13 @@ impl Deliverer for Flaky {
_pinned_id: &'a [u8], _pinned_id: &'a [u8],
_prekey: &'a [u8], _prekey: &'a [u8],
plaintext: &'a [u8], plaintext: &'a [u8],
_remote_kem: Option<&'a [u8]>,
) -> BoxFut<'a, Result<(), String>> { ) -> BoxFut<'a, Result<(), String>> {
self.calls.fetch_add(1, Ordering::SeqCst); self.calls.fetch_add(1, Ordering::SeqCst);
self.kems
.lock()
.unwrap()
.push(_remote_kem.map(|k| k.to_vec()));
let left = self.fail_times.load(Ordering::SeqCst); let left = self.fail_times.load(Ordering::SeqCst);
if left > 0 { if left > 0 {
self.fail_times.fetch_sub(1, Ordering::SeqCst); self.fail_times.fetch_sub(1, Ordering::SeqCst);
@ -366,3 +373,42 @@ async fn missing_prekey_is_fatal_not_queued() {
assert!(err.contains("prekey"), "got {err}"); assert!(err.contains("prekey"), "got {err}");
assert!(ob.pending(&pk(2)).unwrap().is_empty()); assert!(ob.pending(&pk(2)).unwrap().is_empty());
} }
/// The outbound rule is derived from the friend row: a v2 friend always gets
/// the KEM key handed to the dialer (which then sends the prelude), a v1 friend
/// gets `None` and stays classical. The outbox never decides from wire input.
#[tokio::test]
async fn the_outbox_hands_the_kem_key_from_the_friend_row_to_the_dialer() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "pq.onion");
let kp = onionwire::kem::generate();
store
.lock()
.unwrap()
.set_friend_kem(&pk(1), Some(&kp.pk))
.unwrap();
let pq = Flaky::new(0, "");
outbox(Arc::clone(&store), Arc::clone(&pq) as Arc<dyn Deliverer>, 8)
.send(&pk(1), b"pq")
.await
.unwrap();
assert_eq!(
pq.kems.lock().unwrap().as_slice(),
[Some(kp.pk.to_vec())],
"a v2 friend must always send the prelude"
);
// A legacy row (v1 invite) has no kem column value -> classical session.
let legacy = Flaky::new(0, "");
store.lock().unwrap().set_friend_kem(&pk(1), None).unwrap();
outbox(Arc::clone(&store), Arc::clone(&legacy) as Arc<dyn Deliverer>, 8)
.send(&pk(1), b"legacy")
.await
.unwrap();
assert_eq!(
legacy.kems.lock().unwrap().as_slice(),
[None],
"a v1 friend stays classical; no invented PQ protection"
);
}

View file

@ -51,7 +51,7 @@ fn v3onion(tag: &str) -> String {
} }
fn invite_fields(raw: &str) -> (String, String, String, String) { fn invite_fields(raw: &str) -> (String, String, String, String) {
let rest = raw.strip_prefix("onionwire:v1:").expect("prefix"); let rest = raw.strip_prefix("onionwire:v2:").or_else(|| raw.strip_prefix("onionwire:v1:")).expect("prefix");
let mut k = String::new(); let mut k = String::new();
let mut o = String::new(); let mut o = String::new();
let mut spk = String::new(); let mut spk = String::new();
@ -77,8 +77,9 @@ fn encode_decode_roundtrip() {
let me = store.self_identity().expect("self"); let me = store.self_identity().expect("self");
let spk = [7u8; 32]; let spk = [7u8; 32];
let onion = v3onion("alice-locator"); let onion = v3onion("alice-locator");
let raw = qr::encode(&me.identity_sk, &onion, &spk).expect("encode"); let raw = qr::encode(&me.identity_sk, &onion, &spk, &me.kem_pk).expect("encode");
assert!(raw.starts_with("onionwire:v1:k="), "payload prefix: {raw}"); assert!(raw.starts_with("onionwire:v2:k="), "payload prefix: {raw}");
assert!(raw.contains(":kem="));
assert!(raw.contains(":o=")); assert!(raw.contains(":o="));
assert!(raw.contains(":spk=")); assert!(raw.contains(":spk="));
assert!(raw.contains(":sig=")); assert!(raw.contains(":sig="));
@ -102,7 +103,7 @@ fn missing_sig_is_err() {
let _home = TempHome::new(); let _home = TempHome::new();
let store = Store::open().expect("open"); let store = Store::open().expect("open");
let me = store.self_identity().expect("self"); let me = store.self_identity().expect("self");
let raw = qr::encode(&me.identity_sk, &v3onion("x"), &[1u8; 32]).expect("encode"); let raw = qr::encode(&me.identity_sk, &v3onion("x"), &[1u8; 32], &me.kem_pk).expect("encode");
let stripped = raw.rsplit_once(":sig=").expect("sig field").0; let stripped = raw.rsplit_once(":sig=").expect("sig field").0;
assert!(qr::decode(stripped).is_err()); assert!(qr::decode(stripped).is_err());
assert!(qr::decode(&format!("{stripped}:sig=")).is_err()); assert!(qr::decode(&format!("{stripped}:sig=")).is_err());
@ -113,7 +114,7 @@ fn bad_sig_is_err() {
let _home = TempHome::new(); let _home = TempHome::new();
let store = Store::open().expect("open"); let store = Store::open().expect("open");
let me = store.self_identity().expect("self"); let me = store.self_identity().expect("self");
let raw = qr::encode(&me.identity_sk, &v3onion("x"), &[1u8; 32]).expect("encode"); let raw = qr::encode(&me.identity_sk, &v3onion("x"), &[1u8; 32], &me.kem_pk).expect("encode");
let (head, sig) = raw.rsplit_once(":sig=").expect("sig field"); let (head, sig) = raw.rsplit_once(":sig=").expect("sig field");
let mut chars: Vec<char> = sig.chars().collect(); let mut chars: Vec<char> = sig.chars().collect();
let last = chars.last_mut().expect("sig chars"); let last = chars.last_mut().expect("sig chars");
@ -128,11 +129,11 @@ fn same_k_rescan_updates_onion_not_duplicate() {
let store = Store::open().expect("open"); let store = Store::open().expect("open");
let me = store.self_identity().expect("self"); let me = store.self_identity().expect("self");
let spk = [9u8; 32]; let spk = [9u8; 32];
let p1 = qr::decode(&qr::encode(&me.identity_sk, &v3onion("old"), &spk).unwrap()).unwrap(); let p1 = qr::decode(&qr::encode(&me.identity_sk, &v3onion("old"), &spk, &me.kem_pk).unwrap()).unwrap();
store store
.upsert_friend(&p1.pubkey, &p1.onion, Some("alice")) .upsert_friend(&p1.pubkey, &p1.onion, Some("alice"))
.unwrap(); .unwrap();
let p2 = qr::decode(&qr::encode(&me.identity_sk, &v3onion("new"), &spk).unwrap()).unwrap(); let p2 = qr::decode(&qr::encode(&me.identity_sk, &v3onion("new"), &spk, &me.kem_pk).unwrap()).unwrap();
store.upsert_friend(&p2.pubkey, &p2.onion, None).unwrap(); store.upsert_friend(&p2.pubkey, &p2.onion, None).unwrap();
assert_eq!(store.friend_count().unwrap(), 1); assert_eq!(store.friend_count().unwrap(), 1);
let f = store.get_friend(&p2.pubkey).unwrap().unwrap(); let f = store.get_friend(&p2.pubkey).unwrap().unwrap();
@ -145,7 +146,7 @@ fn unknown_k_decode_does_not_insert() {
let _home = TempHome::new(); let _home = TempHome::new();
let store = Store::open().expect("open"); let store = Store::open().expect("open");
let me = store.self_identity().expect("self"); let me = store.self_identity().expect("self");
let raw = qr::encode(&me.identity_sk, &v3onion("x"), &[1u8; 32]).unwrap(); let raw = qr::encode(&me.identity_sk, &v3onion("x"), &[1u8; 32], &me.kem_pk).unwrap();
let _p = qr::decode(&raw).unwrap(); let _p = qr::decode(&raw).unwrap();
assert_eq!(store.friend_count().unwrap(), 0); assert_eq!(store.friend_count().unwrap(), 0);
} }
@ -157,7 +158,7 @@ fn shifted_o_spk_is_err() {
let me = store.self_identity().expect("self"); let me = store.self_identity().expect("self");
let onion = v3onion("honest"); let onion = v3onion("honest");
let spk = [0xab; 32]; let spk = [0xab; 32];
let raw = qr::encode(&me.identity_sk, &onion, &spk).expect("encode"); let raw = qr::encode(&me.identity_sk, &onion, &spk, &me.kem_pk).expect("encode");
let (k, o, spk_hex, sig) = invite_fields(&raw); let (k, o, spk_hex, sig) = invite_fields(&raw);
assert_eq!(spk_hex.len(), 64); assert_eq!(spk_hex.len(), 64);
let mutant = format!( let mutant = format!(
@ -177,9 +178,9 @@ fn encode_rejects_spk_not_32() {
let store = Store::open().expect("open"); let store = Store::open().expect("open");
let me = store.self_identity().expect("self"); let me = store.self_identity().expect("self");
let onion = v3onion("spk"); let onion = v3onion("spk");
assert!(qr::encode(&me.identity_sk, &onion, &[1u8; 31]).is_err()); assert!(qr::encode(&me.identity_sk, &onion, &[1u8; 31], &me.kem_pk).is_err());
assert!(qr::encode(&me.identity_sk, &onion, &[1u8; 33]).is_err()); assert!(qr::encode(&me.identity_sk, &onion, &[1u8; 33], &me.kem_pk).is_err());
assert!(qr::encode(&me.identity_sk, &onion, &[]).is_err()); assert!(qr::encode(&me.identity_sk, &onion, &[], &me.kem_pk).is_err());
} }
#[test] #[test]
@ -188,9 +189,9 @@ fn encode_rejects_garbage_onion() {
let store = Store::open().expect("open"); let store = Store::open().expect("open");
let me = store.self_identity().expect("self"); let me = store.self_identity().expect("self");
let spk = [2u8; 32]; let spk = [2u8; 32];
assert!(qr::encode(&me.identity_sk, "not-an-onion", &spk).is_err()); assert!(qr::encode(&me.identity_sk, "not-an-onion", &spk, &me.kem_pk).is_err());
assert!(qr::encode(&me.identity_sk, "alice.onion", &spk).is_err()); assert!(qr::encode(&me.identity_sk, "alice.onion", &spk, &me.kem_pk).is_err());
assert!(qr::encode(&me.identity_sk, &format!("{}.onion", "A".repeat(56)), &spk).is_err()); assert!(qr::encode(&me.identity_sk, &format!("{}.onion", "A".repeat(56)), &spk, &me.kem_pk).is_err());
} }
#[test] #[test]
@ -198,7 +199,7 @@ fn decode_rejects_spk_len_and_garbage_onion() {
let _home = TempHome::new(); let _home = TempHome::new();
let store = Store::open().expect("open"); let store = Store::open().expect("open");
let me = store.self_identity().expect("self"); let me = store.self_identity().expect("self");
let raw = qr::encode(&me.identity_sk, &v3onion("ok"), &[3u8; 32]).expect("encode"); let raw = qr::encode(&me.identity_sk, &v3onion("ok"), &[3u8; 32], &me.kem_pk).expect("encode");
let (k, o, spk, sig) = invite_fields(&raw); let (k, o, spk, sig) = invite_fields(&raw);
let short_spk = format!("onionwire:v1:k={k}:o={o}:spk={}:sig={sig}", &spk[..62]); let short_spk = format!("onionwire:v1:k={k}:o={o}:spk={}:sig={sig}", &spk[..62]);
assert!(qr::decode(&short_spk).is_err()); assert!(qr::decode(&short_spk).is_err());
@ -206,6 +207,98 @@ fn decode_rejects_spk_len_and_garbage_onion() {
assert!(qr::decode(&garbage_o).is_err()); assert!(qr::decode(&garbage_o).is_err());
} }
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
/// A genuine legacy v1 invite: signature over the unconcatenated `k || o || spk`
/// (the historical layout), no `kem=` field.
fn legacy_v1(sk: &[u8; 32], onion: &str, spk: &[u8; 32]) -> String {
use ed25519_dalek::{Signer, SigningKey};
let signing = SigningKey::from_bytes(sk);
let k = hex(&signing.verifying_key().to_bytes());
let spk_hex = hex(spk);
let mut msg = Vec::new();
msg.extend_from_slice(k.as_bytes());
msg.extend_from_slice(onion.as_bytes());
msg.extend_from_slice(spk_hex.as_bytes());
let sig = hex(&signing.sign(&msg).to_bytes());
format!("onionwire:v1:k={k}:o={onion}:spk={spk_hex}:sig={sig}")
}
#[test]
fn invite_v2_decode_restores_the_kem_key() {
let _home = TempHome::new();
let store = Store::open().expect("open");
let me = store.self_identity().expect("self");
let raw = qr::encode(&me.identity_sk, &v3onion("kem"), &[4u8; 32], &me.kem_pk)
.expect("encode v2");
let p = qr::decode(&raw).expect("decode v2");
assert_eq!(p.kem_pk.as_deref(), Some(me.kem_pk.as_slice()));
assert!(p.kem_pk.as_deref().is_some_and(|k| k.len() == 1184));
}
#[test]
fn invite_v2_kem_strip_fails_signature_and_v1_downgrade_is_rejected() {
let _home = TempHome::new();
let store = Store::open().expect("open");
let me = store.self_identity().expect("self");
let raw = qr::encode(&me.identity_sk, &v3onion("strip"), &[5u8; 32], &me.kem_pk)
.expect("encode v2");
// Dropping the field from a v2 invite is not a valid v2 invite at all.
let stripped: String = raw
.split(':')
.filter(|field| !field.starts_with("kem="))
.collect::<Vec<_>>()
.join(":");
let err = qr::decode(&stripped).expect_err("v2 without kem must fail");
assert!(err.to_string().contains("missing kem"), "{err}");
// The anti-downgrade property: relabel the same bytes v1 and strip `kem=`.
// v1 verification covers a different preimage, so this cannot verify.
let downgraded: String = stripped.replacen("onionwire:v2:", "onionwire:v1:", 1);
let err = qr::decode(&downgraded).expect_err("v1 downgrade must fail");
assert!(err.to_string().contains("bad signature"), "{err}");
// Substituting a different (valid) encapsulation key must break the
// signature rather than silently changing who we encapsulate to.
let other_b64 = {
// Reuse encode by swapping: encode with the other key under the same
// identity would re-sign, so substitute in the serialized invite.
let mut s = raw.clone();
let start = s.find(":kem=").expect("kem field") + 5;
let end = start + s[start..].find(':').expect("kem terminator");
// A different key of the same length; signature still covers this slot.
s.replace_range(start..end, &"A".repeat(end - start));
s
};
let err = qr::decode(&other_b64).expect_err("kem substitution must fail");
assert!(err.to_string().contains("bad signature"), "{err}");
}
#[test]
fn invite_v1_still_decodes_to_a_classical_friend_row() {
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("legacy");
let spk = [8u8; 32];
let raw = legacy_v1(&sk, &onion, &spk);
let p = qr::decode(&raw).expect("legacy v1 decodes");
assert!(p.kem_pk.is_none(), "a v1 invite is a classical friend");
assert_eq!(p.signed_prekey, spk);
store.upsert_friend(&p.pubkey, &p.onion, None).expect("upsert");
store.set_friend_prekey(&p.pubkey, &p.signed_prekey).expect("prekey");
store
.set_friend_kem(&p.pubkey, p.kem_pk.as_deref())
.expect("clear kem");
let f = store.get_friend(&p.pubkey).expect("get").expect("row");
assert!(f.kem_pk.is_none(), "legacy friend row has no PQ key");
}
#[test] #[test]
fn huge_hex_is_err_quickly() { fn huge_hex_is_err_quickly() {
let huge = format!( let huge = format!(

View file

@ -51,6 +51,7 @@ impl Deliverer for Wire {
pinned_id: &'a [u8], pinned_id: &'a [u8],
_prekey: &'a [u8], _prekey: &'a [u8],
payload: &'a [u8], payload: &'a [u8],
_remote_kem: Option<&'a [u8]>,
) -> BoxFut<'a, Result<(), String>> { ) -> BoxFut<'a, Result<(), String>> {
self.queues self.queues
.lock() .lock()

View file

@ -74,6 +74,7 @@ impl Deliverer for Wire {
pinned_id: &'a [u8], pinned_id: &'a [u8],
_prekey: &'a [u8], _prekey: &'a [u8],
payload: &'a [u8], payload: &'a [u8],
_remote_kem: Option<&'a [u8]>,
) -> BoxFut<'a, Result<(), String>> { ) -> BoxFut<'a, Result<(), String>> {
if self.fail_next.load(Ordering::SeqCst) > 0 { if self.fail_next.load(Ordering::SeqCst) > 0 {
self.fail_next.fetch_sub(1, Ordering::SeqCst); self.fail_next.fetch_sub(1, Ordering::SeqCst);

View file

@ -46,6 +46,7 @@ impl Deliverer for Recorder {
_pinned_id: &'a [u8], _pinned_id: &'a [u8],
_prekey: &'a [u8], _prekey: &'a [u8],
payload: &'a [u8], payload: &'a [u8],
_remote_kem: Option<&'a [u8]>,
) -> BoxFut<'a, Result<(), String>> { ) -> BoxFut<'a, Result<(), String>> {
self.sent.lock().unwrap().push(payload.to_vec()); self.sent.lock().unwrap().push(payload.to_vec());
if self.fail_times.load(Ordering::SeqCst) > 0 { if self.fail_times.load(Ordering::SeqCst) > 0 {

View file

@ -334,8 +334,8 @@ fn share_screen_shows_invite_not_qr_at_80x24() {
let sk = [7u8; 32]; let sk = [7u8; 32];
let onion = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; let onion = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion";
let payload = qr::encode(&sk, onion, &[1u8; 32]).expect("encode"); let payload = qr::encode(&sk, onion, &[1u8; 32], &[9u8; 1184]).expect("encode");
assert!(payload.starts_with("onionwire:v1:")); assert!(payload.starts_with("onionwire:v2:"));
let backend = TestBackend::new(80, 24); let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal"); let mut terminal = Terminal::new(backend).expect("terminal");
@ -349,7 +349,7 @@ fn share_screen_shows_invite_not_qr_at_80x24() {
screen.push('\n'); screen.push('\n');
} }
assert!( assert!(
screen.contains("onionwire:v1:"), screen.contains("onionwire:v2:"),
"share screen missing invite prefix:\n{screen}" "share screen missing invite prefix:\n{screen}"
); );
for ch in ['█', '▀', '▄'] { for ch in ['█', '▀', '▄'] {
@ -419,6 +419,7 @@ fn share_payload_rebuilds_from_the_frame_at_80x24_and_120x40() {
&[7u8; 32], &[7u8; 32],
"abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion", "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion",
&[1u8; 32], &[1u8; 32],
&[9u8; 1184],
) )
.expect("encode"); .expect("encode");
@ -437,13 +438,19 @@ fn share_payload_rebuilds_from_the_frame_at_80x24_and_120x40() {
// Trailing cells are the frame's pad, not the payload; nothing else is // Trailing cells are the frame's pad, not the payload; nothing else is
// removed — no gutter is allowed to be there in the first place. // removed — no gutter is allowed to be there in the first place.
let rebuilt: String = rows.iter().map(|r| r.trim_end()).collect(); let rebuilt: String = rows.iter().map(|r| r.trim_end()).collect();
assert_eq!( // A v2 invite is ~1.9 KB. A short terminal cannot show all of it, so
rebuilt, // the frame must either carry the whole payload in order or a faithful
payload, // prefix of it — never a reordered, interleaved or chrome-contaminated
"mouse-selecting the invite at {w}x{h} does not rebuild the payload:\n\ // one. `C`/OSC 52 copies the payload itself.
assert!(
payload.starts_with(&rebuilt) && !rebuilt.is_empty(),
"mouse-selecting the invite at {w}x{h} does not rebuild a payload prefix:\n\
got {rebuilt:?}\nwant {payload:?}\nframe:\n{}", got {rebuilt:?}\nwant {payload:?}\nframe:\n{}",
frame_text(&buf, w, h) frame_text(&buf, w, h)
); );
if rebuilt.len() == payload.len() {
assert_eq!(rebuilt, payload, "full payload rebuild differs");
}
} }
} }
@ -453,6 +460,7 @@ fn share_payload_rows_carry_no_border_glyph() {
&[7u8; 32], &[7u8; 32],
"abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion", "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion",
&[1u8; 32], &[1u8; 32],
&[9u8; 1184],
) )
.expect("encode"); .expect("encode");
@ -493,6 +501,7 @@ fn share_copy_key_sequence_carries_the_payload_exactly() {
&[7u8; 32], &[7u8; 32],
"abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion", "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion",
&[1u8; 32], &[1u8; 32],
&[9u8; 1184],
) )
.expect("encode"); .expect("encode");
let seq = osc52_copy_sequence(&payload); let seq = osc52_copy_sequence(&payload);

View file

@ -19,7 +19,8 @@ use onionwire::tui::{
cell_width, chat_no_friends_lines, chat_with_delivery, compact_banner, draw_main_chrome, cell_width, chat_no_friends_lines, chat_with_delivery, compact_banner, draw_main_chrome,
draw_share, draw_text_overlay, fingerprint_mismatch_banner, help_overlay_text, draw_share, draw_text_overlay, fingerprint_mismatch_banner, help_overlay_text,
main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text, rotate_screen_text, main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text, rotate_screen_text,
status_footer, who_overlay_text, wipe_screen_text, wordmark_banner, ProfileEditor, WipeKind, roster_line, status_footer, who_overlay_text, wipe_screen_text, wordmark_banner, ProfileEditor,
WipeKind,
}; };
use onionwire::{FriendProfile, Message}; use onionwire::{FriendProfile, Message};
use ratatui::Frame; use ratatui::Frame;
@ -90,15 +91,46 @@ fn friend_rows() -> Vec<FriendRow> {
label: "alice".into(), label: "alice".into(),
fingerprint: "aaaaaaaaaaaaaaaa".into(), fingerprint: "aaaaaaaaaaaaaaaa".into(),
stale: false, stale: false,
pq: true,
}, },
FriendRow { FriendRow {
label: "bob-the-stale-peer".into(), label: "bob-the-stale-peer".into(),
fingerprint: "bbbbbbbbbbbbbbbb".into(), fingerprint: "bbbbbbbbbbbbbbbb".into(),
stale: true, stale: true,
pq: true,
}, },
] ]
} }
#[test]
fn a_legacy_friend_row_says_classical_in_the_roster() {
let pq = FriendRow {
label: "alice".into(),
fingerprint: "aaaaaaaaaaaaaaaa".into(),
stale: false,
pq: true,
};
let legacy = FriendRow {
pq: false,
..pq.clone()
};
let pq_text: String = roster_line(&pq, 40).spans.iter().map(|s| s.content.clone()).collect();
let legacy_text: String = roster_line(&legacy, 40)
.spans
.iter()
.map(|s| s.content.clone())
.collect();
assert!(pq_text.contains("alice"), "{pq_text}");
assert!(
!pq_text.contains("classical"),
"a v2 friend must not be labelled classical: {pq_text}"
);
assert!(
legacy_text.contains("classical"),
"a v1 friend must be visibly labelled as lacking PQ protection: {legacy_text}"
);
}
fn out_msg(id: i64, body: &str) -> Message { fn out_msg(id: i64, body: &str) -> Message {
Message { Message {
id, id,
@ -152,7 +184,7 @@ fn empty_chat(phase: TorPhase) -> Vec<String> {
#[test] #[test]
fn dump_audit_frames() { fn dump_audit_frames() {
let invite = qr::encode(&[7u8; 32], ONION, &[1u8; 32]).expect("encode"); let invite = qr::encode(&[7u8; 32], ONION, &[1u8; 32], &[9u8; 1184]).expect("encode");
let friends = friend_rows(); let friends = friend_rows();
let chat = chat_ok(); let chat = chat_ok();
let (queued_chat, queued_note) = chat_queued(); let (queued_chat, queued_note) = chat_queued();
@ -744,7 +776,7 @@ fn status_footer_drops_send_failed_when_crowded() {
#[test] #[test]
fn share_invite_wraps_at_three_sizes() { fn share_invite_wraps_at_three_sizes() {
let invite = qr::encode(&[7u8; 32], ONION, &[1u8; 32]).expect("encode"); let invite = qr::encode(&[7u8; 32], ONION, &[1u8; 32], &[9u8; 1184]).expect("encode");
for (w, h) in SIZES { for (w, h) in SIZES {
let backend = TestBackend::new(w, h); let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal"); let mut terminal = Terminal::new(backend).expect("terminal");
@ -757,7 +789,7 @@ fn share_invite_wraps_at_three_sizes() {
} }
screen.push('\n'); screen.push('\n');
} }
assert!(screen.contains("onionwire:v1:"), "{w}x{h}\n{screen}"); assert!(screen.contains("onionwire:v2:"), "{w}x{h}\n{screen}");
assert!(screen.contains("(o) invite"), "{w}x{h}\n{screen}"); assert!(screen.contains("(o) invite"), "{w}x{h}\n{screen}");
} }
} }

View file

@ -229,7 +229,7 @@ fn dump_spec_frames() {
fn sample_invite() -> String { fn sample_invite() -> String {
let sk = [7u8; 32]; let sk = [7u8; 32];
qr::encode(&sk, ONION, &[1u8; 32]).expect("encode") qr::encode(&sk, ONION, &[1u8; 32], &[9u8; 1184]).expect("encode")
} }
fn invite_line_ok(line: &str) -> bool { fn invite_line_ok(line: &str) -> bool {
@ -240,7 +240,17 @@ fn invite_line_ok(line: &str) -> bool {
|| t.starts_with("o=") || t.starts_with("o=")
|| t.starts_with("spk=") || t.starts_with("spk=")
|| t.starts_with("sig=") || t.starts_with("sig=")
|| t.starts_with("kem=")
|| t.chars().all(|c| c.is_ascii_hexdigit()) || t.chars().all(|c| c.is_ascii_hexdigit())
// Continuation chunks of the long base64url `kem=` field (1579 chars,
// so it must be split even though there is no internal delimiter).
|| {
let body = t.trim_end_matches(':');
!body.is_empty()
&& body
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
}
} }
#[test] #[test]
@ -286,11 +296,12 @@ fn wrap_invite_breaks_on_field_boundaries() {
); );
} }
assert!( assert!(
wrapped.contains("onionwire:v1:"), wrapped.contains("onionwire:v2:"),
"lost invite prefix:\n{wrapped}" "lost invite prefix:\n{wrapped}"
); );
assert!(wrapped.contains("k="), "lost k= field:\n{wrapped}"); assert!(wrapped.contains("k="), "lost k= field:\n{wrapped}");
assert!(wrapped.contains("spk="), "lost spk= field:\n{wrapped}"); assert!(wrapped.contains("spk="), "lost spk= field:\n{wrapped}");
assert!(wrapped.contains("kem="), "lost kem= field:\n{wrapped}");
let joined: String = wrapped.lines().map(str::trim).collect(); let joined: String = wrapped.lines().map(str::trim).collect();
assert_eq!( assert_eq!(
joined, invite, joined, invite,
@ -306,7 +317,7 @@ fn draw_share_invite_does_not_wrap_mid_token() {
terminal.draw(|f| draw_share(f, &invite)).expect("draw"); terminal.draw(|f| draw_share(f, &invite)).expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24); let screen = screen_from(terminal.backend().buffer(), 80, 24);
assert!( assert!(
screen.contains("onionwire:v1:"), screen.contains("onionwire:v2:"),
"missing prefix:\n{screen}" "missing prefix:\n{screen}"
); );
for raw in screen.lines() { for raw in screen.lines() {
@ -317,7 +328,15 @@ fn draw_share_invite_does_not_wrap_mid_token() {
|| inner.starts_with("o=") || inner.starts_with("o=")
|| inner.starts_with("spk=") || inner.starts_with("spk=")
|| inner.starts_with("sig=") || inner.starts_with("sig=")
|| inner.starts_with("kem=")
|| inner.chars().all(|c| c.is_ascii_hexdigit()) || inner.chars().all(|c| c.is_ascii_hexdigit())
|| {
let body = inner.trim_end_matches(':');
!body.is_empty()
&& body
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
}
{ {
assert!( assert!(
invite_line_ok(inner), invite_line_ok(inner),
@ -782,6 +801,7 @@ async fn renders_a_queued_row_from_a_real_outbox_send() {
_pinned_id: &'a [u8], _pinned_id: &'a [u8],
_prekey: &'a [u8], _prekey: &'a [u8],
_plaintext: &'a [u8], _plaintext: &'a [u8],
_remote_kem: Option<&'a [u8]>,
) -> BoxFut<'a, Result<(), String>> { ) -> BoxFut<'a, Result<(), String>> {
Box::pin(async { Err("connect dead.onion:80: timed out".to_string()) }) Box::pin(async { Err("connect dead.onion:80: timed out".to_string()) })
} }