diff --git a/Cargo.lock b/Cargo.lock index 52967c1..1aefb4a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1095,7 +1095,9 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ + "getrandom 0.4.3", "hybrid-array", + "rand_core 0.10.1", ] [[package]] @@ -1802,6 +1804,16 @@ dependencies = [ "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]] name = "der-parser" version = "10.0.0" @@ -1998,12 +2010,12 @@ version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ - "der", + "der 0.7.10", "digest 0.10.7", "elliptic-curve", "rfc6979", "signature", - "spki", + "spki 0.7.3", ] [[package]] @@ -2012,7 +2024,7 @@ version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" dependencies = [ - "pkcs8", + "pkcs8 0.10.2", "signature", ] @@ -2062,7 +2074,7 @@ dependencies = [ "ff", "generic-array", "group", - "pkcs8", + "pkcs8 0.10.2", "rand_core 0.6.4", "sec1", "subtle", @@ -2714,6 +2726,7 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ + "ctutils", "typenum", "zeroize", ] @@ -3163,6 +3176,16 @@ dependencies = [ "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]] name = "konst" version = "0.2.20" @@ -3428,6 +3451,34 @@ dependencies = [ "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]] name = "monero-address" version = "0.1.0" @@ -3785,6 +3836,7 @@ dependencies = [ "hkdf", "hmac", "md-5", + "ml-kem", "qrcode", "rand 0.8.8", "ratatui", @@ -4097,9 +4149,9 @@ version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" dependencies = [ - "der", - "pkcs8", - "spki", + "der 0.7.10", + "pkcs8 0.10.2", + "spki 0.7.3", ] [[package]] @@ -4108,8 +4160,18 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" dependencies = [ - "der", - "spki", + "der 0.7.10", + "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]] @@ -4700,11 +4762,11 @@ dependencies = [ "num-integer", "num-traits", "pkcs1", - "pkcs8", + "pkcs8 0.10.2", "rand_core 0.6.4", "sha2", "signature", - "spki", + "spki 0.7.3", "subtle", "zeroize", ] @@ -4913,9 +4975,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ "base16ct", - "der", + "der 0.7.10", "generic-array", - "pkcs8", + "pkcs8 0.10.2", "subtle", "zeroize", ] @@ -5150,6 +5212,17 @@ dependencies = [ "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]] name = "sharded-slab" version = "0.1.7" @@ -5323,7 +5396,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" dependencies = [ "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]] @@ -5544,7 +5627,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" dependencies = [ "rustix", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index d456e5a..7a16989 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -75,6 +75,10 @@ sha2 = "0.10" md-5 = "0.10" rpassword = "7" 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 } 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 diff --git a/README.md b/README.md index ec9baec..edfe175 100644 --- a/README.md +++ b/README.md @@ -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. 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 -is no invite QR graphic. Chat is Noise IK over your own v3 onion; every chat -message is ratcheted inside that session. Unreachable chat peers go to a **local +each other with an `onionwire:v2:…` invite string (`F2` share / `F3` paste; +~1.9 KB because it carries an ML-KEM-768 key). There is no invite QR graphic. +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 fail closed. Optional Monero: `/pay` invoices, `/tip` payments, and in-app wallet 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 | | `g` / `G` | Jump to top / bottom of the focused pane | | `?` | Keybinding help (`Esc` closes) | -| `F2` | Share invite (`onionwire:v1:…`) | +| `F2` | Share invite (`onionwire:v2:…`, ~1.9 KB) | | `F3` | Paste a friend's invite | | `F4` | Rotate **onion** (locator only) | | `F5` | Selected friend's profile (`/who`) | | `F6` | Wallet (receive QR, balance, transfers, create/import) | | `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`) | | Enter | Send chat to the selected friend, or run a `/command` | | `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, 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. -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 @@ -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. - `/wipe` clears chat, payments and outbox but **keeps** ratchet state. `/wipe-all` removes the data dir. -- There is no `/reset`. State drops when the friend's prekey changes (you - `F3`-paste a refreshed invite). +- There is no `/reset`. State drops when the friend's prekey or ML-KEM key + 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 `rat dropped ()` on stderr and dropped. There is no in-app desync banner. diff --git a/crates/onionwire-sdk/Cargo.lock b/crates/onionwire-sdk/Cargo.lock index fa1d2d2..7f178c8 100644 --- a/crates/onionwire-sdk/Cargo.lock +++ b/crates/onionwire-sdk/Cargo.lock @@ -1181,7 +1181,9 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ + "getrandom 0.4.3", "hybrid-array", + "rand_core 0.10.1", ] [[package]] @@ -1888,6 +1890,16 @@ dependencies = [ "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]] name = "der-parser" version = "10.0.0" @@ -2084,12 +2096,12 @@ version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ - "der", + "der 0.7.10", "digest 0.10.7", "elliptic-curve", "rfc6979", "signature", - "spki", + "spki 0.7.3", ] [[package]] @@ -2098,7 +2110,7 @@ version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" dependencies = [ - "pkcs8", + "pkcs8 0.10.2", "signature", ] @@ -2148,7 +2160,7 @@ dependencies = [ "ff", "generic-array", "group", - "pkcs8", + "pkcs8 0.10.2", "rand_core 0.6.4", "sec1", "subtle", @@ -2811,6 +2823,7 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ + "ctutils", "typenum", "zeroize", ] @@ -3260,6 +3273,16 @@ dependencies = [ "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]] name = "konst" version = "0.2.20" @@ -3525,6 +3548,34 @@ dependencies = [ "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]] name = "monero-address" version = "0.1.0" @@ -3865,6 +3916,7 @@ dependencies = [ "hkdf", "hmac", "md-5", + "ml-kem", "qrcode", "rand 0.8.8", "ratatui", @@ -4156,9 +4208,9 @@ version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" dependencies = [ - "der", - "pkcs8", - "spki", + "der 0.7.10", + "pkcs8 0.10.2", + "spki 0.7.3", ] [[package]] @@ -4167,8 +4219,18 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" dependencies = [ - "der", - "spki", + "der 0.7.10", + "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]] @@ -4765,11 +4827,11 @@ dependencies = [ "num-integer", "num-traits", "pkcs1", - "pkcs8", + "pkcs8 0.10.2", "rand_core 0.6.4", "sha2", "signature", - "spki", + "spki 0.7.3", "subtle", "zeroize", ] @@ -4989,9 +5051,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ "base16ct", - "der", + "der 0.7.10", "generic-array", - "pkcs8", + "pkcs8 0.10.2", "subtle", "zeroize", ] @@ -5207,6 +5269,17 @@ dependencies = [ "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]] name = "sharded-slab" version = "0.1.7" @@ -5386,7 +5459,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" dependencies = [ "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]] @@ -5607,7 +5690,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" dependencies = [ "rustix", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 35d4b70..390d653 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -103,6 +103,10 @@ pub struct FriendInfo { /// Current locator. May be stale if the peer rotated while you were down. pub onion: String, 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. @@ -190,6 +194,8 @@ pub struct RotateOutcome { pub struct InviteInfo { pub pubkey_hex: 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. @@ -300,6 +306,7 @@ pub fn decode_invite(invite: String) -> WResult { Ok(InviteInfo { pubkey_hex: hex(&p.pubkey), onion: p.onion, + pq: p.kem_pk.is_some(), }) } @@ -388,6 +395,7 @@ impl Wire { petname: f.petname, onion: f.onion, last_connect_ok: f.last_connect_ok, + pq: f.kem_pk.is_some(), }) .collect()) } @@ -405,6 +413,7 @@ impl Wire { petname: f.petname, onion: f.onion, last_connect_ok: f.last_connect_ok, + pq: f.kem_pk.is_some(), }) } @@ -1656,6 +1665,17 @@ mod tests { .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] fn tor_state_of_a_stopped_handle_is_stopped() { assert_eq!(stopped_wire().tor_state(), TorState::Stopped); diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 07c07fd..c22f75e 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -4,8 +4,9 @@ This is the wire protocol. A second implementation should be able to interoperate from this document without reading the Rust. 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 -third-party audit. Arti onion services are experimental upstream. +(frame versions 1 and 2, invite schemes `onionwire:v2` (emit) and +`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). @@ -32,13 +33,20 @@ Each install holds: - **Identity** — ed25519 keypair. The 32-byte public key **is** the person. Roster primary key. Displayed as 64 lowercase hex chars (the fingerprint). - **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 - the onion (`F4`) does **not** rotate it. + — rotate it with `F8`, which hard-cuts every stored session. Rotating the + 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. -A friend is `{identity_pk, current_onion, current_prekey_pk}`. Pasting the same -identity `k` updates the locator (and prekey) on that row. It never creates a -second person. +A friend is `{identity_pk, current_onion, current_prekey_pk, kem_pk?}`. Pasting +the same identity `k` updates the locator, prekey and KEM key on that row. It +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 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: ``` -uint8 version = 1 +uint8 version = 1 (normal) | 2 (PQ handshake prelude) uint32 length = big-endian 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. - Other `version` values are a hard fail (close the stream). - 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` -Prologue (both sides, before the first handshake message): `onionwire-v1` -(13 ASCII bytes, no NUL). +Prologue (both sides, before the first Noise handshake message): + +- **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 hard fail. ### Sequence -Initiator knows the responder’s identity pubkey (pinned) and x25519 prekey -from the invite (or roster). +Initiator knows the responder’s identity pubkey (pinned), x25519 prekey and +(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 - the invite `spk`. +0. **PQ prelude** — only when the responder’s roster row has `kem_pk`: + 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**. 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). 4. Both sides enter transport mode. Handshake hash `h` is 32 bytes (BLAKE2s). 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 (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. +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 @@ -566,28 +623,39 @@ the new invite is the signal. Not a QR graphic. A single ASCII string, max 4096 characters: ``` -onionwire:v1:k=<64 hex>:o=:spk=<64 hex>:sig=<128 hex> +onionwire:v2:k=<64 hex>:o=:spk=<64 hex>:kem=:sig=<128 hex> ``` 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 -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):** ``` 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 -(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` -(no domain tag, no separators) is still accepted on decode so old invites -verify. New invites MUST use the domain-separated form. Do not emit legacy. +**Legacy accept (`onionwire:v1`):** a v1 invite has no `kem` field. Decode +accepts it and yields a friend with no `kem_pk`, i.e. a classical peer. A v1 +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 @@ -604,8 +672,12 @@ path”). They are out of scope, not postponed. ## Versioning -- Frame `version` 1 and invite `onionwire:v1` are this document. -- A new handshake prologue or a new invite scheme is a breaking change. +- Frame `version` 1 (normal), frame `version` 2 (PQ prelude), invite + `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. - 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 diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index dadf0cf..22ae450 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -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 -`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 diff --git a/src/frame.rs b/src/frame.rs index 8dbb67c..f4aec8e 100644 --- a/src/frame.rs +++ b/src/frame.rs @@ -1,6 +1,9 @@ use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; 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 type Result = std::result::Result; @@ -53,11 +56,65 @@ pub async fn write_frame(w: &mut W, body: &[u8]) -> Resul } pub async fn read_frame(r: &mut R) -> Result> { + 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), + Prelude(Vec), +} + +pub async fn read_opening(r: &mut R) -> Result { + 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: &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> { + 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: &mut R) -> Result<(u8, Vec)> { let mut hdr = [0u8; 5]; r.read_exact(&mut hdr) .await .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())); } 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: &mut R) -> Result> { r.read_exact(&mut body) .await .map_err(|e| Error(e.to_string()))?; - Ok(body) + Ok((version, body)) +} + +fn encode_version(version: u8, body: &[u8]) -> Result> { + 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) } diff --git a/src/kem.rs b/src/kem.rs new file mode 100644 index 0000000..a43424e --- /dev/null +++ b/src/kem.rs @@ -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 = std::result::Result; + +#[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> { + let ek = encapsulation_key(pk)?; + Ok(ek.to_bytes().as_slice().to_vec()) +} + +pub fn decode_pk(bytes: &[u8]) -> Result> { + encode_pk(bytes) +} + +pub fn encapsulate(pk: &[u8]) -> Result<(Vec, Vec)> { + 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> { + if ct.len() != CT_LEN { + return Err(Error("ct length".into())); + } + Ok(ct.to_vec()) +} + +pub fn decode_ct(bytes: &[u8]) -> Result> { + encode_ct(bytes) +} + +pub fn decapsulate(seed: &[u8], ct: &[u8]) -> Result> { + 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 { + if pk.len() != PK_LEN { + return Err(Error("pk length".into())); + } + let key = ml_kem::kem::Key::::try_from(pk) + .map_err(|_| Error("pk length".into()))?; + EncapsulationKey768::new(&key).map_err(|_| Error("invalid encapsulation key".into())) +} diff --git a/src/lib.rs b/src/lib.rs index 9e4c7c2..70a7059 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ pub mod dispatch; pub mod file; pub mod frame; pub mod hs; +pub mod kem; pub mod loc; pub mod node; pub mod outbox; diff --git a/src/node.rs b/src/node.rs index b39a4e8..c2b0315 100644 --- a/src/node.rs +++ b/src/node.rs @@ -427,7 +427,7 @@ impl Node { pub fn qr_payload(&self) -> Result { 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> { @@ -456,6 +456,10 @@ impl Node { pub fn restore_backup(&self, path: &str, passphrase: &str) -> Result<(), String> { let blob = std::fs::read(path).map_err(|e| e.to_string())?; let k = crate::backup::open(passphrase, &blob)?; + let (kem_seed, kem_pk) = { + let cur = self.keys()?; + (cur.kem_seed, cur.kem_pk) + }; self.store .lock() .map_err(|e| e.to_string())? @@ -466,6 +470,11 @@ impl Node { identity_pk: k.identity_pk, prekey_sk: k.prekey_sk, 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(()) } @@ -477,21 +486,30 @@ impl Node { pub fn add_friend_payload(&self, p: &qr::QrPayload) -> Result<(), String> { let store = self.store.lock().map_err(|e| e.to_string())?; - let prekey_changed = store + let existing = store .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) .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 .upsert_friend(&p.pubkey, &p.onion, None) .map_err(|e| e.to_string())?; store .set_friend_prekey(&p.pubkey, &p.signed_prekey) .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, - // so a refreshed invite makes the stored ratchet state unusable on - // both sides. Drop it: the next frame rebuilds a fresh state. + // and a new KEM key is the same hard cut as F8: the stored ratchet + // state is unusable. Drop it; the next frame rebuilds a fresh state. store.clear_ratchet(&p.pubkey).map_err(|e| e.to_string())?; } Ok(()) @@ -1216,14 +1234,15 @@ impl Node { ) .map_err(|e| e.to_string())?; let pt = profile::encode(&prf); - let (onion, prekey) = { + let (onion, prekey, kem) = { let f = self.friend(friend_pk)?; if f.prekey.len() != 32 { 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. @@ -1719,14 +1738,15 @@ impl Node { async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> { self.ensure_running()?; - let (onion, prekey) = { + let (onion, prekey, kem) = { let f = self.friend(friend_pk)?; if f.prekey.len() != 32 { 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 @@ -1801,7 +1821,7 @@ impl Node { let mut notified = 0; for f in &friends { 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 .is_ok() { @@ -1815,17 +1835,18 @@ impl Node { }) } - /// Rotate the long-lived signed prekey (F8). Hard cut, like the locator - /// rotate: the prekey is our Noise static and the bootstrap ratchet epoch is + /// Rotate the long-lived signed prekey and the ML-KEM-768 key together (F8). + /// 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 /// 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 - /// identity key (and therefore the fingerprint) does not move; the caller - /// re-encodes the F2 invite around the returned pubkey. + /// pushed to peers — a new prekey or KEM key only travels inside a signed + /// invite. The identity key (and therefore the fingerprint) does not move. pub fn rotate_prekey(&self) -> Result<[u8; 32], String> { let mut k = self.keys()?; let sk = StaticSecret::random_from_rng(OsRng); let pk = X25519Public::from(&sk).to_bytes(); + let kem_kp = crate::kem::generate(); { let store = self.store.lock().map_err(|e| e.to_string())?; // `replace_identity_keys` rewrites the prekey columns too; the @@ -1833,12 +1854,17 @@ impl Node { store .replace_identity_keys(&k.identity_sk, &k.identity_pk, &sk.to_bytes(), &pk) .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())? { store.clear_ratchet(&f.pubkey).map_err(|e| e.to_string())?; } } k.prekey_sk = sk.to_bytes(); 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; Ok(pk) } @@ -1907,6 +1933,7 @@ impl Node { friend_pk: &[u8], onion: &str, prekey: &[u8], + remote_kem: Option<&[u8]>, loc_pt: &[u8], ) -> Result<(), String> { if prekey.len() != 32 { @@ -1915,7 +1942,10 @@ impl Node { let deadline = Instant::now() + Duration::from_secs(180); let mut last = None::; 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(()), Err(e) if e.contains("fingerprint mismatch") => return Err(e), Err(e) => last = Some(e), @@ -1931,10 +1961,11 @@ impl Node { pinned_id: &[u8], remote_prekey: &[u8], plaintext: &[u8], + remote_kem: Option<&[u8]>, ) -> Result<(), String> { self.outbox .deliverer() - .deliver(onion, pinned_id, remote_prekey, plaintext) + .deliver(onion, pinned_id, remote_prekey, plaintext, remote_kem) .await } @@ -1948,7 +1979,10 @@ impl Node { let Ok(g) = store.lock() else { 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 .map_err(session_err)?; @@ -2577,6 +2611,7 @@ pub(crate) mod tests { _pinned_id: &'a [u8], _prekey: &'a [u8], _payload: &'a [u8], + _remote_kem: Option<&'a [u8]>, ) -> crate::outbox::BoxFut<'a, Result<(), 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 } + 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 /// 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_prekey = node_prekey(node); let (client_side, server_side) = tokio::io::duplex(64 * 1024); let send = async { let mut stream = Duplex(client_side); - let mut sess = session::handshake_initiator(&mut stream, peer, &node_pk, &node_prekey) - .await - .map_err(|e| e.into_message())?; + let mut sess = session::handshake_initiator( + &mut stream, + 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())?; frame::write_frame(&mut stream, &ct) .await @@ -2709,8 +2759,13 @@ pub(crate) mod tests { node.handle_incoming(&mut stream).await }; let (sent, received) = futures::join!(send, receive); - sent?; - received + // The responder's error is the diagnostic one (e.g. a downgrade + // 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)> { @@ -2792,7 +2847,9 @@ pub(crate) mod tests { let frame = 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!( 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] async fn the_receive_path_keeps_arrival_order_and_drops_replays_and_garbage() { let dir = tempfile::tempdir().unwrap(); @@ -2830,17 +2955,17 @@ pub(crate) mod tests { .collect(); // 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[0]).await.unwrap(); - deliver_frame(&node, &peer, &frames[1]).await.unwrap(); + deliver_frame(&node, &peer, &frames[2], None).await.unwrap(); + deliver_frame(&node, &peer, &frames[0], None).await.unwrap(); + deliver_frame(&node, &peer, &frames[1], None).await.unwrap(); // A replay of an already-consumed frame, and a corrupted one: both are // dropped inside `handle_incoming` without a chat row and without // 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 last = corrupt.len() - 1; corrupt[last] ^= 0x01; - deliver_frame(&node, &peer, &corrupt).await.unwrap(); + deliver_frame(&node, &peer, &corrupt, None).await.unwrap(); assert_eq!( chat_lines(&node, &peer), @@ -2864,6 +2989,7 @@ pub(crate) mod tests { _pinned_id: &'a [u8], _prekey: &'a [u8], _payload: &'a [u8], + _remote_kem: Option<&'a [u8]>, ) -> crate::outbox::BoxFut<'a, Result<(), String>> { Box::pin(async { Ok(()) }) } @@ -2997,6 +3123,7 @@ pub(crate) mod tests { let peer = Keys::generate(); let old_identity = node.identity_pk(); let old_prekey = node_prekey(&node); + let old_kem = node_kem_pk(&node); *node.onion.lock().unwrap() = format!("{}.onion", "a".repeat(56)); { 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_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!( node.identity_pk(), old_identity, @@ -3022,6 +3154,11 @@ pub(crate) mod tests { new_prekey.to_vec(), "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!( store.load_ratchet(&peer.identity_pk).unwrap().is_none(), "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")) .expect("the re-encoded invite decodes"); 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!( payload.pubkey, old_identity.to_vec(), diff --git a/src/outbox.rs b/src/outbox.rs index 325b9a3..62a01c8 100644 --- a/src/outbox.rs +++ b/src/outbox.rs @@ -21,6 +21,10 @@ use crate::store::Store; 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, Option>); + /// First retry waits this long. pub const BACKOFF_START_SECS: i64 = 30; /// Backoff never sleeps longer than this. @@ -50,6 +54,8 @@ const PERMANENT_ERRORS: &[&str] = &[ "fingerprint mismatch", "bad identity proof", "unexpected handshake payload", + "prelude required", + "unexpected prelude", "frame too large", "bad version", "length mismatch", @@ -69,6 +75,7 @@ pub trait Deliverer: Send + Sync { pinned_id: &'a [u8], prekey: &'a [u8], plaintext: &'a [u8], + remote_kem: Option<&'a [u8]>, ) -> BoxFut<'a, Result<(), String>>; } @@ -92,6 +99,7 @@ impl Deliverer for ArtiDeliverer { pinned_id: &'a [u8], prekey: &'a [u8], plaintext: &'a [u8], + remote_kem: Option<&'a [u8]>, ) -> BoxFut<'a, Result<(), String>> { Box::pin(async move { let mut stream = self @@ -100,7 +108,7 @@ impl Deliverer for ArtiDeliverer { .await .map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?; 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 .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], payload: Option<&[u8]>, ) -> Result { - let (onion, prekey) = self.target(friend_pk)?; + let (onion, prekey, kem) = self.target(friend_pk)?; 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(()) => { self.store()?.append_message(friend_pk, "out", plaintext)?; Ok(OutboxStatus::Sent) @@ -266,7 +277,7 @@ impl Outbox { let mut out = Vec::with_capacity(rows.len()); for entry in rows { 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, Err(e) => { self.store()?.mark_outbox_failed(entry.id, now, &e)?; @@ -282,6 +293,7 @@ impl Outbox { &prekey, // Chat stores its frame here; everything else sends its body. entry.payload.as_deref().unwrap_or(&entry.body), + kem.as_deref(), ) .await; let status = match result { @@ -311,9 +323,10 @@ impl Outbox { Ok(out) } - /// Friend's current locator + Noise static. Missing prekey means the invite - /// was never completed — retrying cannot fix that, so it is fatal. - fn target(&self, friend_pk: &[u8]) -> Result<(String, Vec), String> { + /// Friend's current locator, Noise static, and KEM encapsulation key. + /// Missing prekey means the invite was never completed — retrying cannot + /// fix that, so it is fatal. `None` kem is a legacy v1 friend. + fn target(&self, friend_pk: &[u8]) -> Result { let store = self.store()?; let f = store .get_friend(friend_pk) @@ -322,7 +335,7 @@ impl Outbox { if f.prekey.len() != 32 { return Err("friend missing prekey".into()); } - Ok((f.onion, f.prekey)) + Ok((f.onion, f.prekey, f.kem_pk)) } fn store(&self) -> Result, String> { diff --git a/src/qr.rs b/src/qr.rs index 3746775..cc8504d 100644 --- a/src/qr.rs +++ b/src/qr.rs @@ -1,6 +1,8 @@ use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use zeroize::Zeroizing; +use crate::kem; + pub type Result = std::result::Result; #[derive(Debug)] @@ -19,19 +21,33 @@ pub struct QrPayload { pub pubkey: Vec, pub onion: String, pub signed_prekey: Vec, + /// `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>, } -/// 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 HEX_K: usize = 64; const HEX_SPK: usize = 64; const HEX_SIG: usize = 128; -/// `onionwire:v1:k={pubkey_hex}:o={v3onion}:spk={signed_prekey}:sig={sign(v2)}` -pub fn encode(identity_sk: &[u8], onion: &str, signed_prekey: &[u8]) -> Result { +/// Encode a v2 invite. v1 is decode-only. +/// +/// `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 { if signed_prekey.len() != 32 { 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) { 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 Result { if raw.len() > MAX_INVITE { 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) { return Err(Error("k must be 32 bytes".into())); } @@ -77,19 +96,46 @@ pub fn decode(raw: &str) -> Result { .map_err(|_| Error("sig must be 64 bytes".into()))?; let vk = VerifyingKey::from_bytes(&pk_arr).map_err(|e| Error(e.to_string()))?; let signature = Signature::from_bytes(&sig_arr); - let ok_v2 = vk - .verify(&sign_msg_v2(&k, &onion, &spk), &signature) - .is_ok(); - let ok_v1 = vk - .verify(&sign_msg_v1(&k, &onion, &spk), &signature) - .is_ok(); - if !ok_v2 && !ok_v1 { - return Err(Error("bad signature".into())); - } + let kem_pk = match version { + 1 => { + if kem_ascii.is_some() { + return Err(Error("unknown field".into())); + } + let ok_tagged = vk + .verify(&sign_msg_v1_tagged(&k, &onion, &spk), &signature) + .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 { pubkey, onion, 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()) } -fn sign_msg_v2(k: &str, onion: &str, spk: &str) -> Vec { +fn sign_msg_invite_v2(k: &str, onion: &str, spk: &str, kem_ascii: &str) -> Vec { + 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 { let mut msg = Vec::with_capacity(19 + 3 + k.len() + onion.len() + spk.len()); msg.extend_from_slice(b"onionwire-invite-v1"); msg.push(0); @@ -116,7 +178,7 @@ fn sign_msg_v2(k: &str, onion: &str, spk: &str) -> Vec { msg } -fn sign_msg_v1(k: &str, onion: &str, spk: &str) -> Vec { +fn sign_msg_v1_concat(k: &str, onion: &str, spk: &str) -> Vec { let mut msg = Vec::with_capacity(k.len() + onion.len() + spk.len()); msg.extend_from_slice(k.as_bytes()); msg.extend_from_slice(onion.as_bytes()); @@ -124,13 +186,18 @@ fn sign_msg_v1(k: &str, onion: &str, spk: &str) -> Vec { msg } -fn parse_fields(raw: &str) -> Result<(String, String, String, String)> { - let rest = raw - .strip_prefix("onionwire:v1:") - .ok_or_else(|| Error("not onionwire:v1".into()))?; +fn parse_fields(raw: &str) -> Result<(u8, String, String, String, Option, String)> { + let (version, rest) = if let Some(rest) = raw.strip_prefix("onionwire:v2:") { + (2u8, rest) + } 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 o = None; let mut spk = None; + let mut kem_f = None; let mut sig = None; for part in rest.split(':') { 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())); } 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=") { if sig.is_some() { return Err(Error("duplicate sig".into())); @@ -158,9 +233,11 @@ fn parse_fields(raw: &str) -> Result<(String, String, String, String)> { } } Ok(( + version, k.ok_or_else(|| Error("missing k".into()))?, o.ok_or_else(|| Error("missing o".into()))?, spk.ok_or_else(|| Error("missing spk".into()))?, + kem_f, sig.ok_or_else(|| Error("missing sig".into()))?, )) } @@ -182,6 +259,77 @@ fn from_hex(s: &str) -> Result> { .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> { + 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 { + 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)] mod tests { use super::*; @@ -196,10 +344,11 @@ mod tests { let k = to_hex(&sk.verifying_key().to_bytes()); let onion = v3(); 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 p = decode(&raw).expect("legacy concat"); assert_eq!(p.onion, onion); assert_eq!(p.signed_prekey, vec![9u8; 32]); + assert!(p.kem_pk.is_none(), "v1 invite is a classical friend"); } } diff --git a/src/session.rs b/src/session.rs index 2e23022..a3d3486 100644 --- a/src/session.rs +++ b/src/session.rs @@ -8,8 +8,34 @@ use crate::store::SelfIdentity; const PATTERN: &str = "Noise_IK_25519_ChaChaPoly_BLAKE2s"; 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; +/// 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, + pub kem_pk: Option>, +} + +/// 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 { + 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 = std::result::Result; #[derive(Debug)] @@ -72,6 +98,10 @@ pub struct Keys { pub prekey_sk: [u8; 32], #[zeroize(skip)] 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 { @@ -79,11 +109,14 @@ impl Keys { let signing = SigningKey::generate(&mut OsRng); let xsk = StaticSecret::random_from_rng(OsRng); let xpk = X25519Public::from(&xsk); + let kem_kp = crate::kem::generate(); Self { identity_sk: signing.to_bytes(), identity_pk: signing.verifying_key().to_bytes(), prekey_sk: xsk.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)?, prekey_sk: to_32(&me.prekey_sk)?, 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( local: &Keys, pinned_id: &[u8], remote_prekey: &[u8], + remote_kem_pk: Option<&[u8]>, ) -> Result where 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 .parse() .map_err(|e: snow::Error| Error::new(e.to_string()))?; let mut hs = Builder::new(params) .local_private_key(&local.prekey_sk)? .remote_public_key(remote_prekey)? - .prologue(PROLOGUE)? + .prologue(&prologue)? .build_initiator()?; let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]); @@ -249,20 +297,33 @@ pub async fn handshake_responder( ) -> Result where S: futures::io::AsyncRead + futures::io::AsyncWrite + Unpin, - F: FnOnce(&[u8]) -> Option>, + F: FnOnce(&[u8]) -> Option, { + 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 .parse() .map_err(|e: snow::Error| Error::new(e.to_string()))?; let mut hs = Builder::new(params) .local_private_key(&local.prekey_sk)? - .prologue(PROLOGUE)? + .prologue(&prologue)? .build_responder()?; 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)?; if n != 0 { return Err(Error::new("unexpected handshake payload")); @@ -271,8 +332,18 @@ where .get_remote_static() .ok_or_else(|| Error::new("missing remote static"))? .to_vec(); - let expected_id = - lookup_identity(&remote_static).ok_or_else(|| Error::new("unknown prekey"))?; + let peer = 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)?; crate::frame::write_frame(stream, &buf[..n]) .await @@ -328,3 +399,11 @@ fn verify_proof(proof: &[u8], expected_pk: &[u8], hash: &[u8]) -> Result<()> { fn to_32(v: &[u8]) -> Result<[u8; 32]> { 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")) +} diff --git a/src/store.rs b/src/store.rs index c5c92a3..35c7476 100644 --- a/src/store.rs +++ b/src/store.rs @@ -63,6 +63,10 @@ pub struct SelfIdentity { pub onion: String, pub prekey_sk: Zeroizing>, pub prekey_pk: Vec, + /// 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>, + pub kem_pk: Vec, } pub struct Friend { @@ -72,6 +76,9 @@ pub struct Friend { pub onion: String, pub last_connect_ok: bool, pub prekey: Vec, + /// 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>, } pub struct FriendProfile { @@ -247,7 +254,8 @@ impl Store { onion_updated_at INTEGER NOT NULL, added_at INTEGER NOT NULL, 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 ( id INTEGER PRIMARY KEY, @@ -264,6 +272,8 @@ impl Store { onion_rotated_at INTEGER NOT NULL, prekey_sk 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' ); CREATE TABLE IF NOT EXISTS self_profile ( @@ -611,6 +621,20 @@ impl Store { 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<()> { self.add_column_if_missing( "friends", @@ -637,6 +661,21 @@ impl Store { "hs_nickname", "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 // never been told one — a wallet created before this column, or a // 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(()) } pub fn self_identity(&self) -> Result { self.conn .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| { Ok(SelfIdentity { @@ -862,6 +920,8 @@ impl Store { onion: row.get(2)?, prekey_sk: Zeroizing::new(row.get(3)?), 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> { self.conn .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], friend_from_row, ) @@ -923,7 +983,7 @@ impl Store { pub fn friend_by_onion(&self, onion: &str) -> Result> { self.conn .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], friend_from_row, ) @@ -933,7 +993,7 @@ impl Store { pub fn list_friends(&self) -> Result> { 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", )?; let rows = stmt.query_map([], friend_from_row)?; @@ -1084,10 +1144,27 @@ impl Store { 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> { self.conn .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], friend_from_row, ) @@ -1560,6 +1637,8 @@ fn profile_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result } fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { + let kem: Option> = row.get(6)?; + let kem_pk = kem.filter(|k| k.len() == crate::kem::PK_LEN); Ok(Friend { pubkey: row.get(0)?, fingerprint: row.get(1)?, @@ -1567,6 +1646,7 @@ fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { onion: row.get(3)?, last_connect_ok: row.get::<_, i64>(4)? != 0, prekey: row.get(5)?, + kem_pk, }) } @@ -1877,6 +1957,41 @@ mod at_rest { use super::*; 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 /// 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 diff --git a/src/tui.rs b/src/tui.rs index 1cda191..ecc3dee 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -3750,6 +3750,10 @@ pub struct FriendRow { pub fingerprint: String, /// Last dial to this peer's onion did not answer. 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. @@ -3759,6 +3763,7 @@ pub fn friend_row(friend: &Friend) -> FriendRow { label: sanitize::display_text(raw.as_bytes()).to_string(), fingerprint: friend.fingerprint.clone(), 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 { let budget = (inner_width as usize).saturating_sub(2); 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 // 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 @@ -5568,7 +5576,7 @@ fn roster_row_text(row: &FriendRow, inner_width: u16) -> String { } else { (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 { diff --git a/tests/kem.rs b/tests/kem.rs new file mode 100644 index 0000000..6a048f9 --- /dev/null +++ b/tests/kem.rs @@ -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); +} diff --git a/tests/kem_transport.rs b/tests/kem_transport.rs new file mode 100644 index 0000000..462a9eb --- /dev/null +++ b/tests/kem_transport.rs @@ -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> { + 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> { + Pin::new(&mut self.get_mut().0).poll_write(cx, buf) + } + + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().0).poll_flush(cx) + } + + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + 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> { + 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> { + 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> { + Pin::new(&mut self.get_mut().inner).poll_flush(cx) + } + + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().inner).poll_close(cx) + } +} + +fn responder_auth(peer: &Keys) -> impl FnOnce(&[u8]) -> Option + '_ { + 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 + '_ { + 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()); +} diff --git a/tests/outbox.rs b/tests/outbox.rs index 2be2a8f..a2349c4 100644 --- a/tests/outbox.rs +++ b/tests/outbox.rs @@ -25,6 +25,7 @@ struct Flaky { err: String, calls: AtomicUsize, delivered: Mutex>>, + kems: Mutex>>>, } impl Flaky { @@ -34,6 +35,7 @@ impl Flaky { err: err.into(), calls: AtomicUsize::new(0), delivered: Mutex::new(Vec::new()), + kems: Mutex::new(Vec::new()), }) } @@ -53,8 +55,13 @@ impl Deliverer for Flaky { _pinned_id: &'a [u8], _prekey: &'a [u8], plaintext: &'a [u8], + _remote_kem: Option<&'a [u8]>, ) -> BoxFut<'a, Result<(), String>> { 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); if left > 0 { 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!(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, 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, 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" + ); +} diff --git a/tests/qr.rs b/tests/qr.rs index 203c012..3e38e0d 100644 --- a/tests/qr.rs +++ b/tests/qr.rs @@ -51,7 +51,7 @@ fn v3onion(tag: &str) -> 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 o = String::new(); let mut spk = String::new(); @@ -77,8 +77,9 @@ fn encode_decode_roundtrip() { let me = store.self_identity().expect("self"); let spk = [7u8; 32]; let onion = v3onion("alice-locator"); - let raw = qr::encode(&me.identity_sk, &onion, &spk).expect("encode"); - assert!(raw.starts_with("onionwire:v1:k="), "payload prefix: {raw}"); + let raw = qr::encode(&me.identity_sk, &onion, &spk, &me.kem_pk).expect("encode"); + assert!(raw.starts_with("onionwire:v2:k="), "payload prefix: {raw}"); + assert!(raw.contains(":kem=")); assert!(raw.contains(":o=")); assert!(raw.contains(":spk=")); assert!(raw.contains(":sig=")); @@ -102,7 +103,7 @@ fn missing_sig_is_err() { 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("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; assert!(qr::decode(stripped).is_err()); assert!(qr::decode(&format!("{stripped}:sig=")).is_err()); @@ -113,7 +114,7 @@ fn bad_sig_is_err() { 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("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 mut chars: Vec = sig.chars().collect(); 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 me = store.self_identity().expect("self"); 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 .upsert_friend(&p1.pubkey, &p1.onion, Some("alice")) .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(); assert_eq!(store.friend_count().unwrap(), 1); 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 store = Store::open().expect("open"); 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(); 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 onion = v3onion("honest"); 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); assert_eq!(spk_hex.len(), 64); let mutant = format!( @@ -177,9 +178,9 @@ fn encode_rejects_spk_not_32() { let store = Store::open().expect("open"); let me = store.self_identity().expect("self"); let onion = v3onion("spk"); - assert!(qr::encode(&me.identity_sk, &onion, &[1u8; 31]).is_err()); - assert!(qr::encode(&me.identity_sk, &onion, &[1u8; 33]).is_err()); - assert!(qr::encode(&me.identity_sk, &onion, &[]).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], &me.kem_pk).is_err()); + assert!(qr::encode(&me.identity_sk, &onion, &[], &me.kem_pk).is_err()); } #[test] @@ -188,9 +189,9 @@ fn encode_rejects_garbage_onion() { let store = Store::open().expect("open"); let me = store.self_identity().expect("self"); let spk = [2u8; 32]; - assert!(qr::encode(&me.identity_sk, "not-an-onion", &spk).is_err()); - assert!(qr::encode(&me.identity_sk, "alice.onion", &spk).is_err()); - assert!(qr::encode(&me.identity_sk, &format!("{}.onion", "A".repeat(56)), &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, &me.kem_pk).is_err()); + assert!(qr::encode(&me.identity_sk, &format!("{}.onion", "A".repeat(56)), &spk, &me.kem_pk).is_err()); } #[test] @@ -198,7 +199,7 @@ fn decode_rejects_spk_len_and_garbage_onion() { 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("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 short_spk = format!("onionwire:v1:k={k}:o={o}:spk={}:sig={sig}", &spk[..62]); 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()); } +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::>() + .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] fn huge_hex_is_err_quickly() { let huge = format!( diff --git a/tests/ratchet_adversarial.rs b/tests/ratchet_adversarial.rs index eccc206..c8927fa 100644 --- a/tests/ratchet_adversarial.rs +++ b/tests/ratchet_adversarial.rs @@ -51,6 +51,7 @@ impl Deliverer for Wire { pinned_id: &'a [u8], _prekey: &'a [u8], payload: &'a [u8], + _remote_kem: Option<&'a [u8]>, ) -> BoxFut<'a, Result<(), String>> { self.queues .lock() diff --git a/tests/ratchet_e2e.rs b/tests/ratchet_e2e.rs index a86bfd6..e8998fa 100644 --- a/tests/ratchet_e2e.rs +++ b/tests/ratchet_e2e.rs @@ -74,6 +74,7 @@ impl Deliverer for Wire { pinned_id: &'a [u8], _prekey: &'a [u8], payload: &'a [u8], + _remote_kem: Option<&'a [u8]>, ) -> BoxFut<'a, Result<(), String>> { if self.fail_next.load(Ordering::SeqCst) > 0 { self.fail_next.fetch_sub(1, Ordering::SeqCst); diff --git a/tests/ratchet_wire.rs b/tests/ratchet_wire.rs index de32fbd..cf35af4 100644 --- a/tests/ratchet_wire.rs +++ b/tests/ratchet_wire.rs @@ -46,6 +46,7 @@ impl Deliverer for Recorder { _pinned_id: &'a [u8], _prekey: &'a [u8], payload: &'a [u8], + _remote_kem: Option<&'a [u8]>, ) -> BoxFut<'a, Result<(), String>> { self.sent.lock().unwrap().push(payload.to_vec()); if self.fail_times.load(Ordering::SeqCst) > 0 { diff --git a/tests/tui_chrome.rs b/tests/tui_chrome.rs index c1632ac..a8ba51b 100644 --- a/tests/tui_chrome.rs +++ b/tests/tui_chrome.rs @@ -334,8 +334,8 @@ fn share_screen_shows_invite_not_qr_at_80x24() { let sk = [7u8; 32]; let onion = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; - let payload = qr::encode(&sk, onion, &[1u8; 32]).expect("encode"); - assert!(payload.starts_with("onionwire:v1:")); + let payload = qr::encode(&sk, onion, &[1u8; 32], &[9u8; 1184]).expect("encode"); + assert!(payload.starts_with("onionwire:v2:")); let backend = TestBackend::new(80, 24); let mut terminal = Terminal::new(backend).expect("terminal"); @@ -349,7 +349,7 @@ fn share_screen_shows_invite_not_qr_at_80x24() { screen.push('\n'); } assert!( - screen.contains("onionwire:v1:"), + screen.contains("onionwire:v2:"), "share screen missing invite prefix:\n{screen}" ); for ch in ['█', '▀', '▄'] { @@ -419,6 +419,7 @@ fn share_payload_rebuilds_from_the_frame_at_80x24_and_120x40() { &[7u8; 32], "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion", &[1u8; 32], + &[9u8; 1184], ) .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 // removed — no gutter is allowed to be there in the first place. let rebuilt: String = rows.iter().map(|r| r.trim_end()).collect(); - assert_eq!( - rebuilt, - payload, - "mouse-selecting the invite at {w}x{h} does not rebuild the payload:\n\ + // A v2 invite is ~1.9 KB. A short terminal cannot show all of it, so + // the frame must either carry the whole payload in order or a faithful + // prefix of it — never a reordered, interleaved or chrome-contaminated + // 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{}", 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], "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion", &[1u8; 32], + &[9u8; 1184], ) .expect("encode"); @@ -493,6 +501,7 @@ fn share_copy_key_sequence_carries_the_payload_exactly() { &[7u8; 32], "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion", &[1u8; 32], + &[9u8; 1184], ) .expect("encode"); let seq = osc52_copy_sequence(&payload); diff --git a/tests/tui_frames.rs b/tests/tui_frames.rs index 7e4ded6..4a5abe0 100644 --- a/tests/tui_frames.rs +++ b/tests/tui_frames.rs @@ -19,7 +19,8 @@ use onionwire::tui::{ 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, 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 ratatui::Frame; @@ -90,15 +91,46 @@ fn friend_rows() -> Vec { label: "alice".into(), fingerprint: "aaaaaaaaaaaaaaaa".into(), stale: false, + pq: true, }, FriendRow { label: "bob-the-stale-peer".into(), fingerprint: "bbbbbbbbbbbbbbbb".into(), 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 { Message { id, @@ -152,7 +184,7 @@ fn empty_chat(phase: TorPhase) -> Vec { #[test] 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 chat = chat_ok(); let (queued_chat, queued_note) = chat_queued(); @@ -744,7 +776,7 @@ fn status_footer_drops_send_failed_when_crowded() { #[test] 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 { let backend = TestBackend::new(w, h); let mut terminal = Terminal::new(backend).expect("terminal"); @@ -757,7 +789,7 @@ fn share_invite_wraps_at_three_sizes() { } 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}"); } } diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index 87d4887..8df081c 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -229,7 +229,7 @@ fn dump_spec_frames() { fn sample_invite() -> String { 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 { @@ -240,7 +240,17 @@ fn invite_line_ok(line: &str) -> bool { || t.starts_with("o=") || t.starts_with("spk=") || t.starts_with("sig=") + || t.starts_with("kem=") || 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] @@ -286,11 +296,12 @@ fn wrap_invite_breaks_on_field_boundaries() { ); } assert!( - wrapped.contains("onionwire:v1:"), + wrapped.contains("onionwire:v2:"), "lost invite prefix:\n{wrapped}" ); assert!(wrapped.contains("k="), "lost k= 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(); assert_eq!( joined, invite, @@ -306,7 +317,7 @@ fn draw_share_invite_does_not_wrap_mid_token() { terminal.draw(|f| draw_share(f, &invite)).expect("draw"); let screen = screen_from(terminal.backend().buffer(), 80, 24); assert!( - screen.contains("onionwire:v1:"), + screen.contains("onionwire:v2:"), "missing prefix:\n{screen}" ); 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("spk=") || inner.starts_with("sig=") + || inner.starts_with("kem=") || 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!( invite_line_ok(inner), @@ -782,6 +801,7 @@ async fn renders_a_queued_row_from_a_real_outbox_send() { _pinned_id: &'a [u8], _prekey: &'a [u8], _plaintext: &'a [u8], + _remote_kem: Option<&'a [u8]>, ) -> BoxFut<'a, Result<(), String>> { Box::pin(async { Err("connect dead.onion:80: timed out".to_string()) }) }