From b22abd7b2b204977eec4f3637fd46b1b98014b1d Mon Sep 17 00:00:00 2001 From: rust-dev Date: Tue, 20 Oct 2026 12:54:30 -0400 Subject: [PATCH] ratchet: hybrid ML-KEM steps (KDF_RK v2, 2312-byte header, state v2) Every ratchet keypair is {x25519, ml-kem-768}. On a rotation the stepper encapsulates to the receiver's current ratchet KEM key; both the X25519 DH and the ML-KEM secret feed KDF_RK under the new onionwire-ratchet-v2-kdfrk domain, so a later X25519 break does not open a chain established by a hybrid step. Epoch 0 stays classical by construction: the bootstrap root must be a pure function of the two long-lived prekeys for both-send-first convergence, and a per-session ss_kem differs for every one-shot Noise dial. The first rotation (including the bootstrap tie-break rotation) is hybrid, so the residual HNDL window is exactly the epoch-0 chain. docs/THREAT_MODEL.md states that window; no full PQ forward secrecy is claimed. Header 0x02 adds kem_pub[1184] || kem_ct[1088] to the 40-byte classical header and is used on every frame of a hybrid chain, so a lost first frame is harmless. A step with no KEM section is rejected (hybrid step required) and a hybrid step at a classical friend is rejected (unexpected hybrid step): no classical fallback. State moves to blob v0.2: fixed 211-byte prefix plus flagged KEM fields. A v1 blob is dropped and re-bootstrapped (hard cut, like F8); a corrupt v2 or a newer version is an error, not a silent reset. Tests: hybrid root agreement on both sides, both-send-first convergence with hybrid keys, no-downgrade, tampered kem_pub/kem_ct fail closed, MAX_SKIP on a hybrid chain, classical friends still step classically, state freeze at v0.2 and the node-level hard cut. --- README.md | 13 +- docs/PROTOCOL.md | 265 ++++++++++++++++++++----- docs/THREAT_MODEL.md | 74 +++++-- src/kem.rs | 10 + src/node.rs | 130 ++++++++++++- src/ratchet.rs | 447 ++++++++++++++++++++++++++++++++++++++----- tests/ratchet.rs | 423 ++++++++++++++++++++++++++++++++++++---- 7 files changed, 1196 insertions(+), 166 deletions(-) diff --git a/README.md b/README.md index 01b3a8c..78c1c54 100644 --- a/README.md +++ b/README.md @@ -317,11 +317,14 @@ session carries. Wire format: [docs/PROTOCOL.md](docs/PROTOCOL.md). removes the data dir. - 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). +- **Ratchet steps are hybrid; epoch 0 is not.** Every rotation after the + bootstrap mixes an ML-KEM-768 secret into the chain KDF, so a later X25519 + break does not open a hybrid chain. The bootstrap epoch is still derived only + from the two X25519 prekeys — a per-session KEM secret cannot be folded in + without breaking both-send-first convergence — so messages sent before the + first rotation stay X25519-only at the ratchet layer, and classical (v1) + friends have no PQ layer at all. No full post-quantum forward secrecy is + claimed; 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/docs/PROTOCOL.md b/docs/PROTOCOL.md index aaedc96..72ffd93 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -143,18 +143,41 @@ Receiver rules: rendered, or persisted. The ratchet state is not advanced. - Unpadded frames are not accepted as if they were a bucket: if the first two bytes do not describe a consistent `pad_len`, the frame fails closed. -- The `rat ` frame version stays `0x01`; padding is a plaintext-layer change. +- Padding is a plaintext-layer change and is independent of the `rat ` frame + version: a classical (`0x01`) and a hybrid (`0x02`) frame carry the same + padded plaintext. See [Ratchet (chat layer)](#ratchet-chat-layer) for the + header each version adds. -Minimum observable size: a 256-byte bucket plus the `rat ` frame overhead -(`rat ` 4 + version 1 + header 40 + nonce 12 + tag 16 = 73) is a 329-byte -ratchet frame; the Noise transport adds its 16-byte tag and the framing header -adds 5 bytes, so the **smallest chat frame on the wire is 350 bytes**, whatever -the body length. The 32768 bucket is a 32862-byte frame, under the 65535 cap. +The ladder floor stays at **256** even though a hybrid frame's floor is over +2.6 KB. The ladder schedules the *plaintext*, and a hybrid step's size is +dominated by its 2312-byte header — the 256 bucket is a rounding error there, +so raising the floor would not conceal the header and would only inflate +classical (`0x01`) chat, which is still the epoch-0 and legacy-friend path. A +second, version-specific ladder would double the normative surface for no +privacy gain; the bucket boundaries remain observable within each size class +either way. -The ML-KEM-768 ciphertext is confined to the one-shot handshake prelude -(`version = 2`, 1095 bytes on the wire once per session). It is not part of a -`rat ` header: ratchet keys in a chat frame are X25519 (32 bytes), so the -hybrid transport does not widen this floor. +Minimum observable size depends on the `rat ` header version: + +- Classical (`0x01`): `rat ` 4 + version 1 + header 40 + nonce 12 + bucket 256 + + tag 16 = **329-byte `rat ` frame**; the Noise transport adds its 16-byte + tag and the framing header adds 5 bytes, so the smallest classical chat frame + on the wire is **350 bytes**. +- Hybrid (`0x02`): `rat ` 4 + version 1 + header 2312 + nonce 12 + bucket 256 + + tag 16 = **2601-byte `rat ` frame**, i.e. **2622 bytes on the wire**. The + 2272 extra header bytes are the sender's ML-KEM-768 ratchet key and the + ciphertext to the receiver's; the 256-byte bucket applies unchanged inside + them. + +Both floors hold whatever the body length. The 32768 bucket yields a +32862-byte classical frame and a 35113-byte hybrid frame, both under the 65535 +Noise body cap. + +The ML-KEM-768 ciphertext appears in two places: the one-shot handshake prelude +(`version = 2`, 1095 bytes once per session), and every `rat ` header after the +first hybrid ratchet step (`kem_pub[1184] || kem_ct[1088]`). Epoch 0 of a chat +is always classical, so the first `rat ` frame of a friend relationship uses +the 40-byte header. `fil ` chunks are deliberately **not** padded. They are raw file bytes paced through the accept token bucket, and padding them would either cut the usable @@ -464,7 +487,7 @@ is a chat line `[file] name (N bytes)`, never the raw frame. ### Chat A chat send is ratcheted: the wire form of a chat message is a `rat ` frame -(see “Ratchet (v1 chat layer)”), and the plaintext inside that frame is the chat +(see “Ratchet (chat layer)”), and the plaintext inside that frame is the chat line below, padded to a length bucket first (see [Length buckets](#length-buckets)). A bare chat frame with no typed prefix is still accepted inbound as a chat line (older peers), but MUST NOT be emitted. @@ -480,7 +503,7 @@ A chat line is at most 32766 bytes (the largest bucket minus the 2-byte `pad_len` header); a longer body is a protocol error, not a queued message. See [Length buckets](#length-buckets). -## Ratchet (v1 chat layer) +## Ratchet (chat layer) Chat is the only application payload that is ratcheted. A chat send is Double-Ratchet encrypted first, and the resulting `rat ` frame is the @@ -498,29 +521,53 @@ instead. ``` "rat " 4 bytes (0x72 0x61 0x74 0x20) -version 1 byte 0x01 -header 40 bytes dh_pub[32] || N uint32 BE || PN uint32 BE -nonce 12 bytes random, per message +version 1 byte 0x01 (classical) or 0x02 (hybrid) +-- version 0x01: classical header, 40 bytes +header 40 bytes dh_pub[32] || N uint32 BE || PN uint32 BE +nonce 12 bytes random, per message +ciphertext n+16 ChaCha20-Poly1305 ciphertext || tag + +-- version 0x02: hybrid header, 2312 bytes +header 2312 bytes dh_pub[32] || N uint32 BE || PN uint32 BE + || kem_pub[1184] || kem_ct[1088] +nonce 12 bytes random, per message ciphertext n+16 ChaCha20-Poly1305 ciphertext || tag ``` -- `dh_pub` — the sender's current ratchet public key (X25519, 32 bytes). +- `dh_pub` — the sender's current X25519 ratchet public key (32 bytes). - `N` — the index of this message in the sender's current sending chain, counting from 0. - `PN` — how many messages the sender sent in its *previous* sending chain. -- Associated data is the 40-byte header, exactly as serialized above - (`dh_pub || N as u32 BE || PN as u32 BE`). A tampered `dh_pub`, `N` or `PN` +- `kem_pub` — the sender's current ML-KEM-768 ratchet encapsulation key + (1184 bytes). +- `kem_ct` — an ML-KEM-768 ciphertext (1088 bytes) that the sender + encapsulated to the *receiver's current* ratchet KEM key. It is repeated on + every frame of a chain a hybrid step established, so a lost first frame does + not wedge the chain. +- Associated data is the whole header for the version in use, exactly as + serialized above. A tampered `dh_pub`, `N`, `PN`, `kem_pub` or `kem_ct` therefore fails closed. - The ChaCha20-Poly1305 key is the message key from `KDF_CK`. The 12-byte nonce is random per message, not a chain counter. -- Minimum *ratchet* frame is 73 bytes: 5 + 40 + 12 + 16. A chat frame is larger - because its plaintext is padded to a bucket (see - [Length buckets](#length-buckets)); an empty chat line is a 329-byte `rat ` - frame. +- A chat frame's minimum size depends on the header version, not the body: an + empty chat line still pads to the 256-byte bucket. Version `0x01` is 329 + bytes (5 + 40 + 12 + 256 + 16); version `0x02` is 2601 bytes + (5 + 2312 + 12 + 256 + 16). A hybrid message therefore carries 2272 more + header bytes than a classical one. See [Length buckets](#length-buckets). +- On the wire those become 350 bytes for `0x01` (329 + the Noise 16-byte tag + + the 5-byte framing header) and 2622 bytes for `0x02`. The 350-byte floor is + the classical case only. +- A `rat ` frame with no padding at all cannot occur for chat; the bare frame + overhead (empty ciphertext plaintext) is 73 bytes for `0x01` + (5 + 40 + 12 + 16) and 2345 bytes for `0x02` (5 + 2312 + 12 + 16). - A receiver MUST reject a frame without the `rat ` prefix, a version other than - `0x01`, or less than 73 bytes. + `0x01`/`0x02`, or a frame shorter than its version's minimum. - The frame must fit the Noise body cap (65535 bytes, including the 16-byte - Poly1305 tag), so a `rat ` frame is at most 65519 bytes. + Poly1305 tag), so a `rat ` frame is at most 65519 bytes. A maximal hybrid + plaintext is therefore 63174 bytes, still far above the chat line limit. +- A `rat ` frame is one Noise body: the `fil ` chunk-pacing rules do not apply, + and the receive token bucket counts rendezvous accepts, not bytes, so the + larger hybrid header changes neither. Because the header rides inside Noise, an observer sees one opaque ciphertext per message: no message counts, no ratchet keys, and nothing that marks a first @@ -528,28 +575,45 @@ message of a chain versus a later one. ### KDFs -Signal's constructions, unchanged: +Signal's constructions, with a second domain for hybrid steps: ``` -KDF_RK(root, dh_out): +KDF_RK(root, dh_out): # v1: epoch 0, classical friends okm = HKDF-SHA256(salt = root, ikm = dh_out, info = "onionwire-ratchet-v1-kdfrk", L = 64) new_root = okm[0..32] chain_key = okm[32..64] +KDF_RK_hybrid(root, dh_out, ss_kem): # v2: every hybrid ratchet step + okm = HKDF-SHA256(salt = root, ikm = dh_out || ss_kem, + info = "onionwire-ratchet-v2-kdfrk", L = 64) + new_root = okm[0..32] + chain_key = okm[32..64] + KDF_CK(chain_key): message_key = HMAC-SHA256(chain_key, 0x01) next_chain_key = HMAC-SHA256(chain_key, 0x02) ``` -`HKDF` is RFC 5869 with SHA-256, `HMAC` is SHA-256. Each side of an epoch -derives its chains from one shared DH output with `KDF_RK` called **twice**: +`HKDF` is RFC 5869 with SHA-256, `HMAC` is SHA-256. The two `KDF_RK` forms +differ in **both** input shape and info string on purpose: `ikm` is 32 bytes for +v1 and `dh_out || ss_kem` (64 bytes) for v2, and the domain strings are +distinct. There is no way to derive a v2 chain without a real `ss_kem`, and a +classical derivation can never be mistaken for a hybrid one. + +Each side of an epoch derives its chains from one shared input with `KDF_RK` +called **twice**: ``` -epoch_chains(root, shared) -> (new_root, ck_lo, ck_hi): +epoch_chains(root, shared) -> (new_root, ck_lo, ck_hi): # v1 (root1, ck_lo) = KDF_RK(root, shared) (root2, ck_hi) = KDF_RK(root1, shared) new_root = root2 + +epoch_chains_hybrid(root, dh_out, ss_kem) -> (new_root, ck_lo, ck_hi): # v2 + (root1, ck_lo) = KDF_RK_hybrid(root, dh_out, ss_kem) + (root2, ck_hi) = KDF_RK_hybrid(root1, dh_out, ss_kem) + new_root = root2 ``` `lo` is the lexicographically lower of the pair's two ratchet public keys and @@ -573,16 +637,30 @@ root_key = hk.expand("root", 32) my_secret = hk.expand("ratchet-key" || my_identity_pk, 32) peer_secret = hk.expand("ratchet-key" || peer_identity_pk, 32) -state = bootstrap(root_key, my_keypair(my_secret), X25519_pub(peer_secret)) +my_ratchet = keypair(my_secret) // x25519 secret/public + ML-KEM-768 +peer_ratchet = keypair(peer_secret) // derived by both sides, same values + +state = bootstrap(root_key, my_ratchet, + peer_ratchet.x25519_pub, + peer_ratchet.kem_pub if the friend row carries kem_pk else None) ``` `HKDF.expand` above is the RFC 5869 expand step (no second extract). The two identity public keys are public (invite/roster), so either peer computes its own -secrets and the peer's, and both agree with no new wire field. Then: +secrets and the peer's, and both agree with no new wire field. The ML-KEM half of +each initial ratchet keypair is derived from that keypair's X25519 secret, so the +peer's KEM ratchet public key needs no wire field either: + +``` +kem_seed = HKDF-SHA256(salt = "ratchet-kem", ikm = x25519_secret).expand("seed", 64) +kem_pub = ML-KEM-768 encapsulation key from kem_seed +``` + +Then: ``` shared = DH(my_secret, remote_pub) -(new_root, ck_lo, ck_hi) = epoch_chains(root_key, shared) +(new_root, ck_lo, ck_hi) = epoch_chains(root_key, shared) // v1: epoch 0 is classical send_ck = chain_for(my_pub, remote_pub) // ck_lo or ck_hi recv_ck = chain_for(remote_pub, my_pub) send_n = recv_n = 0, PN = 0, established = false @@ -591,6 +669,52 @@ send_n = recv_n = 0, PN = 0, established = false Fresh entropy enters at the first DH ratchet step; the bootstrap epoch itself is prekey-bound (see [THREAT_MODEL.md](THREAT_MODEL.md)). +### Hybrid ratchet steps, and why epoch 0 stays classical + +Every ratchet keypair is now `{x25519, ML-KEM-768}`. On a step the peer that +rotates encapsulates to the receiver's **current** ratchet KEM key and puts +`kem_pub` (its new key) and `kem_ct` (that ciphertext) in the header. The +receiver decapsulates with the key it already holds, so both sides feed +`KDF_RK_hybrid` the same `(X25519 DH, ss_kem)` pair and derive the same chains. +No extra round trip is added: the KEM material rides on the rotation frame +itself, and is repeated on every later frame of that chain so a lost first frame +is harmless. + +**Epoch 0 cannot be per-session, so it stays classical.** Epoch 0's root is +derived from the two long-lived signed prekeys precisely so that neither side +needs a wire field and both converge even when both send first. The hybrid Noise +session does carry an `ss_kem` (see Transport), but each chat message is its own +one-shot Noise session: a fresh encapsulation, therefore a different `ss_kem` for +every dial, and *different* sessions for the two peers' first sends. Binding the +epoch-0 root to that secret would make the root a function of which session +carried which message, so: + +- two peers sending first would derive different epoch-0 roots and could not + read each other at all, and +- even a single direction would break at the second message, because message 2 + would arrive on a different Noise session with a different `ss_kem` while the + receiver still holds the root from message 1. + +There is no way to keep both "no wire field, both-send-first convergence" and a +per-session secret in epoch 0 without replacing the one-shot session model, which +is out of scope. Epoch 0 is therefore derived exactly as before, with the v1 +`KDF_RK`, and the KEM secret enters at the **first rotation after +`established`**. The first rotation is hybrid even for the bootstrap tie-break +rotation: that is what closes the window two round trips in. + +Consequences, stated exactly: + +- Every frame sent before the first hybrid step (the whole of epoch 0, in both + directions, plus any outbox row encoded on it) is protected by X25519 only. A + harvest-now adversary who later breaks X25519 can read those frames. This is + the residual window and it does not shrink with more messages, only with the + first rotation. +- Every frame on a chain established by a hybrid step additionally requires the + ML-KEM-768 secret. Breaking X25519 alone does not open it. +- A frame that carries a new `dh_pub` but no KEM section is **rejected** + (`hybrid step required`); a KEM section on a non-KEM friend is rejected too. + There is no classical fallback once a session has KEM material. + **Convergence when both peers send first.** Either peer may send immediately on the bootstrap epoch, so two peers can each build a sending chain before either has received anything. Because the epoch's two chains come from the unordered @@ -613,7 +737,8 @@ rotation first, so at most one rotation is ever in flight, and both peers feed On a decrypted `rat ` frame (the outer Noise session has already been verified, so the peer identity is pinned): -1. Parse; reject bad prefix, version or a frame under 73 bytes. +1. Parse; reject a bad prefix or version, and a frame shorter than its + version's minimum (73 bytes for `0x01`, 2345 for `0x02`). 2. If `(dh_pub, N)` is in the skipped-key store: open with that key, **delete it** from the store, deliver. A replay of the same frame then fails closed because the key is gone. @@ -624,11 +749,15 @@ so the peer identity is pinned): - Derive message keys for `recv_n .. N` into the skipped store, derive the key for `N`, open, set `recv_n = N + 1`. - On the *first* frame received in this state (`established == false`): set - `established`, and if `my_pub < remote_pub`, rotate the sending chain - (fresh keypair; `epoch_chains(root, DH(new_secret, remote_pub))`; new - sending chain for `new_pub → remote_pub`; `PN = old send_n`; `send_n = 0`). - The receiving chain is untouched. -4. Else it is a ratchet key not adopted yet: run a full DH ratchet step. + `established`, and if `my_pub < remote_pub`, rotate the sending chain — + fresh `{x25519, ml-kem}` keypair; for a hybrid friend encapsulate to + `remote_kem_pub` and derive with `epoch_chains_hybrid(root, DH(new_secret, + remote_pub), ss)`, for a classical friend `epoch_chains(root, DH(...))`; + new sending chain for `new_pub → remote_pub`; `PN = old send_n`; + `send_n = 0`. The receiving chain is untouched. +4. Else it is a ratchet key not adopted yet: run a full DH ratchet step. A + session that holds `remote_kem_pub` rejects a frame with no KEM section, and + a session without KEM material rejects a frame that has one. ### DH ratchet step @@ -641,18 +770,26 @@ On a frame whose `dh_pub` differs from the adopted remote public key: - Derive `recv_n .. PN` into the skipped store, tagged with the retired remote public key, so stragglers of the old chain still decrypt. 2. **Receiving half of the step**, on the pair `(my current secret, frame.dh_pub)`: - `shared = DH(my_secret, frame.dh_pub)`, - `(root_a, ck_lo, ck_hi) = epoch_chains(root, shared)`, + `shared = DH(my_secret, frame.dh_pub)`. For a hybrid step also + `ss_kem = ML-KEM.Decaps(my_current_ratchet_kem_secret, frame.kem_ct)`, then + `(root_a, ck_lo, ck_hi) = epoch_chains_hybrid(root, shared, ss_kem)`; + otherwise `(root_a, ck_lo, ck_hi) = epoch_chains(root, shared)`. `recv_ck = chain_for(frame.dh_pub, my_pub)`, then open the frame with this chain exactly as in step 3 above (it must be within `MAX_SKIP` of index 0). -3. **Sending half:** generate a fresh ratchet keypair, - `shared = DH(new_secret, frame.dh_pub)`, - `(root, ck_lo, ck_hi) = epoch_chains(root_a, shared)`, +3. **Sending half:** generate a fresh ratchet keypair `{x25519, ml-kem}`. For a + hybrid step encapsulate to `frame.kem_pub` (`(kem_ct, ss_kem) = + ML-KEM.Encaps(frame.kem_pub)`), derive + `(root, ck_lo, ck_hi) = epoch_chains_hybrid(root_a, DH(new_secret, + frame.dh_pub), ss_kem)` and keep `kem_ct` in the state so every frame of the + new sending chain carries it; otherwise `epoch_chains(root_a, DH(...))`. `send_ck = chain_for(new_pub, frame.dh_pub)`, `remote_pub = frame.dh_pub`, - `PN = old send_n`, `send_n = 0`, `established = true`. + `remote_kem_pub = frame.kem_pub`, `PN = old send_n`, `send_n = 0`, + `established = true`, `recv_hybrid = frame has a KEM section`. 4. The frame is opened with the *new* receiving chain's message key. If the AEAD open fails, nothing is applied: the state must be byte-identical to before - the frame. + the frame. (A tampered `kem_ct` yields a different `ss_kem` through ML-KEM's + implicit rejection, and the AEAD then fails; a tampered `kem_pub` is inside + the AAD, so it fails the same way.) The next frame this side sends therefore carries the new `dh_pub`, which is what lets the peer step too. @@ -674,10 +811,32 @@ lets the peer step too. `ratchet_sessions` in the SQLCipher store: one row per friend (`friend_id` primary key, `FOREIGN KEY` → `friends.id` `ON DELETE CASCADE`, -`state BLOB NOT NULL`, `updated_at`). The blob is version byte `0x01` followed by -the implementation's serialized ratchet state. The state is device-local: it is -**never** transmitted, and its layout is not part of this wire protocol. The -store is encrypted as a whole, so the blob is ciphertext on disk. +`state BLOB NOT NULL`, `updated_at`). The blob is version byte `0x02` followed by +the implementation's serialized ratchet state: + +``` +0 version 0x02 +1..211 fixed prefix: root, local secret/public, remote public, + send_ck/send_n, recv_ck/recv_n, PN, established, flags, + skipped-count +then remote ratchet KEM public key (1184 bytes) if flag 0x01 +then pending KEM ciphertext (1088 bytes) if flag 0x02 + (flag 0x04 marks a receiving chain established hybrid) +then skipped keys, dh_pub[32] || n u32 BE || message key[32] +``` + +The state is device-local: it is **never** transmitted, and its layout is not +part of this wire protocol. The store is encrypted as a whole, so the blob is +ciphertext on disk. + +**Hard cut.** Version `0x01` is the pre-hybrid layout, which had no KEM ratchet +key and no pending ciphertext. It is **dropped, not migrated**: on load, a v1 +blob is deleted and the session re-bootstraps from the two prekeys, exactly the +way an `F8` prekey rotation drops state. Nothing is half-read, and epoch 0 comes +back identical because its derivation did not change. A *corrupt* v2 blob or one +written by a **newer** version is reported as an error instead — those are not an +old format, and silently resetting them would be a downgrade. The same cut +applies to any peer whose prekey or KEM key changes. ### Not ratcheted @@ -754,6 +913,8 @@ path”). They are out of scope, not postponed. 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 - disagree cannot read each other's chat, and every other frame keeps working. +- The `rat ` frame has its own version byte (`0x01` classical, `0x02` hybrid). + A different ratchet frame layout or a different KDF is a breaking change for + chat only: peers that disagree cannot read each other's chat, and every other + frame keeps working. A `0x02` frame from a peer whose roster row says + `classical`, or a `0x01` step from a hybrid peer, is rejected. diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 0c47236..b618876 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -135,13 +135,22 @@ device. below. - *Post-compromise security after a DH ratchet step.* An attacker holding a snapshot of one side's state cannot read the conversation past the next DH - ratchet step: that step feeds a fresh X25519 output into the root, and the - snapshot stops producing chain keys. The window is not zero — it lasts until - the next step — but no attacker can prevent it closing. -- *The ratchet header is not on the wire.* `dh_pub`, `N` and `PN` ride inside - the Noise ciphertext (authenticated as AEAD associated data), so message - counts and ratchet-key changes are not observable, and a tampered header fails - closed. + ratchet step: that step feeds a fresh X25519 output — and, from the first + rotation, a fresh ML-KEM-768 secret — into the root, and the snapshot stops + producing chain keys. The window is not zero — it lasts until the next step — + but no attacker can prevent it closing. +- *Quantum-resistant chains from the first rotation.* Every ratchet step mixes a + fresh ML-KEM-768 secret into `KDF_RK` alongside the X25519 output + (`dh_out || ss_kem`, info `onionwire-ratchet-v2-kdfrk`). A harvest-now + adversary who records a hybrid chain and later breaks X25519 still needs the + ML-KEM-768 secret to walk that chain, which breaking X25519 does not give. + Ratchet keypairs are generated as `{x25519, ml-kem}` with the KEM seed derived + from the X25519 secret, so the KEM half adds no state to protect. +- *The ratchet header is not on the wire.* `dh_pub`, `N`, `PN` and, on hybrid + chains, `kem_pub`/`kem_ct` ride inside the Noise ciphertext (authenticated as + AEAD associated data), so message counts and ratchet-key changes are not + observable, and a tampered header fails closed. A missing KEM section on a + step is a hard `hybrid step required` rejection, never a classical fallback. **Honest limits.** @@ -151,16 +160,38 @@ device. oldest-first. A snapshot also carries the current sending and receiving chain keys, which read the current chain until it advances. This is the price of out-of-order delivery, and it is per friend. -- *The bootstrap epoch is prekey-bound.* The initial root and both initial - ratchet secrets are HKDF outputs of the X25519 DH between the two long-lived - signed prekeys, and the identity pubkeys that separate them are public. An - attacker who has both peers' prekey statics can therefore reconstruct the - **first** epoch. What that does not buy is a recorded message: every `rat ` - frame travels inside a one-shot Noise session whose ephemerals are not derived - from the prekeys, so the prekeys alone do not open stored traffic. From the - first DH ratchet step on, fresh X25519 secrets enter and the prekeys derive - nothing — the bootstrap epoch is the exception, not the rule, and it is the - reason the state is dropped when a peer's prekey changes. +- *Epoch 0 is classical — this is the remaining harvest-now window.* The + bootstrap root and both initial ratchet secrets are HKDF outputs of the + X25519 DH between the two long-lived signed prekeys, and the identity pubkeys + that separate them are public. A per-session KEM secret cannot be folded into + epoch 0: each chat message is its own one-shot Noise session, so `ss_kem` + differs per dial and per peer, and a root bound to it would make the two peers + (or even message 1 and message 2) derive different chains. Epoch 0 is + therefore derived with the classical `KDF_RK`, and the ML-KEM secret enters at + the **first rotation** — two round trips in, at the latest. + What that leaves exposed, precisely: + - The epoch-0 *chain keys* are not post-quantum. A future X25519 break + reconstructs the prekey DH, hence the epoch-0 root and every message key on + that chain. This covers everything sent before the first hybrid step, + including any frame that was encoded on epoch 0 and left in the outbox. + - It does **not** by itself open a recorded v2 transcript, because a v2 friend + wraps every `rat ` frame in the hybrid Noise session (ML-KEM-768 prelude). + The epoch-0 chain keys are a second layer; breaking X25519 alone still leaves + that outer layer closed. The exposure becomes real the moment the rat frame + itself is accessible — a state snapshot taken at epoch 0, an old client that + logged it, or a peer running the classical transport. + - For a **classical (v1) friend** there is no PQ layer anywhere: transport and + every ratchet step are X25519-only, so the whole conversation is + harvest-now-decrypt-later exposed. Hybrid ratchet steps require `kem_pk` on + the roster row, which a legacy invite does not carry. + - From the first hybrid step on, a state snapshot plus a future X25519 break is + not enough: the chain also needs the ML-KEM-768 secret, and the next rotation + replaces it. We do **not** claim full post-quantum forward secrecy, because + epoch 0 is outside that guarantee. + The bootstrap epoch is still the reason state is dropped when a peer's prekey + changes, and an attacker holding both prekey statics can reconstruct epoch 0 + directly (no break needed). A recorded message is not opened by the prekeys + alone while the one-shot Noise session an ML-KEM friend used remains intact. - *No deniability and no non-repudiation claim.* Chat frames are not signed and both parties derive the same chain keys, so nothing here would let a third party decide which of the two authored a chat line. Identity is proven per @@ -182,9 +213,12 @@ device. 32 KiB — `docs/PROTOCOL.md`, “Length buckets”), so an observer sees only the bucket and not the body length. That is all it hides: message timing, retry cadence, the one-shot-per-message circuits, and the timing of the handshake - are unchanged, and no cover traffic or jitter is generated. Non-chat frames - (`loc `, `prf `, `inv `, `rcp `, `tip `, `fil `) are not padded and still - reveal their own sizes. + are unchanged, and no cover traffic or jitter is generated. The frame header + is not padded: a classical `rat ` frame is 350 bytes at its smallest, while a + hybrid step's 2312-byte ML-KEM header makes its smallest frame 2622 bytes on + the wire. That is a size class, not a message count, and it does not leak the + body length inside the bucket. Non-chat frames (`loc `, `prf `, `inv `, + `rcp `, `tip `, `fil `) are not padded and still reveal their own sizes. - *The ratchet does not re-open the "no server-side outbox" lock.* The state is device-local, one row per friend in the encrypted store, and nothing about it is transmitted. The local retry queue's two accepted consequences (device diff --git a/src/kem.rs b/src/kem.rs index a43424e..24c62eb 100644 --- a/src/kem.rs +++ b/src/kem.rs @@ -86,6 +86,16 @@ pub fn decapsulate(seed: &[u8], ct: &[u8]) -> Result> { Ok(ss.as_slice().to_vec()) } +/// Canonical encapsulation key for a stored 64-byte decapsulation seed. +/// +/// The ratchet derives its KEM half from the X25519 ratchet secret, so it never +/// stores the ML-KEM seed separately; this recomputes the public half. +pub fn pk_from_seed(seed: &[u8]) -> Result> { + let seed_arr = Seed::try_from(seed).map_err(|_| Error("seed length".into()))?; + let dk = DecapsulationKey768::from_seed(seed_arr); + Ok(dk.encapsulation_key().to_bytes().as_slice().to_vec()) +} + fn encapsulation_key(pk: &[u8]) -> Result { if pk.len() != PK_LEN { return Err(Error("pk length".into())); diff --git a/src/node.rs b/src/node.rs index ded4ce8..4685828 100644 --- a/src/node.rs +++ b/src/node.rs @@ -2326,6 +2326,7 @@ fn bootstrap_ratchet( keys: &Keys, peer_pk: &[u8], peer_prekey: &[u8], + hybrid: bool, ) -> Result { let peer_pk: [u8; 32] = peer_pk .try_into() @@ -2343,7 +2344,20 @@ fn bootstrap_ratchet( let local = RatchetKeyPair::from_secret(ratchet_seed(&hk, &keys.identity_pk)?); let remote = ratchet_seed(&hk, &peer_pk)?; let remote_pub = X25519Public::from(&StaticSecret::from(remote)).to_bytes(); - Ok(RatchetState::bootstrap(root_key, local, remote_pub)) + // The peer's initial ratchet keypair is derived, so its ML-KEM half is too: + // a hybrid friend needs no extra wire field at bootstrap. Epoch 0 itself + // stays classical; the first rotation is the first hybrid step. + let remote_kem = if hybrid { + Some(RatchetKeyPair::from_secret(remote).kem_public().to_vec()) + } else { + None + }; + Ok(RatchetState::bootstrap( + root_key, + local, + remote_pub, + remote_kem.as_deref(), + )) } /// `HKDF(info = "ratchet-key" || pubkey)` — the initial ratchet secret both @@ -2366,7 +2380,20 @@ fn ratchet_seed(hk: &Hkdf, pubkey: &[u8; 32]) -> Result<[u8; 32], String /// session behind. fn ratchet_for(store: &Store, keys: &Keys, friend_pk: &[u8]) -> Result { if let Some(blob) = store.load_ratchet(friend_pk).map_err(|e| e.to_string())? { - return RatchetState::from_bytes(&blob).map_err(|e| format!("ratchet state: {e}")); + match RatchetState::from_bytes(&blob) { + Ok(state) => return Ok(state), + // Hard cut, exactly like F8: the *pre-hybrid* v1 blob has no KEM + // ratchet key and is dropped, never half-migrated. The bootstrap + // epoch is a pure function of the (unchanged) prekeys, so it is + // rebuilt. A newer version is not an old format and must not be + // reset silently. + Err(crate::ratchet::Error::UnsupportedStateVersion(1)) => { + store.clear_ratchet(friend_pk).map_err(|e| e.to_string())?; + } + // A corrupt *current* state, or one written by a newer client, is + // surfaced rather than silently reset. + Err(e) => return Err(format!("ratchet state: {e}")), + } } let f = store .get_friend(friend_pk) @@ -2375,7 +2402,7 @@ fn ratchet_for(store: &Store, keys: &Keys, friend_pk: &[u8]) -> Result 210, + "the rebuilt state carries the peer's KEM ratchet key" + ); + } + + #[tokio::test] + async fn a_corrupt_current_ratchet_blob_is_an_error_not_a_silent_drop() { + 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"); + // A v2 blob missing its last byte: a hard cut must not paper over this + // one, because a corrupt current state is not an old format. + let mut corrupt = vec![crate::ratchet::STATE_VERSION]; + corrupt.resize(300, 0x5a); + store + .save_ratchet(&peer.identity_pk, &corrupt) + .expect("row"); + let keys = node.keys.lock().unwrap(); + let err = encode_chat_frame(&store, &keys, &peer.identity_pk, b"no") + .expect_err("a corrupt current state must fail, not re-bootstrap"); + assert!( + err.contains("ratchet state"), + "expected a state error, got: {err}" + ); + } + + #[tokio::test] + async fn a_future_ratchet_blob_is_an_error_not_a_silent_downgrade() { + 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"); + // Only the *old* layout is a hard cut. A newer state must not be + // silently reset to epoch 0 by an older client. + let mut future = vec![crate::ratchet::STATE_VERSION + 1]; + future.resize(300, 0x5a); + store.save_ratchet(&peer.identity_pk, &future).expect("row"); + let keys = node.keys.lock().unwrap(); + let err = encode_chat_frame(&store, &keys, &peer.identity_pk, b"no") + .expect_err("a future state version must not be downgraded silently"); + assert!( + err.contains("unsupported ratchet state version"), + "expected a version error, got: {err}" + ); + } + #[tokio::test] async fn a_prelude_less_session_against_a_kem_friend_is_rejected() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/ratchet.rs b/src/ratchet.rs index 745e239..a982bc0 100644 --- a/src/ratchet.rs +++ b/src/ratchet.rs @@ -9,28 +9,70 @@ //! # Frame //! //! ```text -//! b"rat " || 0x01 || header[40] || nonce[12] || ciphertext -//! header = dh_pub[32] || N u32 BE || PN u32 BE +//! b"rat " || 0x01 || dh_pub[32] || N u32 BE || PN u32 BE +//! || nonce[12] || ciphertext (epoch 0, classical) +//! b"rat " || 0x02 || dh_pub[32] || N u32 BE || PN u32 BE +//! || kem_pub[1184] || kem_ct[1088] +//! || nonce[12] || ciphertext (hybrid step chain) //! ``` //! -//! `dh_pub` is the sender's current ratchet public key, `N` the index of this -//! message in the sender's current sending chain, `PN` how many messages the -//! sender sent in its *previous* sending chain. The header is plaintext inside -//! the ratchet frame and is used verbatim as AEAD associated data, so a tampered -//! `dh_pub`/`N`/`PN` fails closed. The whole frame travels inside the Noise -//! transport (never in clear on the wire), so an observer learns neither message -//! counts nor ratchet keys (`docs/THREAT_MODEL.md`). +//! `dh_pub` is the sender's current X25519 ratchet public key, `N` the index of +//! this message in the sender's current sending chain, `PN` how many messages +//! the sender sent in its *previous* sending chain. The header is plaintext +//! inside the ratchet frame and is used verbatim as AEAD associated data, so a +//! tampered `dh_pub`/`N`/`PN` — or a tampered/stripped KEM section — fails closed. +//! +//! Version `0x02` is the hybrid header: it adds the sender's current ML-KEM-768 +//! ratchet public key and the ciphertext the sender encapsulated *to the +//! receiver's* current ML-KEM ratchet key. The section is repeated on every +//! frame of a chain a hybrid step established, so losing the first frame of that +//! chain is harmless. A hybrid header is 2312 bytes, not 40 (see +//! `docs/PROTOCOL.md`). Version `0x01` is unchanged: epoch 0 and every step of a +//! legacy friend that has no KEM key. +//! +//! The whole frame travels inside the Noise transport (never in clear on the +//! wire), so an observer learns neither message counts nor ratchet keys +//! (`docs/THREAT_MODEL.md`). //! //! # KDFs //! -//! Signal's constructions, unchanged: +//! Signal's constructions: //! -//! - `KDF_RK(root, dh_out)` = HKDF-SHA256(salt = root, ikm = dh_out, -//! info = `onionwire-ratchet-v1-kdfrk`) -> 64 bytes = `(root', chain_key)`. +//! - `KDF_RK(root, dh_out)` (v1 domain) = HKDF-SHA256(salt = root, ikm = +//! dh_out, info = `onionwire-ratchet-v1-kdfrk`) -> 64 bytes = +//! `(root', chain_key)`. Used for the bootstrap epoch and for classical +//! friends. +//! - `KDF_RK(root, dh_out, ss_kem)` (v2 domain) = HKDF-SHA256(salt = root, +//! ikm = `dh_out || ss_kem`, info = `onionwire-ratchet-v2-kdfrk`) -> 64 +//! bytes. Used by **every** hybrid ratchet step. A different input shape gets +//! a different info string on purpose: the two derivations are never +//! interchangeable, so a stripped KEM secret cannot produce the v2 chain. //! - `KDF_CK(ck)` = `(HMAC-SHA256(ck, 0x01), HMAC-SHA256(ck, 0x02))`, first 32 //! bytes each: `(message_key, next_chain_key)`. The message key is the //! ChaCha20-Poly1305 key; the 12-byte nonce is random per message. //! +//! # Hybrid ratchet keys +//! +//! Every ratchet keypair is `{x25519, ML-KEM-768}`. The ML-KEM seed is +//! HKDF-SHA256 over the X25519 ratchet secret (`ratchet-kem`), so a keypair is +//! exactly as secret as its 32-byte X25519 seed and the KEM half is never a +//! function of anything public. On a step the stepper encapsulates to the +//! receiver's current KEM ratchet key and carries the ciphertext next to its new +//! `dh_pub` and `kem_pub`; both the X25519 DH and that KEM secret feed +//! `KDF_RK`. The receiver decapsulates with the key it already holds and derives +//! the same pair of secrets. No extra round trip, no extra wire field at +//! bootstrap. +//! +//! **Epoch 0 stays classical.** The bootstrap root must be a pure function of +//! the two long-lived signed prekeys so that both peers converge — every chat +//! message is its own one-shot Noise session, and a per-session secret (such as +//! the hybrid prologue's `ss_kem`) differs for every dial and for each peer's +//! first send. Binding epoch 0 to it would give the two peers different roots +//! and different chains, breaking both-send-first convergence outright. The KEM +//! secret therefore enters at the first ratchet step, and messages sent before +//! that step remain harvest-now-decrypt-later exposed to a future X25519 break +//! (`docs/THREAT_MODEL.md`). +//! //! # Initiation and convergence //! //! Signal's X3DH init assumes exactly one side speaks first. Here every message @@ -48,6 +90,13 @@ //! decided by public-key order, never by who spoke first, so both peers derive //! the same two chains for the same pair and each sends on its own direction. //! +//! On a hybrid step the pair's shared input is `(X25519 DH, ML-KEM secret)`: +//! the stepper encapsulated to the receiver's *current* KEM ratchet key, and the +//! receiver decapsulates the same ciphertext with the matching key before it +//! rotates. That secret is a pure function of the pair as well, so the argument +//! is unchanged — with hybrid keys both peers still walk the same `(root, DH, +//! ss_kem)` sequence in the same causal order. +//! //! Invariant: *the root and the chain keys are a pure function of the sequence //! of ratchet-key pairs, and the two peers walk that sequence in the same //! causal order.* A DH ratchet step happens only when a frame arrives carrying a @@ -65,6 +114,14 @@ //! only then rotates. From the second epoch on, every rotation is a reply to an //! adopted key, so no tie-break is needed and the ratchet alternates. //! +//! # No downgrade +//! +//! A session that holds the peer's KEM ratchet key rejects a step that carries +//! only X25519 (`BadFrame("hybrid step required")`), and a session with no KEM +//! material rejects a hybrid step (`BadFrame("unexpected hybrid step")`). Once a +//! chain was established hybrid, every frame on it must carry the hybrid header. +//! There is no classical fallback path in `decrypt`. +//! //! # Bounds //! //! `MAX_SKIP` per chain jump, `MAX_SKIPPED_KEYS` stored keys with oldest-first @@ -89,19 +146,35 @@ pub const MAX_SKIP: u32 = 2000; pub const MAX_SKIPPED_KEYS: usize = 2000; /// Typed frame prefix (`[a-z]{3} ` convention). pub const FRAME_PREFIX: &[u8; 4] = b"rat "; -/// Frame version byte. +/// Frame version byte: classical header (epoch 0 and legacy friends). pub const FRAME_VERSION: u8 = 1; +/// Frame version byte: the header carries the hybrid ML-KEM ratchet section. +pub const FRAME_VERSION_HYBRID: u8 = 2; /// `dh_pub[32] || N u32 BE || PN u32 BE`. pub const HEADER_LEN: usize = 40; +/// Extra header bytes on a hybrid chain: `kem_pub || kem_ct`. +const KEM_HEADER_LEN: usize = crate::kem::PK_LEN + crate::kem::CT_LEN; +/// Hybrid header: the classical fields plus the ML-KEM ratchet section. +pub const HEADER_LEN_HYBRID: usize = HEADER_LEN + KEM_HEADER_LEN; /// Offset of the header inside a frame (`rat ` + version). pub const HEADER_OFFSET: usize = 5; -/// Serialized-state version byte. -pub const STATE_VERSION: u8 = 1; +/// Serialized-state version byte. Version 1 is the pre-hybrid layout and is +/// dropped, never migrated. +pub const STATE_VERSION: u8 = 2; const NONCE_LEN: usize = 12; const TAG_LEN: usize = 16; -const MIN_FRAME_LEN: usize = HEADER_OFFSET + HEADER_LEN + NONCE_LEN + TAG_LEN; const KDF_RK_INFO: &[u8] = b"onionwire-ratchet-v1-kdfrk"; +const KDF_RK_HYBRID_INFO: &[u8] = b"onionwire-ratchet-v2-kdfrk"; +const RATCHET_KEM_SALT: &[u8] = b"ratchet-kem"; + +// State-blob flags, wire format. +const FLAG_REMOTE_KEM: u8 = 0x01; +const FLAG_PENDING_KEM_CT: u8 = 0x02; +const FLAG_RECV_HYBRID: u8 = 0x04; +const KNOWN_FLAGS: u8 = FLAG_REMOTE_KEM | FLAG_PENDING_KEM_CT | FLAG_RECV_HYBRID; +/// Fixed part of a v2 state blob: see `to_bytes`. +const STATE_PREFIX_LEN: usize = 1 + 32 + 32 + 32 + 32 + 32 + 4 + 32 + 4 + 4 + 1 + 1 + 4; pub type Result = std::result::Result; @@ -136,11 +209,34 @@ impl std::fmt::Display for Error { impl std::error::Error for Error {} -/// `KDF_RK`: HKDF-SHA256(salt = root, ikm = dh_out) -> `(new_root, chain_key)`. +/// `KDF_RK` (v1 domain): HKDF-SHA256(salt = root, ikm = dh_out) -> +/// `(new_root, chain_key)`. The bootstrap epoch and classical friends only; +/// every hybrid step uses [`kdf_rk_hybrid`]. pub fn kdf_rk(root: &[u8; 32], dh_out: &[u8; 32]) -> ([u8; 32], [u8; 32]) { - let hk = Hkdf::::new(Some(root), dh_out); + expand_root(root, dh_out, KDF_RK_INFO) +} + +/// `KDF_RK` (v2 domain): HKDF-SHA256(salt = root, ikm = `dh_out || ss_kem`, +/// info = `onionwire-ratchet-v2-kdfrk`) -> `(new_root, chain_key)`. +/// +/// Both secrets are always input. A caller with no KEM secret must use +/// [`kdf_rk`], never a zero `ss_kem`: the two info strings differ on purpose, so +/// a classical-only derivation can never be mistaken for a hybrid one. +pub fn kdf_rk_hybrid( + root: &[u8; 32], + dh_out: &[u8; 32], + ss_kem: &[u8; 32], +) -> ([u8; 32], [u8; 32]) { + let mut ikm = Zeroizing::new([0u8; 64]); + ikm[..32].copy_from_slice(dh_out); + ikm[32..].copy_from_slice(ss_kem); + expand_root(root, &ikm[..], KDF_RK_HYBRID_INFO) +} + +fn expand_root(root: &[u8; 32], ikm: &[u8], info: &[u8]) -> ([u8; 32], [u8; 32]) { + let hk = Hkdf::::new(Some(root), ikm); let mut okm = Zeroizing::new([0u8; 64]); - hk.expand(KDF_RK_INFO, &mut okm[..]) + hk.expand(info, &mut okm[..]) .expect("64 bytes is a valid HKDF-SHA256 output length"); let mut new_root = [0u8; 32]; new_root.copy_from_slice(&okm[..32]); @@ -173,12 +269,19 @@ fn dh(secret: &[u8; 32], public: &[u8; 32]) -> [u8; 32] { .to_bytes() } -/// One ratchet keypair. The secret wipes on drop; `Debug` never prints it. +/// One ratchet keypair: X25519 plus ML-KEM-768. +/// +/// The KEM decapsulation seed is derived from the X25519 secret, so the pair is +/// exactly as secret as one 32-byte random seed and nothing in it is a function +/// of a public value. The secret halves wipe on drop; `Debug` never prints them. #[derive(Clone, Zeroize, ZeroizeOnDrop)] pub struct RatchetKeyPair { secret: Zeroizing<[u8; 32]>, #[zeroize(skip)] public: [u8; 32], + kem_seed: Zeroizing<[u8; crate::kem::SEED_LEN]>, + #[zeroize(skip)] + kem_public: Vec, } impl RatchetKeyPair { @@ -191,12 +294,40 @@ impl RatchetKeyPair { pub fn from_secret(secret: [u8; 32]) -> Self { let secret = Zeroizing::new(secret); let public = X25519Public::from(&StaticSecret::from(*secret)).to_bytes(); - Self { secret, public } + let kem_seed = ratchet_kem_seed(&secret); + let kem_public = crate::kem::pk_from_seed(&kem_seed[..]) + .expect("a 64-byte HKDF output is a valid ML-KEM seed"); + Self { + secret, + public, + kem_seed, + kem_public, + } } pub fn public(&self) -> [u8; 32] { self.public } + + /// The ML-KEM-768 ratchet encapsulation key the peer encapsulates to. + pub fn kem_public(&self) -> &[u8] { + &self.kem_public + } + + fn kem_seed(&self) -> &[u8] { + &self.kem_seed[..] + } +} + +/// `HKDF-SHA256(salt = "ratchet-kem", ikm = x25519 secret)` -> 64-byte ML-KEM +/// seed: deterministic for a ratchet secret and never derivable from the +/// ratchet *public* key. +fn ratchet_kem_seed(secret: &[u8; 32]) -> Zeroizing<[u8; crate::kem::SEED_LEN]> { + let hk = Hkdf::::new(Some(RATCHET_KEM_SALT), secret); + let mut seed = Zeroizing::new([0u8; crate::kem::SEED_LEN]); + hk.expand(b"seed", &mut seed[..]) + .expect("64 bytes is a valid HKDF-SHA256 output length"); + seed } impl std::fmt::Debug for RatchetKeyPair { @@ -204,6 +335,7 @@ impl std::fmt::Debug for RatchetKeyPair { f.debug_struct("RatchetKeyPair") .field("secret", &"") .field("public", &self.public) + .field("kem_public_len", &self.kem_public.len()) .finish() } } @@ -284,6 +416,18 @@ pub struct RatchetState { /// The peer's adopted ratchet public key. #[zeroize(skip)] remote_pub: [u8; 32], + /// The peer's adopted ML-KEM ratchet encapsulation key (`None` for a + /// classical friend, which has no KEM material at all). + #[zeroize(skip)] + remote_kem_pub: Option>, + /// The KEM ciphertext our current sending chain repeats in every header, + /// encapsulated to the peer's *next* ratchet KEM key. `None` on the + /// classical bootstrap chain. + #[zeroize(skip)] + pending_kem_ct: Option>, + /// Whether the current receiving chain was established by a hybrid step. + #[zeroize(skip)] + recv_hybrid: bool, /// Sending chain `(chain key, index)`. send_ck: Zeroizing<[u8; 32]>, #[zeroize(skip)] @@ -306,6 +450,8 @@ impl std::fmt::Debug for RatchetState { f.debug_struct("RatchetState") .field("local_pub", &self.local.public()) .field("remote_pub", &self.remote_pub) + .field("hybrid_send", &self.pending_kem_ct.is_some()) + .field("hybrid_recv", &self.recv_hybrid) .field("send_n", &self.send_n) .field("recv_n", &self.recv_n) .field("prev_send_len", &self.prev_send_len) @@ -327,6 +473,9 @@ struct StepPlan { root_key: [u8; 32], local: RatchetKeyPair, remote_pub: [u8; 32], + remote_kem_pub: Option>, + pending_kem_ct: Option>, + recv_hybrid: bool, send_ck: [u8; 32], recv: ChainPlan, retired: Vec, @@ -337,7 +486,18 @@ impl RatchetState { /// Bootstrap both chain directions from the session root, our initial /// ratchet keypair and the peer's initial ratchet public key. Both peers may /// send immediately; see the module docs for the convergence argument. - pub fn bootstrap(root_key: [u8; 32], local: RatchetKeyPair, remote_pub: [u8; 32]) -> Self { + /// + /// `remote_kem_pub` is the peer's initial ML-KEM ratchet key, or `None` for + /// a classical friend with no KEM material. Epoch 0 is derived with the + /// classical `KDF_RK` either way: its root must be a pure function of the + /// prekey DH for both-send-first to converge. The first `established` + /// rotation, not the bootstrap, is where the KEM secret enters. + pub fn bootstrap( + root_key: [u8; 32], + local: RatchetKeyPair, + remote_pub: [u8; 32], + remote_kem_pub: Option<&[u8]>, + ) -> Self { let shared = dh(&local.secret, &remote_pub); let (root, ck_lo, ck_hi) = epoch_chains(&root_key, &shared); let send_ck = chain_for(&local.public, &remote_pub, ck_lo, ck_hi); @@ -346,6 +506,9 @@ impl RatchetState { root_key: Zeroizing::new(root), local, remote_pub, + remote_kem_pub: remote_kem_pub.map(<[u8]>::to_vec), + pending_kem_ct: None, + recv_hybrid: false, send_ck: Zeroizing::new(send_ck), send_n: 0, recv_ck: Zeroizing::new(recv_ck), @@ -356,6 +519,12 @@ impl RatchetState { } } + /// Whether this session holds the peer's ML-KEM ratchet key, and therefore + /// requires a KEM section on every step. Epoch 0 is still classical. + pub fn hybrid(&self) -> bool { + self.remote_kem_pub.is_some() + } + /// Our current ratchet public key: what the peer sees in our headers. pub fn public(&self) -> [u8; 32] { self.local.public() @@ -382,7 +551,7 @@ impl RatchetState { pub fn encrypt(&mut self, plaintext: &[u8]) -> Result> { let (message_key, next_ck) = kdf_ck(&self.send_ck); - let header = header_bytes(&self.local.public(), self.send_n, self.prev_send_len); + let (version, header) = self.outgoing_header(); let mut nonce = [0u8; NONCE_LEN]; rand::rngs::OsRng.fill_bytes(&mut nonce); let cipher = ChaCha20Poly1305::new(Key::from_slice(&message_key[..])); @@ -399,15 +568,39 @@ impl RatchetState { *self.send_ck = next_ck; self.send_n += 1; - let mut frame = Vec::with_capacity(MIN_FRAME_LEN + ciphertext.len()); + let mut frame = + Vec::with_capacity(HEADER_OFFSET + header.len() + NONCE_LEN + ciphertext.len()); frame.extend_from_slice(FRAME_PREFIX); - frame.push(FRAME_VERSION); + frame.push(version); frame.extend_from_slice(&header); frame.extend_from_slice(&nonce); frame.extend_from_slice(&ciphertext); Ok(frame) } + /// The version byte and exact header bytes (the AEAD associated data) for + /// the next send. A hybrid send repeats `pending_kem_ct` and our current + /// ratchet KEM public key so a lost first frame of the chain does not wedge + /// the receiver. + fn outgoing_header(&self) -> (u8, Vec) { + match &self.pending_kem_ct { + Some(ct) => ( + FRAME_VERSION_HYBRID, + hybrid_header( + &self.local.public(), + self.send_n, + self.prev_send_len, + self.local.kem_public(), + ct, + ), + ), + None => ( + FRAME_VERSION, + header_bytes(&self.local.public(), self.send_n, self.prev_send_len).to_vec(), + ), + } + } + pub fn decrypt(&mut self, frame: &[u8]) -> Result> { let frame = Frame::parse(frame)?; @@ -420,6 +613,11 @@ impl RatchetState { } if frame.dh_pub == self.remote_pub { + // A chain has one header shape for its whole life. A stripped or + // padded frame is a different chain, not a fallback. + if frame.kem.is_some() != self.recv_hybrid { + return Err(Error::BadFrame("chain header kind")); + } let plan = self.plan_chain(&self.recv_ck, self.recv_n, &frame, self.remote_pub)?; let plaintext = open(&plan.message_key, &frame)?; self.apply_chain(plan); @@ -432,7 +630,13 @@ impl RatchetState { return Ok(plaintext); } - // A ratchet key we have not adopted yet: full DH ratchet step. + // A ratchet key we have not adopted yet: a full step, and it must agree + // with what this session knows about the peer's KEM capability. + match (&self.remote_kem_pub, frame.kem) { + (Some(_), None) => return Err(Error::BadFrame("hybrid step required")), + (None, Some(_)) => return Err(Error::BadFrame("unexpected hybrid step")), + _ => {} + } let plan = self.plan_step(&frame)?; let plaintext = open(&plan.recv.message_key, &frame)?; self.apply_step(plan); @@ -502,21 +706,50 @@ impl RatchetState { } // (a) receiving half of the step, on the pair we and the peer now share. + // The KEM secret is the one the peer encapsulated to our *current* + // ratchet KEM key; `frame.kem` (the peer's new key plus that + // ciphertext) is what makes this step hybrid. let shared = dh(&self.local.secret, &frame.dh_pub); - let (root_a, ck_lo, ck_hi) = epoch_chains(&self.root_key, &shared); + let (root_a, ck_lo, ck_hi) = match frame.kem { + Some(kem) => { + let ss = decapsulate_ratchet(&self.local, kem.ct)?; + epoch_chains_hybrid(&self.root_key, &shared, &ss) + } + None => epoch_chains(&self.root_key, &shared), + }; let recv_ck = chain_for(&frame.dh_pub, &self.local.public, ck_lo, ck_hi); let recv = self.plan_chain(&recv_ck, 0, frame, frame.dh_pub)?; // (b) sending half: a fresh keypair, so our sending direction ratchets. + // For a hybrid step we encapsulate to the peer's new ratchet KEM key and + // carry both secrets into the KDF; the ciphertext rides on every frame of + // this new sending chain. let local = RatchetKeyPair::generate(); let shared = dh(&local.secret, &frame.dh_pub); - let (root, ck_lo, ck_hi) = epoch_chains(&root_a, &shared); + let (root, ck_lo, ck_hi, pending_kem_ct) = match frame.kem { + Some(kem) => { + let (ct, ss) = crate::kem::encapsulate(kem.pk) + .map_err(|_| Error::BadFrame("kem public key"))?; + let ss: [u8; 32] = ss + .try_into() + .map_err(|_| Error::BadFrame("kem secret length"))?; + let (root, ck_lo, ck_hi) = epoch_chains_hybrid(&root_a, &shared, &ss); + (root, ck_lo, ck_hi, Some(ct)) + } + None => { + let (root, ck_lo, ck_hi) = epoch_chains(&root_a, &shared); + (root, ck_lo, ck_hi, None) + } + }; let send_ck = chain_for(&local.public, &frame.dh_pub, ck_lo, ck_hi); Ok(StepPlan { root_key: root, local, remote_pub: frame.dh_pub, + remote_kem_pub: frame.kem.map(|kem| kem.pk.to_vec()), + pending_kem_ct, + recv_hybrid: frame.kem.is_some(), send_ck, recv, retired, @@ -529,6 +762,9 @@ impl RatchetState { root_key, local, remote_pub, + remote_kem_pub, + pending_kem_ct, + recv_hybrid, send_ck, recv, retired, @@ -540,6 +776,9 @@ impl RatchetState { self.root_key = Zeroizing::new(root_key); self.local = local; self.remote_pub = remote_pub; + self.remote_kem_pub = remote_kem_pub; + self.pending_kem_ct = pending_kem_ct; + self.recv_hybrid = recv_hybrid; self.send_ck = Zeroizing::new(send_ck); self.prev_send_len = prev_send_len; self.send_n = 0; @@ -548,24 +787,39 @@ impl RatchetState { } /// Bootstrap tie-break rotation: rotate only our sending chain; the - /// receiving chain stays on the epoch both peers already share. + /// receiving chain stays on the epoch both peers already share. A hybrid + /// friend's rotation is a hybrid step too — that is what makes the first + /// rotation after epoch 0 PQ-bound. fn rotate_sending_chain(&mut self) { let local = RatchetKeyPair::generate(); let shared = dh(&local.secret, &self.remote_pub); - let (root, ck_lo, ck_hi) = epoch_chains(&self.root_key, &shared); + let (root, ck_lo, ck_hi, pending_kem_ct) = match &self.remote_kem_pub { + Some(peer_kem) => { + let (ct, ss) = crate::kem::encapsulate(peer_kem) + .expect("a ratchet KEM key is validated when it is adopted"); + let ss: [u8; 32] = ss.try_into().expect("ML-KEM secret is 32 bytes"); + let (root, ck_lo, ck_hi) = epoch_chains_hybrid(&self.root_key, &shared, &ss); + (root, ck_lo, ck_hi, Some(ct)) + } + None => { + let (root, ck_lo, ck_hi) = epoch_chains(&self.root_key, &shared); + (root, ck_lo, ck_hi, None) + } + }; let send_ck = chain_for(&local.public, &self.remote_pub, ck_lo, ck_hi); self.root_key = Zeroizing::new(root); self.send_ck = Zeroizing::new(send_ck); self.local = local; + self.pending_kem_ct = pending_kem_ct; self.prev_send_len = self.send_n; self.send_n = 0; } - /// Versioned state for the persistence card. The returned bytes contain - /// ratchet secrets — the caller owns wiping them. Layout (`STATE_VERSION` 1): + /// Versioned state for persistence. The returned bytes contain ratchet + /// secrets — the caller owns wiping them. Layout (`STATE_VERSION` 2): /// /// ```text - /// 0 version byte 0x01 + /// 0 version byte 0x02 /// 1..33 root_key /// 33..65 local ratchet secret /// 65..97 local ratchet public @@ -576,11 +830,25 @@ impl RatchetState { /// 197..201 recv_n u32 BE /// 201..205 prev_send_len u32 BE /// 205 established (0 or 1) - /// 206..210 skipped count u32 BE + /// 206 flags: 0x01 remote_kem_pub, 0x02 pending_kem_ct, 0x04 recv_hybrid + /// 207..211 skipped count u32 BE + /// then, if flagged: remote ratchet KEM public key (1184 bytes) + /// then, if flagged: pending KEM ciphertext (1088 bytes) /// then, in insertion order: dh_pub[32] || n u32 BE || message key[32] /// ``` pub fn to_bytes(&self) -> Vec { - let mut out = Zeroizing::new(Vec::with_capacity(210)); + let mut flags = 0u8; + if self.remote_kem_pub.is_some() { + flags |= FLAG_REMOTE_KEM; + } + if self.pending_kem_ct.is_some() { + flags |= FLAG_PENDING_KEM_CT; + } + if self.recv_hybrid { + flags |= FLAG_RECV_HYBRID; + } + + let mut out = Zeroizing::new(Vec::with_capacity(STATE_PREFIX_LEN)); out.push(STATE_VERSION); out.extend_from_slice(&self.root_key[..]); out.extend_from_slice(&self.local.secret[..]); @@ -592,7 +860,14 @@ impl RatchetState { out.extend_from_slice(&self.recv_n.to_be_bytes()); out.extend_from_slice(&self.prev_send_len.to_be_bytes()); out.push(u8::from(self.established)); + out.push(flags); out.extend_from_slice(&(self.skipped.len() as u32).to_be_bytes()); + if let Some(kem) = &self.remote_kem_pub { + out.extend_from_slice(kem); + } + if let Some(ct) = &self.pending_kem_ct { + out.extend_from_slice(ct); + } for (pubkey, n, key) in self.skipped.iter() { out.extend_from_slice(&pubkey); out.extend_from_slice(&n.to_be_bytes()); @@ -621,7 +896,28 @@ impl RatchetState { 1 => true, _ => return Err(Error::BadState("established flag")), }; + let flags = r.u8()?; + if flags & !KNOWN_FLAGS != 0 { + return Err(Error::BadState("state flags")); + } + // A pending ciphertext or a hybrid receive chain without the peer's + // KEM key cannot be a state this implementation wrote. + if flags & FLAG_REMOTE_KEM == 0 && flags & (FLAG_PENDING_KEM_CT | FLAG_RECV_HYBRID) != 0 { + return Err(Error::BadState("KEM state without a peer ratchet key")); + } let count = r.u32()? as usize; + let remote_kem_pub = if flags & FLAG_REMOTE_KEM != 0 { + let kem = r.take(crate::kem::PK_LEN)?; + crate::kem::decode_pk(kem).map_err(|_| Error::BadState("peer ratchet KEM key"))?; + Some(kem.to_vec()) + } else { + None + }; + let pending_kem_ct = if flags & FLAG_PENDING_KEM_CT != 0 { + Some(r.take(crate::kem::CT_LEN)?.to_vec()) + } else { + None + }; let mut skipped = SkippedKeys::default(); for _ in 0..count { let pubkey = r.array32()?; @@ -645,6 +941,9 @@ impl RatchetState { root_key, local, remote_pub, + remote_kem_pub, + pending_kem_ct, + recv_hybrid: flags & FLAG_RECV_HYBRID != 0, send_ck, recv_ck, send_n, @@ -664,6 +963,28 @@ fn epoch_chains(root: &[u8; 32], shared: &[u8; 32]) -> ([u8; 32], [u8; 32], [u8; (root, ck_lo, ck_hi) } +/// The hybrid epoch: the same two-call shape, with both secrets fed to every +/// `KDF_RK` call. +fn epoch_chains_hybrid( + root: &[u8; 32], + shared: &[u8; 32], + ss_kem: &[u8; 32], +) -> ([u8; 32], [u8; 32], [u8; 32]) { + let (root, ck_lo) = kdf_rk_hybrid(root, shared, ss_kem); + let (root, ck_hi) = kdf_rk_hybrid(&root, shared, ss_kem); + (root, ck_lo, ck_hi) +} + +/// Decapsulate the ratchet KEM ciphertext with our current ratchet keypair. +/// ML-KEM uses implicit rejection, so a tampered `ct` yields a different secret +/// rather than an error — the AEAD open is what reports it. +fn decapsulate_ratchet(local: &RatchetKeyPair, ct: &[u8]) -> Result<[u8; 32]> { + let ss = crate::kem::decapsulate(local.kem_seed(), ct) + .map_err(|_| Error::BadFrame("kem ciphertext"))?; + ss.try_into() + .map_err(|_| Error::BadFrame("kem secret length")) +} + fn chain_for(sender: &[u8; 32], receiver: &[u8; 32], ck_lo: [u8; 32], ck_hi: [u8; 32]) -> [u8; 32] { if sender <= receiver { ck_lo } else { ck_hi } } @@ -676,11 +997,31 @@ fn header_bytes(dh_pub: &[u8; 32], n: u32, pn: u32) -> [u8; HEADER_LEN] { header } +/// `dh_pub || N || PN || kem_pub || kem_ct`, the hybrid AAD. +fn hybrid_header(dh_pub: &[u8; 32], n: u32, pn: u32, kem_pub: &[u8], kem_ct: &[u8]) -> Vec { + debug_assert_eq!(kem_pub.len(), crate::kem::PK_LEN); + debug_assert_eq!(kem_ct.len(), crate::kem::CT_LEN); + let mut header = Vec::with_capacity(HEADER_LEN_HYBRID); + header.extend_from_slice(&header_bytes(dh_pub, n, pn)); + header.extend_from_slice(kem_pub); + header.extend_from_slice(kem_ct); + header +} + +/// The ML-KEM section of a hybrid header. +#[derive(Clone, Copy)] +struct KemSection<'a> { + pk: &'a [u8], + ct: &'a [u8], +} + struct Frame<'a> { - header: [u8; HEADER_LEN], + /// Exactly the bytes both sides feed to the AEAD. + header: Vec, dh_pub: [u8; 32], n: u32, pn: u32, + kem: Option>, nonce: [u8; NONCE_LEN], ciphertext: &'a [u8], } @@ -690,23 +1031,38 @@ impl<'a> Frame<'a> { if !frame.starts_with(FRAME_PREFIX) { return Err(Error::BadFrame("prefix")); } - // Length first: a frame too short to hold a header, nonce and tag is - // truncated whatever its version byte claims, and indexing anything - // past the prefix on it would be out of bounds. - if frame.len() < MIN_FRAME_LEN { + // Length first: a frame too short to hold even a version byte is + // truncated whatever it claims, and indexing `frame[4]` on it would be + // out of bounds. + if frame.len() < HEADER_OFFSET { return Err(Error::BadFrame("truncated")); } - match frame[FRAME_PREFIX.len()] { - FRAME_VERSION => {} + // The header length depends on the version, so the family's minimum is + // checked after the version is known. A short frame is still a length + // error, never a version error: parse order is load-bearing. + let (header_len, hybrid) = match frame[FRAME_PREFIX.len()] { + FRAME_VERSION => (HEADER_LEN, false), + FRAME_VERSION_HYBRID => (HEADER_LEN_HYBRID, true), _ => return Err(Error::BadFrame("version")), + }; + let min = HEADER_OFFSET + header_len + NONCE_LEN + TAG_LEN; + if frame.len() < min { + return Err(Error::BadFrame("truncated")); } - let mut header = [0u8; HEADER_LEN]; - header.copy_from_slice(&frame[HEADER_OFFSET..HEADER_OFFSET + HEADER_LEN]); + + let header = frame[HEADER_OFFSET..HEADER_OFFSET + header_len].to_vec(); let mut dh_pub = [0u8; 32]; dh_pub.copy_from_slice(&header[..32]); let n = u32::from_be_bytes(header[32..36].try_into().expect("4 bytes")); let pn = u32::from_be_bytes(header[36..40].try_into().expect("4 bytes")); - let nonce_at = HEADER_OFFSET + HEADER_LEN; + let kem = hybrid.then(|| { + let at = HEADER_OFFSET + HEADER_LEN; + KemSection { + pk: &frame[at..at + crate::kem::PK_LEN], + ct: &frame[at + crate::kem::PK_LEN..HEADER_OFFSET + HEADER_LEN_HYBRID], + } + }); + let nonce_at = HEADER_OFFSET + header_len; let mut nonce = [0u8; NONCE_LEN]; nonce.copy_from_slice(&frame[nonce_at..nonce_at + NONCE_LEN]); Ok(Self { @@ -714,6 +1070,7 @@ impl<'a> Frame<'a> { dh_pub, n, pn, + kem, nonce, ciphertext: &frame[nonce_at + NONCE_LEN..], }) diff --git a/tests/ratchet.rs b/tests/ratchet.rs index b5434ae..b653810 100644 --- a/tests/ratchet.rs +++ b/tests/ratchet.rs @@ -2,16 +2,19 @@ //! replay/tamper failure, serialization and zeroize. use onionwire::ratchet::{ - Error, FRAME_PREFIX, FRAME_VERSION, HEADER_LEN, HEADER_OFFSET, MAX_SKIP, MAX_SKIPPED_KEYS, - RatchetKeyPair, RatchetState, STATE_VERSION, kdf_ck, + Error, FRAME_PREFIX, FRAME_VERSION, FRAME_VERSION_HYBRID, HEADER_LEN, HEADER_LEN_HYBRID, + HEADER_OFFSET, MAX_SKIP, MAX_SKIPPED_KEYS, RatchetKeyPair, RatchetState, STATE_VERSION, kdf_ck, + kdf_rk, kdf_rk_hybrid, }; use zeroize::{Zeroize, ZeroizeOnDrop}; const ROOT: [u8; 32] = [0x7au8; 32]; -/// Two peers from one bootstrap root. `a` is always the peer whose ratchet key -/// sorts lower, so the documented bootstrap tie-break (lower key rotates first) -/// is predictable instead of coin-flip dependent. +/// Two hybrid peers from one bootstrap root: each knows the other's initial +/// ratchet ML-KEM key, the same way a v2 friend row lets both sides derive it. +/// `a` is always the peer whose ratchet key sorts lower, so the documented +/// bootstrap tie-break (lower key rotates first) is predictable instead of +/// coin-flip dependent. fn peers() -> (RatchetState, RatchetState) { let k1 = RatchetKeyPair::from_secret([0x11u8; 32]); let k2 = RatchetKeyPair::from_secret([0x22u8; 32]); @@ -21,10 +24,28 @@ fn peers() -> (RatchetState, RatchetState) { (k2, k1) }; let (lo_pub, hi_pub) = (lo.public(), hi.public()); + let (lo_kem, hi_kem) = (lo.kem_public().to_vec(), hi.kem_public().to_vec()); assert_ne!(lo_pub, hi_pub, "test keypairs must differ"); ( - RatchetState::bootstrap(ROOT, lo, hi_pub), - RatchetState::bootstrap(ROOT, hi, lo_pub), + RatchetState::bootstrap(ROOT, lo, hi_pub, Some(&hi_kem)), + RatchetState::bootstrap(ROOT, hi, lo_pub, Some(&lo_kem)), + ) +} + +/// The same pair for a legacy friend whose roster row carries no ML-KEM key: +/// every step stays classical. +fn classical_peers() -> (RatchetState, RatchetState) { + let k1 = RatchetKeyPair::from_secret([0x11u8; 32]); + let k2 = RatchetKeyPair::from_secret([0x22u8; 32]); + let (lo, hi) = if k1.public() < k2.public() { + (k1, k2) + } else { + (k2, k1) + }; + let (lo_pub, hi_pub) = (lo.public(), hi.public()); + ( + RatchetState::bootstrap(ROOT, lo, hi_pub, None), + RatchetState::bootstrap(ROOT, hi, lo_pub, None), ) } @@ -124,6 +145,262 @@ fn both_peers_send_first_converges_in_either_receive_order() { assert_eq!(a.decrypt(&b2).expect("a"), b"four"); } +/// Both sides of a hybrid ratchet step must land on the same root and the same +/// two chain keys. The classical halves are the two sides' view of one X25519 +/// DH and the ML-KEM secret is a real encaps/decaps round trip, so this pins +/// the mixing in `KDF_RK`, not a deterministic function called twice. +#[test] +fn hybrid_ratchet_step_derives_identical_roots_on_both_sides() { + use onionwire::kem; + use x25519_dalek::{PublicKey as X25519Public, StaticSecret}; + + let a_secret = StaticSecret::from([0x11u8; 32]); + let b_secret = StaticSecret::from([0x22u8; 32]); + let a_pub = X25519Public::from(&a_secret).to_bytes(); + let b_pub = X25519Public::from(&b_secret).to_bytes(); + let dh_a = a_secret + .diffie_hellman(&X25519Public::from(b_pub)) + .to_bytes(); + let dh_b = b_secret + .diffie_hellman(&X25519Public::from(a_pub)) + .to_bytes(); + assert_eq!(dh_a, dh_b, "the classical halves must agree first"); + + // The stepper encapsulates to the receiver's ratchet KEM key; the receiver + // decapsulates the same ciphertext with the seed it holds. + let receiver = kem::generate(); + let (ct, ss_sealer) = kem::encapsulate(&receiver.pk).expect("encapsulate"); + let ss_opener = kem::decapsulate(&receiver.seed[..], &ct).expect("decapsulate"); + let ss_sealer: [u8; 32] = ss_sealer.try_into().expect("32-byte secret"); + let ss_opener: [u8; 32] = ss_opener.try_into().expect("32-byte secret"); + assert_eq!(ss_sealer, ss_opener, "ML-KEM round trip must agree"); + + // `epoch_chains` is two KDF_RK calls on the same pair, second on the first + // call's root. Both sides must reproduce it exactly. + let (root1_a, ck_lo_a) = kdf_rk_hybrid(&ROOT, &dh_a, &ss_sealer); + let (root2_a, ck_hi_a) = kdf_rk_hybrid(&root1_a, &dh_a, &ss_sealer); + let (root1_b, ck_lo_b) = kdf_rk_hybrid(&ROOT, &dh_b, &ss_opener); + let (root2_b, ck_hi_b) = kdf_rk_hybrid(&root1_b, &dh_b, &ss_opener); + + assert_eq!( + root2_a, root2_b, + "both sides must derive the same epoch root" + ); + assert_eq!(ck_lo_a, ck_lo_b, "lo chain key differs between peers"); + assert_eq!(ck_hi_a, ck_hi_b, "hi chain key differs between peers"); + + // A different input shape under a different domain: a classical-only + // derivation can never collide with (or stand in for) the hybrid one. + let (classical_root, _) = kdf_rk(&ROOT, &dh_a); + assert_ne!( + root1_a, classical_root, + "hybrid and classical domains collide" + ); +} + +/// The regression the whole card turns on: both peers send on the bootstrap +/// epoch before either has received anything, then keep exchanging while the +/// steps are hybrid. +#[test] +fn both_peers_send_first_converges_with_hybrid_ratchet_keys() { + let (mut a, mut b) = peers(); + + let a1 = a.encrypt(b"a-first").expect("a encrypt"); + let b1 = b.encrypt(b"b-first").expect("b encrypt"); + assert_eq!( + a1[4], FRAME_VERSION, + "epoch 0 is classical: the bootstrap root is prekey-bound, not per-session" + ); + + assert_eq!(b.decrypt(&a1).expect("b decrypt a1"), b"a-first"); + assert_eq!(a.decrypt(&b1).expect("a decrypt b1"), b"b-first"); + + // Only the lower-key peer rotated on establishment; its next frame is the + // first hybrid step, and it carries a KEM section rather than a bare DH. + let a2 = a.encrypt(b"a-second").expect("a encrypt"); + assert_eq!( + a2[4], FRAME_VERSION_HYBRID, + "the first rotation after bootstrap must be a hybrid step" + ); + let b2 = b.encrypt(b"b-second").expect("b encrypt"); + assert_eq!(b.decrypt(&a2).expect("b decrypt a2"), b"a-second"); + assert_eq!(a.decrypt(&b2).expect("a decrypt b2"), b"b-second"); + + // Both directions are hybrid from here, and the conversation keeps flowing. + let a3 = a.encrypt(b"a-third").expect("a encrypt"); + let b3 = b.encrypt(b"b-third").expect("b encrypt"); + assert_eq!(b3[4], FRAME_VERSION_HYBRID, "b's reply must step hybrid"); + assert_eq!(b.decrypt(&a3).expect("b decrypt a3"), b"a-third"); + assert_eq!(a.decrypt(&b3).expect("a decrypt b3"), b"b-third"); + + let a4 = a.encrypt(b"a-fourth").expect("a encrypt"); + assert_eq!(b.decrypt(&a4).expect("b decrypt a4"), b"a-fourth"); +} + +/// Drive both peers through the bootstrap exchange until `a` (the lower key) +/// has rotated its sending chain onto a hybrid step. Returns that step frame +/// together with the receiving peer, which has not adopted the new key yet. +fn hybrid_step_frame() -> (RatchetState, RatchetState, Vec) { + let (mut a, mut b) = peers(); + let a1 = a.encrypt(b"a-bootstrap").expect("encrypt"); + let b1 = b.encrypt(b"b-bootstrap").expect("encrypt"); + assert_eq!(b.decrypt(&a1).expect("b bootstrap"), b"a-bootstrap"); + assert_eq!(a.decrypt(&b1).expect("a bootstrap"), b"b-bootstrap"); + let step = a.encrypt(b"step").expect("encrypt"); + assert_eq!(step[4], FRAME_VERSION_HYBRID, "a must have rotated"); + (a, b, step) +} + +/// No downgrade: a peer that has the friend's ML-KEM ratchet key must not +/// accept a *step* that carries only X25519. This is the attack the card names +/// — strip the KEM section from a rotation frame and hope the receiver falls +/// back to the classical `KDF_RK`. +#[test] +fn a_hybrid_peer_will_not_accept_a_classical_only_ratchet_step() { + let (_a, mut b, step) = hybrid_step_frame(); + assert!(b.hybrid(), "b holds a's ML-KEM ratchet key"); + + let before = b.to_bytes(); + let stripped = strip_kem_section(&step); + assert_eq!( + stripped[4], FRAME_VERSION, + "the downgrade frame is classical" + ); + + assert_eq!( + b.decrypt(&stripped) + .expect_err("a classical step is a downgrade"), + Error::BadFrame("hybrid step required"), + "the receiver must refuse before it ever derives a classical chain" + ); + assert_eq!( + before, + b.to_bytes(), + "a rejected downgrade mutated the state" + ); +} + +/// A tampered KEM component must fail closed: the ciphertext yields a wrong +/// secret (implicit rejection, not an error) and the public key is covered by +/// the AEAD associated data. Neither may fall back to classical `KDF_RK`. +#[test] +fn a_tampered_mlkem_header_component_fails_closed() { + let (_a, mut b, step) = hybrid_step_frame(); + + let kem_pub_at = HEADER_OFFSET + HEADER_LEN; + let kem_ct_at = kem_pub_at + 1184; + for (what, at) in [ + ("kem_pub", kem_pub_at), + ("kem_ct", kem_ct_at), + ("kem_ct tail", kem_ct_at + 1087), + ] { + let mut tampered = step.clone(); + tampered[at] ^= 0x01; + let before = b.to_bytes(); + assert_eq!( + b.decrypt(&tampered).expect_err(what), + Error::Authentication, + "a tampered {what} must not derive a usable chain" + ); + assert_eq!(before, b.to_bytes(), "a tampered {what} mutated the state"); + } + + // The genuine frame still opens afterwards: the failures were not partial. + assert_eq!(b.decrypt(&step).expect("genuine step"), b"step"); +} + +/// A legacy friend has no KEM material, so a hybrid step is not something it +/// can interpret — and it must not try. +#[test] +fn a_hybrid_step_against_a_classical_friend_is_rejected() { + let (_a, b, hybrid_step) = hybrid_step_frame(); + + let stranger = RatchetKeyPair::from_secret([0x33u8; 32]); + let mut classical = RatchetState::bootstrap(ROOT, stranger, b.public(), None); + assert!(!classical.hybrid()); + let before = classical.to_bytes(); + assert_eq!( + classical + .decrypt(&hybrid_step) + .expect_err("a classical state cannot take a hybrid step"), + Error::BadFrame("unexpected hybrid step") + ); + assert_eq!(before, classical.to_bytes()); +} + +/// Classical friends keep working end to end, including their steps: the hard +/// cut is state-shape, not a ban on non-PQ peers. +#[test] +fn a_classical_friend_still_ratchets_with_classical_frames() { + let (mut a, mut b) = classical_peers(); + let (a_pub, b_pub) = (a.public(), b.public()); + let texts = ["a1", "b1", "a2", "b2", "a3"]; + + for (i, text) in texts.iter().enumerate() { + let from_a = i % 2 == 0; + let frame = if from_a { + a.encrypt(text.as_bytes()).expect("a encrypt") + } else { + b.encrypt(text.as_bytes()).expect("b encrypt") + }; + assert_eq!(frame[4], FRAME_VERSION, "a classical friend emits v1 only"); + let opened = if from_a { + b.decrypt(&frame).expect("b decrypt") + } else { + a.decrypt(&frame).expect("a decrypt") + }; + assert_eq!(opened, text.as_bytes()); + } + assert_ne!(a.public(), a_pub, "a never ratcheted"); + assert_ne!(b.public(), b_pub, "b never ratcheted"); +} + +/// The hybrid header is ~2.3 KB, still far below the Noise body cap, and the +/// classical header is unchanged. +#[test] +fn a_hybrid_header_is_2312_bytes_and_fits_the_frame_limit() { + assert_eq!(HEADER_LEN, 40, "the classical header layout did not move"); + assert_eq!(HEADER_LEN_HYBRID, 2312, "40 + 1184 kem_pub + 1088 kem_ct"); + assert_eq!(HEADER_LEN_HYBRID, HEADER_LEN + 1184 + 1088); + + let (mut a, mut b) = peers(); + let a1 = a.encrypt(b"x").expect("encrypt"); + assert_eq!( + a1.len(), + 5 + HEADER_LEN + 12 + 1 + 16, + "classical frame size" + ); + assert_eq!(b.decrypt(&a1).expect("bootstrap"), b"x"); + + let reply = b.encrypt(b"x").expect("encrypt"); + assert_eq!(a.decrypt(&reply).expect("bootstrap reply"), b"x"); + let step = a.encrypt(b"x").expect("encrypt"); + assert_eq!(step[4], FRAME_VERSION_HYBRID); + assert_eq!( + step.len(), + 5 + HEADER_LEN_HYBRID + 12 + 1 + 16, + "hybrid frame size" + ); + assert!( + step.len() < onionwire::frame::MAX_FRAME, + "a hybrid chat frame must still fit one Noise body" + ); + assert_eq!(b.decrypt(&step).expect("hybrid"), b"x"); +} + +/// `patch` for the fields after the 40-byte classical header, and the +/// downgrade shape: a hybrid frame rebuilt as a classical one, KEM section +/// gone. Exactly what a stripped step looks like on the wire. +fn strip_kem_section(frame: &[u8]) -> Vec { + assert_eq!(frame[4], FRAME_VERSION_HYBRID, "not a hybrid frame"); + let mut out = Vec::with_capacity(frame.len() - HEADER_LEN_HYBRID + HEADER_LEN); + out.extend_from_slice(FRAME_PREFIX); + out.push(FRAME_VERSION); + out.extend_from_slice(&frame[HEADER_OFFSET..HEADER_OFFSET + HEADER_LEN]); + out.extend_from_slice(&frame[HEADER_OFFSET + HEADER_LEN_HYBRID..]); + out +} + /// A→B, B→A, A→B with the DH ratchet stepping along the way. #[test] fn round_trip_across_two_dh_ratchet_steps() { @@ -353,6 +630,33 @@ fn n_beyond_max_skip_is_rejected_and_the_state_is_untouched() { assert_eq!(after_limit_check, b.to_bytes()); } +/// The same bound on a chain established by a hybrid step: the KEM section +/// shifts the nonce, not `N`, so a rewritten `N` is still the bound the +/// receiver sees, and a rejected jump leaves the state untouched. +#[test] +fn max_skip_is_still_enforced_on_a_hybrid_chain() { + let (mut a, mut b, step) = hybrid_step_frame(); + assert_eq!(b.decrypt(&step).expect("step"), b"step"); + assert!(b.recv_index() > 0); + + let frame = a.encrypt(b"far").expect("encrypt"); + assert_eq!(frame[4], FRAME_VERSION_HYBRID, "still a hybrid chain"); + let next = b.recv_index(); + + let before = b.to_bytes(); + let too_far = patch(&frame, 32, &(next + MAX_SKIP + 1).to_be_bytes()); + assert_eq!(b.decrypt(&too_far), Err(Error::MaxSkipExceeded)); + assert_eq!(before, b.to_bytes(), "state changed on a rejected jump"); + + // `MAX_SKIP` itself is legal: it gets as far as the AEAD and fails there. + let at_limit = patch(&frame, 32, &(next + MAX_SKIP).to_be_bytes()); + assert_eq!(b.decrypt(&at_limit), Err(Error::Authentication)); + assert_eq!(before, b.to_bytes()); + + // No silent eviction from the rejected bound: the real frame still opens. + assert_eq!(b.decrypt(&frame).expect("far"), b"far"); +} + #[test] fn replay_fails_closed() { let (mut a, mut b) = peers(); @@ -423,8 +727,15 @@ fn skipped_keys_never_exceed_the_cap_and_evict_oldest_first() { #[test] fn header_tamper_fails_authentication() { - // dh_pub[0], N low byte, PN low byte: each is covered by the AEAD's AAD. - for offset in [0usize, 35, 39] { + // N and PN are covered by the AEAD's AAD. A flipped dh_pub looks like an + // unadopted step, and a classical step into a KEM-capable session is a + // downgrade: rejected before any chain is derived, which is at least as + // strong as an AEAD failure. + for (offset, expected) in [ + (0usize, Error::BadFrame("hybrid step required")), + (35, Error::Authentication), + (39, Error::Authentication), + ] { let (mut a, mut b) = peers(); let frame = a.encrypt(b"secret").expect("encrypt"); let mut tampered = frame.clone(); @@ -433,13 +744,7 @@ fn header_tamper_fails_authentication() { let err = b .decrypt(&tampered) .expect_err("tampered header must not decrypt"); - assert!( - matches!( - err, - Error::Authentication | Error::MaxSkipExceeded | Error::UsedMessageKey - ), - "unexpected error for header byte {offset}: {err:?}" - ); + assert_eq!(err, expected, "unexpected error for header byte {offset}"); // State was not advanced by the rejected frame: the real one still opens. assert_eq!(b.decrypt(&frame).expect("untampered"), b"secret"); @@ -492,55 +797,79 @@ fn state_round_trips_and_rejects_garbage() { // An absurd skipped-key count is a truncation error, not a panic or an // allocation of 4 billion entries. let mut huge_count = bytes.clone(); - huge_count[206..210].copy_from_slice(&u32::MAX.to_be_bytes()); + huge_count[207..211].copy_from_slice(&u32::MAX.to_be_bytes()); assert!(RatchetState::from_bytes(&huge_count).is_err()); } -/// Fixed size of a v1 state blob's prefix: the version byte, the root key, the +/// Fixed size of a v2 state blob's prefix: the version byte, the root key, the /// local secret and public, the remote public, both chain keys, both counters, -/// `prev_send_len`, the established flag and the skipped-key count. +/// `prev_send_len`, the established flag, the KEM flags and the skipped-key +/// count. Any optional KEM fields follow it. /// Documented in `src/ratchet.rs`'s `to_bytes` layout. -const STATE_PREFIX_LEN: usize = 1 + 32 + 32 + 32 + 32 + 32 + 4 + 32 + 4 + 4 + 1 + 4; +const STATE_PREFIX_LEN: usize = 1 + 32 + 32 + 32 + 32 + 32 + 4 + 32 + 4 + 4 + 1 + 1 + 4; /// Freeze guard for the persisted wire format. A stored session is only /// meaningful if both sides agree byte for byte on the layout, so a version /// bump or a field insertion must break this test on purpose. /// -/// `0x01` is asserted as a literal: asserting `STATE_VERSION` would silently +/// `0x02` is asserted as a literal: asserting `STATE_VERSION` would silently /// follow a bump instead of catching it, which is the whole point of the -/// guard. +/// guard. Version 1 is the pre-hybrid layout that the hard cut drops. #[test] -fn ratchet_state_blob_is_frozen_at_version_v1() { +fn ratchet_state_blob_is_frozen_at_version_v2() { let local = RatchetKeyPair::from_secret([0x11u8; 32]); let remote = RatchetKeyPair::from_secret([0x22u8; 32]); - let state = RatchetState::bootstrap(ROOT, local, remote.public()); - let bytes = state.to_bytes(); + let classical = RatchetState::bootstrap(ROOT, local, remote.public(), None); + let bytes = classical.to_bytes(); assert_eq!( - STATE_VERSION, 1, + STATE_VERSION, 2, "the frozen version byte changed: this is a wire-format break, not a refactor" ); assert_eq!( - bytes[0], 0x01, - "a state blob must start with the v1 version byte" + bytes[0], 0x02, + "a state blob must start with the v2 version byte" ); assert_eq!( bytes.len(), STATE_PREFIX_LEN, - "the fixed part of the v1 layout changed (a field was added, removed or resized)" + "the fixed part of the v2 layout changed (a field was added, removed or resized)" ); assert_eq!( bytes.len(), - 210, - "the documented v1 prefix is 210 bytes; a different number means the \ + 211, + "the documented v2 prefix is 211 bytes; a different number means the \ format moved and stored sessions need a migration path" ); + assert_eq!( + bytes[206], 0x00, + "flags: no KEM material for a classical friend" + ); + + let hybrid_local = RatchetKeyPair::from_secret([0x11u8; 32]); + let hybrid_remote = RatchetKeyPair::from_secret([0x22u8; 32]); + let hybrid = RatchetState::bootstrap( + ROOT, + hybrid_local, + hybrid_remote.public(), + Some(hybrid_remote.kem_public()), + ); + let hbytes = hybrid.to_bytes(); + assert_eq!( + hbytes[206], 0x01, + "flag bit0 marks the peer's ML-KEM ratchet key; pending ct is bit1" + ); + assert_eq!( + hbytes.len(), + STATE_PREFIX_LEN + 1184, + "the KEM ratchet public key is 1184 bytes and has no length prefix" + ); } /// A blob written by another version must come back as a typed /// `UnsupportedStateVersion`, never as a panic and never as a state decoded /// under the wrong layout. The guard must also not be over-eager: the -/// untouched v1 blob still loads. +/// untouched v2 blob still loads. #[test] fn ratchet_state_foreign_version_is_rejected_not_misread() { let (mut a, mut b) = peers(); @@ -557,7 +886,7 @@ fn ratchet_state_foreign_version_is_rejected_not_misread() { bytes.len() ); - for version in [0x00u8, 0x02, 0x7f, 0xff] { + for version in [0x00u8, 0x01, 0x7f, 0xff] { let mut foreign = bytes.clone(); foreign[0] = version; assert_eq!( @@ -567,8 +896,8 @@ fn ratchet_state_foreign_version_is_rejected_not_misread() { ); } - let reloaded = RatchetState::from_bytes(&bytes).expect("the untouched v1 blob still loads"); - assert_eq!(reloaded.to_bytes(), bytes, "v1 round trip is not stable"); + let reloaded = RatchetState::from_bytes(&bytes).expect("the untouched v2 blob still loads"); + assert_eq!(reloaded.to_bytes(), bytes, "v2 round trip is not stable"); } /// Mirrors the private `MIN_FRAME_LEN` in `src/ratchet.rs` @@ -583,7 +912,7 @@ const MIN_FRAME_LEN: usize = HEADER_OFFSET + HEADER_LEN + 12 + 16; fn short_frames_are_rejected_without_panicking() { let local = RatchetKeyPair::from_secret([0x11u8; 32]); let remote = RatchetKeyPair::from_secret([0x22u8; 32]); - let mut state = RatchetState::bootstrap(ROOT, local, remote.public()); + let mut state = RatchetState::bootstrap(ROOT, local, remote.public(), None); let before = state.to_bytes(); // The bare prefix: a prefix hit, so it must fall through to the length @@ -623,12 +952,13 @@ fn short_frames_are_rejected_without_panicking() { fn a_wrong_frame_version_is_rejected() { let local = RatchetKeyPair::from_secret([0x11u8; 32]); let remote = RatchetKeyPair::from_secret([0x22u8; 32]); - let mut state = RatchetState::bootstrap(ROOT, local, remote.public()); + let mut state = RatchetState::bootstrap(ROOT, local, remote.public(), None); let before = state.to_bytes(); + let foreign = 0x7f; // neither the classical nor the hybrid version let mut wrong = Vec::new(); wrong.extend_from_slice(FRAME_PREFIX); - wrong.push(FRAME_VERSION + 1); + wrong.push(foreign); wrong.resize(MIN_FRAME_LEN, 0); assert_eq!( @@ -644,12 +974,23 @@ fn a_wrong_frame_version_is_rejected() { // Below the minimum the length check wins, whatever the version byte says: // a frame that cannot hold a header, nonce and tag is truncated. let mut short_wrong = FRAME_PREFIX.to_vec(); - short_wrong.push(FRAME_VERSION + 1); + short_wrong.push(foreign); assert!(matches!( state.decrypt(&short_wrong), Err(Error::BadFrame(_)) )); assert_eq!(state.to_bytes(), before); + + // A hybrid-version frame shorter than a hybrid header is truncated, not a + // version error and never an out-of-bounds read of the KEM section. + let mut short_hybrid = FRAME_PREFIX.to_vec(); + short_hybrid.push(FRAME_VERSION_HYBRID); + short_hybrid.resize(MIN_FRAME_LEN, 0); + assert_eq!( + state.decrypt(&short_hybrid).expect_err("short hybrid"), + Error::BadFrame("truncated") + ); + assert_eq!(state.to_bytes(), before); } fn assert_zeroize_on_drop() {} @@ -674,7 +1015,7 @@ fn ratchet_state_wipes_its_secrets() { before[33..65].iter().any(|byte| *byte != 0), "ratchet secret should be live before zeroize" ); - assert!(before[206..210] != 0u32.to_be_bytes(), "no skipped keys"); + assert!(before[207..211] != 0u32.to_be_bytes(), "no skipped keys"); b.zeroize(); @@ -693,7 +1034,7 @@ fn ratchet_state_wipes_its_secrets() { "chain keys survived zeroize" ); assert_eq!( - after[206..210], + after[207..211], 0u32.to_be_bytes(), "skipped message keys survived zeroize" );