//! Double Ratchet for chat payloads: one state machine per friend. //! //! Wire-independent on purpose. A frame is opaque bytes that ride *inside* the //! existing Noise transport message; nothing here knows about Arti, sessions or //! the store. `rat ` follows the protocol's `[a-z]{3} ` typed-prefix convention //! (`docs/PROTOCOL.md`), so a pre-ratchet client drops it as an unknown prefix //! instead of rendering ciphertext as a chat line. //! //! # Frame //! //! ```text //! 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 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: //! //! - `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 //! is its own dialed one-shot Noise session and **either peer may send first**, //! so two peers can each build a fresh sending chain before either has received //! anything. //! //! The resolution is per-direction chains with role-separated derivation: an //! epoch is identified by the *unordered pair* of the two current ratchet public //! keys, and the epoch's two chain keys come from two `KDF_RK` calls on that //! pair's shared secret. The first call yields the chain for the direction //! `lo -> hi` (lexicographically lower public key to higher), the second — on //! the first call's root — the chain for `hi -> lo`, and the second call's root //! is the epoch's new root. Which side authored which direction is therefore //! 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 //! ratchet public key we have not adopted yet, and the side that performs the //! step is exactly the side that receives; the peer cannot have rotated a second //! time without having received ours first, so at most one rotation is ever in //! flight. Both peers therefore feed `KDF_RK` the same `(root, dh)` pairs in the //! same order and stay in lockstep — including when both peers send before //! receiving anything, and including the reply that follows that race. //! //! The bootstrap epoch is a special case: both peers may send on it immediately //! (the peer's initial ratchet public key is exchanged with the session key), so //! it needs a deterministic tie-break for the *first* rotation. The peer whose //! ratchet public key is lexicographically lower rotates; the other adopts and //! 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 //! eviction, and a skipped key is deleted as soon as it decrypts a frame. Any //! bound check happens before the state is touched, so a rejected frame leaves //! the state byte-identical. use std::collections::{BTreeMap, HashMap}; use chacha20poly1305::aead::{Aead, KeyInit, Payload}; use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce}; use hkdf::Hkdf; use hmac::{Hmac, Mac}; use rand::RngCore; use sha2::Sha256; use x25519_dalek::{PublicKey as X25519Public, StaticSecret}; use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; /// Largest gap between two messages of one chain we will derive keys for. pub const MAX_SKIP: u32 = 2000; /// Largest number of skipped message keys kept at once. 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: 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. 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 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; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Error { /// Frame is not ours: bad prefix, bad version, truncated, or trailing bytes. BadFrame(&'static str), /// Header claims a chain jump beyond `MAX_SKIP`. Nothing was advanced. MaxSkipExceeded, /// This message key is gone: replayed, already used, or older than the chain. UsedMessageKey, /// AEAD rejected the frame: wrong key or a tampered header. Authentication, /// Serialized state is not a version-1 ratchet state. BadState(&'static str), /// A serialized state with this version cannot be read. UnsupportedStateVersion(u8), } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::BadFrame(why) => write!(f, "bad ratchet frame: {why}"), Error::MaxSkipExceeded => write!(f, "ratchet chain jump exceeds MAX_SKIP"), Error::UsedMessageKey => write!(f, "ratchet message key already used"), Error::Authentication => write!(f, "ratchet frame failed authentication"), Error::BadState(why) => write!(f, "bad ratchet state: {why}"), Error::UnsupportedStateVersion(v) => write!(f, "unsupported ratchet state version {v}"), } } } impl std::error::Error for Error {} /// `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]) { 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(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]); let mut chain_key = [0u8; 32]; chain_key.copy_from_slice(&okm[32..]); (new_root, chain_key) } /// `KDF_CK`: `(message_key, next_chain_key)` = HMAC-SHA256(ck, 0x01|0x02). pub fn kdf_ck(chain_key: &[u8; 32]) -> (Zeroizing<[u8; 32]>, [u8; 32]) { let mut message_key = Zeroizing::new([0u8; 32]); message_key.copy_from_slice(&hmac_sha256(chain_key, &[0x01])); let next = hmac_sha256(chain_key, &[0x02]); (message_key, next) } fn hmac_sha256(key: &[u8; 32], data: &[u8]) -> [u8; 32] { let mut mac = as Mac>::new_from_slice(key).expect("HMAC accepts any key length"); mac.update(data); let out = mac.finalize().into_bytes(); let mut buf = [0u8; 32]; buf.copy_from_slice(&out[..32]); buf } fn dh(secret: &[u8; 32], public: &[u8; 32]) -> [u8; 32] { let secret = StaticSecret::from(*secret); secret .diffie_hellman(&X25519Public::from(*public)) .to_bytes() } /// 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 { pub fn generate() -> Self { let mut secret = Zeroizing::new([0u8; 32]); rand::rngs::OsRng.fill_bytes(&mut secret[..]); Self::from_secret(*secret) } pub fn from_secret(secret: [u8; 32]) -> Self { let secret = Zeroizing::new(secret); let public = X25519Public::from(&StaticSecret::from(*secret)).to_bytes(); 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 { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("RatchetKeyPair") .field("secret", &"") .field("public", &self.public) .field("kem_public_len", &self.kem_public.len()) .finish() } } /// `(sender ratchet public key, index in that sending chain)`. type SkippedKeyId = ([u8; 32], u32); /// A message key tagged with the chain position it belongs to. type SkippedKey = (SkippedKeyId, [u8; 32]); /// Skipped message keys, tagged with the sending ratchet key they belong to and /// the index in that chain. Evicts oldest-first at `MAX_SKIPPED_KEYS`. #[derive(Default)] struct SkippedKeys { map: HashMap)>, order: BTreeMap, next_serial: u64, } impl SkippedKeys { fn len(&self) -> usize { self.map.len() } fn peek(&self, pubkey: &[u8; 32], n: u32) -> Option> { self.map.get(&(*pubkey, n)).map(|(_, key)| key.clone()) } fn take(&mut self, pubkey: &[u8; 32], n: u32) -> Option> { let (serial, key) = self.map.remove(&(*pubkey, n))?; debug_assert!(self.order.remove(&serial).is_some()); Some(key) } fn insert(&mut self, pubkey: [u8; 32], n: u32, key: [u8; 32]) { if self.map.contains_key(&(pubkey, n)) { return; } while self.map.len() >= MAX_SKIPPED_KEYS { let Some((&serial, &old_key)) = self.order.iter().next() else { break; }; self.order.remove(&serial); let _ = self.map.remove(&old_key); } let serial = self.next_serial; self.next_serial += 1; self.map.insert((pubkey, n), (serial, Zeroizing::new(key))); self.order.insert(serial, (pubkey, n)); } /// In insertion order: `(dh_pub, n, message key)`. fn iter(&self) -> impl Iterator + '_ { self.order.iter().filter_map(|(_, &(pubkey, n))| { self.map .get(&(pubkey, n)) .map(|(_, key)| (pubkey, n, **key)) }) } } impl Zeroize for SkippedKeys { fn zeroize(&mut self) { for (_, key) in self.map.values_mut() { key.zeroize(); } self.map.clear(); self.order.clear(); } } /// One friend's Double Ratchet state. Chat only. #[derive(Zeroize, ZeroizeOnDrop)] pub struct RatchetState { /// Session root, advanced by every DH ratchet step. root_key: Zeroizing<[u8; 32]>, /// Our current ratchet keypair. local: RatchetKeyPair, /// 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)] send_n: u32, /// Receiving chain `(chain key, index)`. recv_ck: Zeroizing<[u8; 32]>, #[zeroize(skip)] recv_n: u32, /// `PN`: messages sent in our previous sending chain. #[zeroize(skip)] prev_send_len: u32, /// Cleared on the peer's first message; picks the bootstrap tie-break. #[zeroize(skip)] established: bool, skipped: SkippedKeys, } impl std::fmt::Debug for RatchetState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 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) .field("skipped", &self.skipped.len()) .finish_non_exhaustive() } } /// What a decrypt would do, fully validated, before a single field is touched. struct ChainPlan { message_key: Zeroizing<[u8; 32]>, chain_key: Zeroizing<[u8; 32]>, next_n: u32, skipped: Vec, } /// A full DH ratchet step, validated, ready to be applied. 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, prev_send_len: u32, } 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. /// /// `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); let recv_ck = chain_for(&remote_pub, &local.public, ck_lo, ck_hi); Self { 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), recv_n: 0, prev_send_len: 0, established: false, skipped: SkippedKeys::default(), } } /// 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() } /// The peer's current ratchet public key. pub fn remote_pub(&self) -> [u8; 32] { self.remote_pub } /// Index the next message we send will carry. pub fn send_index(&self) -> u32 { self.send_n } /// Index of the next message we expect on the current receiving chain. pub fn recv_index(&self) -> u32 { self.recv_n } pub fn skipped_len(&self) -> usize { self.skipped.len() } pub fn encrypt(&mut self, plaintext: &[u8]) -> Result> { let (message_key, next_ck) = kdf_ck(&self.send_ck); 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[..])); let ciphertext = cipher .encrypt( Nonce::from_slice(&nonce), Payload { msg: plaintext, aad: &header, }, ) .map_err(|_| Error::Authentication)?; *self.send_ck = next_ck; self.send_n += 1; let mut frame = Vec::with_capacity(HEADER_OFFSET + header.len() + NONCE_LEN + ciphertext.len()); frame.extend_from_slice(FRAME_PREFIX); 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)?; // A key we skipped earlier: use it, then forget it, so a replay of the // same frame fails closed. if let Some(message_key) = self.skipped.peek(&frame.dh_pub, frame.n) { let plaintext = open(&message_key, &frame)?; self.skipped.take(&frame.dh_pub, frame.n); return Ok(plaintext); } 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); if !self.established { self.established = true; if self.local.public < self.remote_pub { self.rotate_sending_chain(); } } return Ok(plaintext); } // 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); Ok(plaintext) } /// Validate a receive on a chain we already hold, deriving any keys we /// skipped over. Pure: nothing is mutated and no chain is advanced. fn plan_chain( &self, chain_key: &[u8; 32], next_n: u32, frame: &Frame, skipped_for: [u8; 32], ) -> Result { if frame.n < next_n { return Err(Error::UsedMessageKey); } let jump = frame.n - next_n; if jump > MAX_SKIP { return Err(Error::MaxSkipExceeded); } let mut ck = Zeroizing::new(*chain_key); let mut skipped = Vec::with_capacity(jump as usize); for n in next_n..frame.n { let (message_key, next) = kdf_ck(&ck); skipped.push(((skipped_for, n), *message_key)); *ck = next; } let (message_key, next_ck) = kdf_ck(&ck); Ok(ChainPlan { message_key, chain_key: Zeroizing::new(next_ck), next_n: frame.n + 1, skipped, }) } fn apply_chain(&mut self, plan: ChainPlan) { for ((pubkey, n), key) in plan.skipped { self.skipped.insert(pubkey, n, key); } *self.recv_ck = *plan.chain_key; self.recv_n = plan.next_n; } /// Validate a full DH ratchet step: retire the old chain (skipping up to /// `PN`), derive the new receiving chain, then rotate our sending keypair /// and derive the new sending chain. Pure up to the returned plan. fn plan_step(&self, frame: &Frame) -> Result { // Retire the old receiving chain: the peer tells us with `PN` how many // messages it sent there, so we can still read stragglers. if frame.pn < self.recv_n { return Err(Error::UsedMessageKey); } let jump = frame.pn - self.recv_n; if jump > MAX_SKIP { return Err(Error::MaxSkipExceeded); } let mut retired = Vec::with_capacity(jump as usize); let mut ck = Zeroizing::new(*self.recv_ck); for n in self.recv_n..frame.pn { let (message_key, next) = kdf_ck(&ck); retired.push(((self.remote_pub, n), *message_key)); *ck = next; } // (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) = 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, 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, prev_send_len: self.send_n, }) } fn apply_step(&mut self, plan: StepPlan) { let StepPlan { root_key, local, remote_pub, remote_kem_pub, pending_kem_ct, recv_hybrid, send_ck, recv, retired, prev_send_len, } = plan; for ((pubkey, n), key) in retired { self.skipped.insert(pubkey, n, key); } 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; self.established = true; self.apply_chain(recv); } /// Bootstrap tie-break rotation: rotate only our sending chain; the /// 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, 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 persistence. The returned bytes contain ratchet /// secrets — the caller owns wiping them. Layout (`STATE_VERSION` 2): /// /// ```text /// 0 version byte 0x02 /// 1..33 root_key /// 33..65 local ratchet secret /// 65..97 local ratchet public /// 97..129 remote ratchet public /// 129..161 sending chain key /// 161..165 send_n u32 BE /// 165..197 receiving chain key /// 197..201 recv_n u32 BE /// 201..205 prev_send_len u32 BE /// 205 established (0 or 1) /// 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 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[..]); out.extend_from_slice(&self.local.public); out.extend_from_slice(&self.remote_pub); out.extend_from_slice(&self.send_ck[..]); out.extend_from_slice(&self.send_n.to_be_bytes()); out.extend_from_slice(&self.recv_ck[..]); 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()); out.extend_from_slice(&key); } out.to_vec() } pub fn from_bytes(bytes: &[u8]) -> Result { let mut r = Reader::new(bytes); let version = r.u8()?; if version != STATE_VERSION { return Err(Error::UnsupportedStateVersion(version)); } let root_key = Zeroizing::new(r.array32()?); let secret = Zeroizing::new(r.array32()?); let local_pub = r.array32()?; let remote_pub = r.array32()?; let send_ck = Zeroizing::new(r.array32()?); let send_n = r.u32()?; let recv_ck = Zeroizing::new(r.array32()?); let recv_n = r.u32()?; let prev_send_len = r.u32()?; let established = match r.u8()? { 0 => false, 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()?; let n = r.u32()?; let key = r.array32()?; skipped.insert(pubkey, n, key); } r.end()?; let local = RatchetKeyPair::from_secret(*secret); if local.public != local_pub { return Err(Error::BadState( "ratchet secret does not match its public key", )); } // A blob may not smuggle in more keys than the live cap allows. if skipped.len() != count { return Err(Error::BadState("skipped key count")); } Ok(Self { root_key, local, remote_pub, remote_kem_pub, pending_kem_ct, recv_hybrid: flags & FLAG_RECV_HYBRID != 0, send_ck, recv_ck, send_n, recv_n, prev_send_len, established, skipped, }) } } /// `KDF_RK` twice on one pair: `(root, ck_lo, ck_hi)` where `lo` is the /// lexicographically lower public key of the pair. fn epoch_chains(root: &[u8; 32], shared: &[u8; 32]) -> ([u8; 32], [u8; 32], [u8; 32]) { let (root, ck_lo) = kdf_rk(root, shared); let (root, ck_hi) = kdf_rk(&root, shared); (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 } } fn header_bytes(dh_pub: &[u8; 32], n: u32, pn: u32) -> [u8; HEADER_LEN] { let mut header = [0u8; HEADER_LEN]; header[..32].copy_from_slice(dh_pub); header[32..36].copy_from_slice(&n.to_be_bytes()); header[36..40].copy_from_slice(&pn.to_be_bytes()); 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> { /// 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], } impl<'a> Frame<'a> { fn parse(frame: &'a [u8]) -> Result { if !frame.starts_with(FRAME_PREFIX) { return Err(Error::BadFrame("prefix")); } // 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")); } // 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 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 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 { header, dh_pub, n, pn, kem, nonce, ciphertext: &frame[nonce_at + NONCE_LEN..], }) } } /// AEAD-open with the header as associated data. fn open(message_key: &[u8; 32], frame: &Frame<'_>) -> Result> { let cipher = ChaCha20Poly1305::new(Key::from_slice(message_key)); cipher .decrypt( Nonce::from_slice(&frame.nonce), Payload { msg: frame.ciphertext, aad: &frame.header, }, ) .map_err(|_| Error::Authentication) } struct Reader<'a> { bytes: &'a [u8], at: usize, } impl<'a> Reader<'a> { fn new(bytes: &'a [u8]) -> Self { Self { bytes, at: 0 } } fn take(&mut self, n: usize) -> Result<&'a [u8]> { let end = self .at .checked_add(n) .ok_or(Error::BadState("length overflow"))?; let slice = self .bytes .get(self.at..end) .ok_or(Error::BadState("truncated"))?; self.at = end; Ok(slice) } fn u8(&mut self) -> Result { Ok(self.take(1)?[0]) } fn u32(&mut self) -> Result { Ok(u32::from_be_bytes( self.take(4)?.try_into().expect("4 bytes"), )) } fn array32(&mut self) -> Result<[u8; 32]> { Ok(self.take(32)?.try_into().expect("32 bytes")) } fn end(&self) -> Result<()> { if self.at != self.bytes.len() { return Err(Error::BadState("trailing bytes")); } Ok(()) } }