//! Double Ratchet module tests: KDF vectors, ratchet steps, skipped-key bounds, //! replay/tamper failure, serialization and zeroize. use onionwire::ratchet::{ 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 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]); let (lo, hi) = if k1.public() < k2.public() { (k1, k2) } else { (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, 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), ) } fn header_at(frame: &[u8]) -> [u8; 40] { frame[HEADER_OFFSET..HEADER_OFFSET + 40] .try_into() .expect("40") } fn patch(frame: &[u8], offset: usize, value: &[u8]) -> Vec { let mut out = frame.to_vec(); let at = HEADER_OFFSET + offset; out[at..at + value.len()].copy_from_slice(value); out } /// Failing test first: `KDF_CK(ck) = (HMAC-SHA256(ck, 0x01), HMAC-SHA256(ck, 0x02))`, /// first 32 bytes each, for `ck = 0x00..0x1f`. /// /// Independently computed with: /// /// ```text /// python3 -c " /// import hmac,hashlib /// ck=bytes(range(32)) /// print(hmac.new(ck,bytes([1]),hashlib.sha256).digest().hex()) /// print(hmac.new(ck,bytes([2]),hashlib.sha256).digest().hex()) /// " /// ``` #[test] fn kdf_ck_matches_an_independently_computed_vector() { let ck: [u8; 32] = std::array::from_fn(|i| i as u8); let (message_key, next_chain_key) = kdf_ck(&ck); let expected_message_key = "9b4c8120a4823a95f47cde17a244f4507244ee6e3957d1fab9fa29b44d3829b7"; let expected_next_chain_key = "4304c22c84a53755ab08ead8d97a8d429be5efa480682d7ad1da27f73e1fbe1d"; assert_eq!(hex(&message_key[..]), expected_message_key); assert_eq!(hex(&next_chain_key), expected_next_chain_key); } fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } #[test] fn frames_use_the_typed_prefix_and_version() { let (mut a, _b) = peers(); let frame = a.encrypt(b"hi").expect("encrypt"); assert_eq!(&frame[..4], FRAME_PREFIX); assert_eq!(&frame[..4], b"rat "); assert_eq!(frame[4], FRAME_VERSION); assert_eq!(header_at(&frame).len(), 40); } /// The gate of the card: both peers build and use a sending chain before either /// has received anything, then both receive, then keep exchanging. #[test] fn both_peers_send_first_converges() { let (mut a, mut b) = peers(); let (a_pub, b_pub) = (a.public(), b.public()); let a1 = a.encrypt(b"a-first").expect("a encrypt"); let b1 = b.encrypt(b"b-first").expect("b encrypt"); assert_eq!(b.decrypt(&a1).expect("b decrypt a1"), b"a-first"); assert_eq!(a.decrypt(&b1).expect("a decrypt b1"), b"b-first"); // A further exchange in both directions must still decrypt. let a2 = a.encrypt(b"a-second").expect("a encrypt"); 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"); // And the DH ratchet actually moved on both sides. assert_ne!(a.public(), a_pub, "a never rotated its ratchet key"); assert_ne!(b.public(), b_pub, "b never rotated its ratchet key"); let a3 = a.encrypt(b"a-third").expect("a encrypt"); assert_eq!(b.decrypt(&a3).expect("b decrypt a3"), b"a-third"); } /// Same race, delivered in the other order: the receiving order must not matter. #[test] fn both_peers_send_first_converges_in_either_receive_order() { let (mut a, mut b) = peers(); let a1 = a.encrypt(b"one").expect("a encrypt"); let b1 = b.encrypt(b"two").expect("b encrypt"); assert_eq!(a.decrypt(&b1).expect("a first"), b"two"); assert_eq!(b.decrypt(&a1).expect("b second"), b"one"); let a2 = a.encrypt(b"three").expect("a encrypt"); let b2 = b.encrypt(b"four").expect("b encrypt"); assert_eq!(b.decrypt(&a2).expect("b"), b"three"); 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() { let (mut a, mut b) = peers(); let (a_pub, b_pub) = (a.public(), b.public()); let m1 = a.encrypt(b"m1").expect("encrypt"); assert_eq!(b.decrypt(&m1).expect("decrypt m1"), b"m1"); let m2 = b.encrypt(b"m2").expect("encrypt"); assert_eq!(a.decrypt(&m2).expect("decrypt m2"), b"m2"); let m3 = a.encrypt(b"m3").expect("encrypt"); assert_eq!(b.decrypt(&m3).expect("decrypt m3"), b"m3"); // Both directions took at least one DH ratchet step. assert_ne!(a.public(), a_pub, "a's sending ratchet never advanced"); assert_ne!(b.public(), b_pub, "b's sending ratchet never advanced"); let m4 = b.encrypt(b"m4").expect("encrypt"); assert_eq!(a.decrypt(&m4).expect("decrypt m4"), b"m4"); } /// The ratchet key a frame advertises: `dh_pub[0..32]` of the header. fn dh_pub(frame: &[u8]) -> [u8; 32] { header_at(frame)[..32].try_into().expect("32") } /// Lockstep on a bidirectional burst: every frame after a peer has stepped /// carries the key that peer is now sending with, and the receiver *adopts /// exactly that key* before its sending chain rekeys. /// /// `round_trip_across_two_dh_ratchet_steps` only asserts that neither sending /// ratchet stayed put; it would still pass if the two sides stepped onto /// unconnected epochs, and it never checks that either side adopted the key the /// other advertised. This test reads the key out of the wire header and asserts /// the adoption, per step, on a burst in both directions. /// /// The bootstrap tie-break means one A→B/B→A round cannot step both sides: only /// the lower-key peer rotates its sending chain on establishment, and the other /// peer has still only ever seen bootstrap keys. The burst therefore drives the /// second and third rounds, and pins the intermediate state at each one. #[test] fn bidirectional_burst_keeps_the_dh_ratchet_in_lockstep() { let (mut a, mut b) = peers(); let (a0, b0) = (a.public(), b.public()); assert_eq!(a.remote_pub(), b0, "a starts keyed to b's bootstrap key"); assert_eq!(b.remote_pub(), a0, "b starts keyed to a's bootstrap key"); // Round 1 — A→B then B→A. Only a rotates here (it sorts lower). let m1 = a.encrypt(b"a/1").expect("encrypt"); assert_eq!( dh_pub(&m1), a0, "a's first frame advertises its bootstrap key" ); assert_eq!(b.decrypt(&m1).expect("b decrypts a/1"), b"a/1"); assert_eq!(b.public(), b0, "b has no new key to adopt yet"); assert_eq!(b.remote_pub(), a0); let m2 = b.encrypt(b"b/1").expect("encrypt"); assert_eq!( dh_pub(&m2), b0, "b's first frame advertises its bootstrap key" ); assert_eq!(a.decrypt(&m2).expect("a decrypts b/1"), b"b/1"); let a1 = a.public(); assert_ne!(a1, a0, "round 1 must rotate a's sending ratchet key"); assert_eq!(a.remote_pub(), b0, "a is keyed to the key b advertised"); // Round 2 — a's fresh key reaches b, which is the step the one-round // exchange never takes. let m3 = a.encrypt(b"a/2").expect("encrypt"); assert_eq!(dh_pub(&m3), a1, "a advertises the key it just ratcheted to"); assert_eq!(b.decrypt(&m3).expect("b decrypts a/2"), b"a/2"); let b1 = b.public(); assert_ne!(b1, b0, "b must DH-ratchet on a's new key"); assert_eq!(b.remote_pub(), a1, "b adopted exactly the key a advertised"); // Round 3 — the mirror image: b's fresh key reaches a. let m4 = b.encrypt(b"b/2").expect("encrypt"); assert_eq!(dh_pub(&m4), b1, "b advertises the key it just ratcheted to"); assert_eq!(a.decrypt(&m4).expect("a decrypts b/2"), b"b/2"); let a2 = a.public(); assert_ne!(a2, a1, "a stepped onto a fresh key of its own"); assert_eq!(a.remote_pub(), b1, "a adopted exactly the key b advertised"); // The burst proper: three frames each way on the epoch both sides now hold. let to_b: Vec> = (0..3) .map(|i| { a.encrypt(format!("a/burst{i}").as_bytes()) .expect("encrypt") }) .collect(); for frame in &to_b { assert_eq!(dh_pub(frame), a2, "the burst stays on a's current key"); } for (i, frame) in to_b.iter().enumerate() { assert_eq!( b.decrypt(frame).expect("burst a→b"), format!("a/burst{i}").as_bytes() ); } let b2 = b.public(); assert_ne!( b2, b1, "b's first burst frame is a full step, not a chain read" ); assert_eq!(b.remote_pub(), a2, "b adopted a's burst key"); assert_eq!(b.recv_index(), 3, "all three burst frames were consumed"); assert_eq!(b.skipped_len(), 0, "in-order burst skipped nothing"); let to_a: Vec> = (0..3) .map(|i| { b.encrypt(format!("b/burst{i}").as_bytes()) .expect("encrypt") }) .collect(); for frame in &to_a { assert_eq!(dh_pub(frame), b2, "the burst stays on b's current key"); } for (i, frame) in to_a.iter().enumerate() { assert_eq!( a.decrypt(frame).expect("burst b→a"), format!("b/burst{i}").as_bytes() ); } // Lockstep after the burst: the peer that received last is keyed to the // other's *current* key, and the sender's own key is the one its burst // advertised. (b's view of a is a2 — a's step generated a3, which has not // been sent yet; that lag is the ratchet's normal one-header asymmetry.) assert_eq!(a.remote_pub(), b2); assert_eq!(a.remote_pub(), b.public(), "a is keyed to b's current key"); assert_eq!(b.remote_pub(), a2, "b is keyed to a's last advertised key"); assert_ne!(a.public(), a2, "a stepped again on b's burst"); assert_ne!(a.public(), a0, "a never ratcheted across the whole burst"); assert_ne!(b.public(), b0, "b never ratcheted across the whole burst"); assert_eq!(a.skipped_len(), 0); assert_eq!(a.recv_index(), 3); // And the conversation still flows on the epoch the burst left behind. let after = a.encrypt(b"a/after").expect("encrypt"); assert_eq!(b.decrypt(&after).expect("a/after"), b"a/after"); } #[test] fn out_of_order_within_one_chain() { let (mut a, mut b) = peers(); let frames: Vec> = (0..5) .map(|i| a.encrypt(format!("m{i}").as_bytes()).expect("encrypt")) .collect(); assert_eq!(b.decrypt(&frames[4]).expect("4"), b"m4"); for i in [2usize, 0, 1, 3] { assert_eq!( b.decrypt(&frames[i]).expect("out of order"), format!("m{i}").as_bytes() ); } assert_eq!( b.recv_index(), 5, "chain index should have consumed all five" ); assert_eq!(b.skipped_len(), 0, "every skipped key was used"); // A fresh message continues the same chain. let next = a.encrypt(b"m5").expect("encrypt"); assert_eq!(b.decrypt(&next).expect("m5"), b"m5"); } /// The `PN` case: a key skipped in the previous chain survives a DH ratchet step. #[test] fn key_skipped_before_a_ratchet_step_still_decrypts_after_it() { let (mut a, mut b) = peers(); // A sends three; B only gets the last, so 0 and 1 are skipped. let old: Vec> = (0..3) .map(|i| a.encrypt(format!("old{i}").as_bytes()).expect("encrypt")) .collect(); assert_eq!(b.decrypt(&old[2]).expect("old2"), b"old2"); assert_eq!(b.skipped_len(), 2); // B replies; A (the lower ratchet key) rotates its sending chain. let reply = b.encrypt(b"reply").expect("encrypt"); assert_eq!(a.decrypt(&reply).expect("reply"), b"reply"); let b_pub = b.public(); // Two messages on the new epoch. B's first one is a full DH ratchet step. let new0 = a.encrypt(b"new0").expect("encrypt"); let new1 = a.encrypt(b"new1").expect("encrypt"); assert_eq!(b.decrypt(&new0).expect("new0"), b"new0"); assert_ne!(b.public(), b_pub, "b should have rotated in the step"); assert_eq!(b.decrypt(&new1).expect("new1"), b"new1"); // The old chain's skipped keys are still usable after the step. assert_eq!(b.decrypt(&old[0]).expect("old0"), b"old0"); assert_eq!(b.decrypt(&old[1]).expect("old1"), b"old1"); assert_eq!(b.skipped_len(), 0); } #[test] fn n_beyond_max_skip_is_rejected_and_the_state_is_untouched() { let (mut a, mut b) = peers(); let frame = a.encrypt(b"far").expect("encrypt"); let too_far = patch(&frame, 32, &(MAX_SKIP + 1).to_be_bytes()); let before = b.to_bytes(); let err = b .decrypt(&too_far) .expect_err("must reject a >MAX_SKIP jump"); assert_eq!(err, Error::MaxSkipExceeded); assert_eq!(before, b.to_bytes(), "state changed on a rejected frame"); // MAX_SKIP itself is legal: the bound is exclusive of the limit, so the // frame gets as far as the AEAD (wrong key -> Authentication), and the // failed open still leaves the state byte-identical. let at_limit = patch(&frame, 32, &MAX_SKIP.to_be_bytes()); let after_limit_check = b.to_bytes(); assert_eq!( b.decrypt(&at_limit).expect_err("wrong key"), Error::Authentication ); 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(); let frame = a.encrypt(b"once").expect("encrypt"); assert_eq!(b.decrypt(&frame).expect("first"), b"once"); let err = b.decrypt(&frame).expect_err("replay must fail"); assert_eq!(err, Error::UsedMessageKey); // And it really did not yield plaintext a second time: the error carries no // payload, and a decrypted-once frame is gone from the skipped store too. assert_eq!(b.skipped_len(), 0); } #[test] fn skipped_keys_never_exceed_the_cap_and_evict_oldest_first() { let (mut a, mut b) = peers(); let per_epoch = 1400usize; let mut first_epoch: Vec> = Vec::new(); let mut last_epoch: Vec> = Vec::new(); for epoch in 0..3 { let frames: Vec> = (0..per_epoch) .map(|i| { a.encrypt(format!("e{epoch}-{i}").as_bytes()) .expect("encrypt") }) .collect(); // B only receives the last frame of each chain: the rest are skipped. assert_eq!( b.decrypt(frames.last().expect("frame")).expect("last"), format!("e{epoch}-{}", per_epoch - 1).as_bytes() ); assert!( b.skipped_len() <= MAX_SKIPPED_KEYS, "store grew past the cap: {}", b.skipped_len() ); if epoch == 0 { first_epoch = frames; } else if epoch == 2 { last_epoch = frames; } else { // A reply moves A to a new sending chain for the next epoch. let reply = b.encrypt(b"reply").expect("encrypt"); assert_eq!(a.decrypt(&reply).expect("reply"), b"reply"); } } assert_eq!( b.skipped_len(), MAX_SKIPPED_KEYS, "store should be full, not under the cap" ); // The newest chain's early keys are present... assert_eq!( b.decrypt(&last_epoch[0]).expect("newest chain key kept"), b"e2-0" ); // ...and the first chain's are the ones that were evicted. assert!( b.decrypt(&first_epoch[0]).is_err(), "oldest skipped key should have been evicted" ); } #[test] fn header_tamper_fails_authentication() { // 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(); tampered[HEADER_OFFSET + offset] ^= 0x01; let err = b .decrypt(&tampered) .expect_err("tampered header must not decrypt"); 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"); } } #[test] fn state_round_trips_and_rejects_garbage() { let (mut a, mut b) = peers(); let frames: Vec> = (0..3) .map(|i| a.encrypt(format!("m{i}").as_bytes()).expect("encrypt")) .collect(); assert_eq!(b.decrypt(&frames[2]).expect("m2"), b"m2"); assert_eq!(b.skipped_len(), 2); let bytes = b.to_bytes(); assert_eq!(bytes[0], STATE_VERSION); let mut reloaded = RatchetState::from_bytes(&bytes).expect("reload"); assert_eq!(reloaded.to_bytes(), bytes, "round trip is not stable"); assert_eq!(reloaded.skipped_len(), 2); assert_eq!(reloaded.recv_index(), b.recv_index()); assert_eq!(reloaded.public(), b.public()); assert_eq!(reloaded.remote_pub(), b.remote_pub()); // A reloaded state keeps the conversation going, skipped keys included. let next = a.encrypt(b"after reload").expect("encrypt"); assert_eq!(reloaded.decrypt(&next).expect("next"), b"after reload"); assert_eq!(reloaded.decrypt(&frames[0]).expect("skipped"), b"m0"); // Truncated, empty, wrong version, trailing bytes. assert!(RatchetState::from_bytes(&[]).is_err()); assert!(RatchetState::from_bytes(&bytes[..bytes.len() - 1]).is_err()); assert!(RatchetState::from_bytes(&[0u8; 3]).is_err()); let mut trailing = bytes.clone(); trailing.push(0); assert!(RatchetState::from_bytes(&trailing).is_err()); let mut wrong_version = bytes.clone(); wrong_version[0] = STATE_VERSION + 1; assert_eq!( RatchetState::from_bytes(&wrong_version).expect_err("wrong version"), Error::UnsupportedStateVersion(STATE_VERSION + 1) ); // A tampered secret no longer matches its public key. let mut bad_secret = bytes.clone(); bad_secret[33] ^= 0xff; assert!(RatchetState::from_bytes(&bad_secret).is_err()); // 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[207..211].copy_from_slice(&u32::MAX.to_be_bytes()); assert!(RatchetState::from_bytes(&huge_count).is_err()); } /// 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, 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 + 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. /// /// `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. Version 1 is the pre-hybrid layout that the hard cut drops. #[test] fn ratchet_state_blob_is_frozen_at_version_v2() { let local = RatchetKeyPair::from_secret([0x11u8; 32]); let remote = RatchetKeyPair::from_secret([0x22u8; 32]); let classical = RatchetState::bootstrap(ROOT, local, remote.public(), None); let bytes = classical.to_bytes(); assert_eq!( STATE_VERSION, 2, "the frozen version byte changed: this is a wire-format break, not a refactor" ); assert_eq!( 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 v2 layout changed (a field was added, removed or resized)" ); assert_eq!( bytes.len(), 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 v2 blob still loads. #[test] fn ratchet_state_foreign_version_is_rejected_not_misread() { let (mut a, mut b) = peers(); // Decrypting m2 first leaves m0/m1 in the skipped store, so the blob is // longer than the fixed prefix and the check cannot pass by luck. let frames: Vec> = (0..3) .map(|i| a.encrypt(format!("m{i}").as_bytes()).expect("encrypt")) .collect(); assert_eq!(b.decrypt(&frames[2]).expect("m2"), b"m2"); let bytes = b.to_bytes(); assert!( bytes.len() > STATE_PREFIX_LEN, "expected skipped keys in the blob, got {} bytes", bytes.len() ); for version in [0x00u8, 0x01, 0x7f, 0xff] { let mut foreign = bytes.clone(); foreign[0] = version; assert_eq!( RatchetState::from_bytes(&foreign).expect_err("a foreign version must be rejected"), Error::UnsupportedStateVersion(version), "version {version:#04x} must be rejected under its own code, not misread or panicked on" ); } 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` /// (`HEADER_OFFSET + HEADER_LEN + NONCE_LEN + TAG_LEN`), which the crate does /// not export. const MIN_FRAME_LEN: usize = HEADER_OFFSET + HEADER_LEN + 12 + 16; /// A frame too short to hold a header, nonce and tag is rejected, and the bare /// 4-byte `rat ` prefix in particular must not panic by indexing `frame[4]` /// before the length check. Every rejection leaves the state byte-identical. #[test] 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(), None); let before = state.to_bytes(); // The bare prefix: a prefix hit, so it must fall through to the length // check. This is the case that used to index `frame[4]` on a 4-byte slice. let mut tail = vec![FRAME_VERSION]; tail.extend_from_slice(b"abcd"); let mut short = Vec::new(); short.extend_from_slice(FRAME_PREFIX); short.extend_from_slice(&tail); assert_eq!(short.len(), 9, "prefix plus a five-byte tail"); // A well-formed-looking header that is one byte too short to hold the // nonce and tag. let mut too_short = Vec::new(); too_short.extend_from_slice(FRAME_PREFIX); too_short.push(FRAME_VERSION); too_short.resize(MIN_FRAME_LEN - 1, 0); for (why, frame) in [ ("the bare rat prefix", &FRAME_PREFIX[..]), ("an empty slice", &[][..]), ("a partial prefix", &b"rat"[..]), ("a five-byte tail after rat ", &short[..]), ("MIN_FRAME_LEN - 1 bytes", &too_short[..]), ] { match state.decrypt(frame) { Err(Error::BadFrame(_)) => {} other => panic!("{why} was not rejected as a bad frame: {other:?}"), } assert_eq!(state.to_bytes(), before, "{why} mutated the state"); } } /// A frame long enough to hold the header but carrying a version byte this /// implementation does not speak is a version error, not a truncation. #[test] 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(), 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(foreign); wrong.resize(MIN_FRAME_LEN, 0); assert_eq!( state.decrypt(&wrong).expect_err("wrong version"), Error::BadFrame("version") ); assert_eq!( state.to_bytes(), before, "a rejected frame mutated the state" ); // 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(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() {} #[test] fn ratchet_state_wipes_its_secrets() { assert_zeroize_on_drop::(); assert_zeroize_on_drop::(); let (mut a, mut b) = peers(); let frames: Vec> = (0..3) .map(|i| a.encrypt(format!("m{i}").as_bytes()).expect("encrypt")) .collect(); let _ = b.decrypt(&frames[2]).expect("m2"); let before = b.to_bytes(); assert!( before[1..33].iter().any(|byte| *byte != 0), "root key should be live before zeroize" ); assert!( before[33..65].iter().any(|byte| *byte != 0), "ratchet secret should be live before zeroize" ); assert!(before[207..211] != 0u32.to_be_bytes(), "no skipped keys"); b.zeroize(); let after = b.to_bytes(); assert!( after[1..33].iter().all(|byte| *byte == 0), "root key survived zeroize" ); assert!( after[33..65].iter().all(|byte| *byte == 0), "ratchet secret survived zeroize" ); assert!( after[129..161].iter().all(|byte| *byte == 0) && after[165..197].iter().all(|byte| *byte == 0), "chain keys survived zeroize" ); assert_eq!( after[207..211], 0u32.to_be_bytes(), "skipped message keys survived zeroize" ); }