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

@ -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<T> = std::result::Result<T, Error>;
@ -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::<Sha256>::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::<Sha256>::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<u8>,
}
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::<Sha256>::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", &"<redacted>")
.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<Vec<u8>>,
/// 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<Vec<u8>>,
/// 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<Vec<u8>>,
pending_kem_ct: Option<Vec<u8>>,
recv_hybrid: bool,
send_ck: [u8; 32],
recv: ChainPlan,
retired: Vec<SkippedKey>,
@ -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<Vec<u8>> {
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<u8>) {
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<Vec<u8>> {
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<u8> {
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<u8> {
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<u8>,
dh_pub: [u8; 32],
n: u32,
pn: u32,
kem: Option<KemSection<'a>>,
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..],
})