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.
This commit is contained in:
rust-dev 2026-10-20 12:54:30 -04:00 • committed by agent
commit b22abd7b2b
No known key found for this signature in database
7 changed files with 1198 additions and 168 deletions

View file

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