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:
parent
fec68e31ff
commit
b22abd7b2b
7 changed files with 1198 additions and 168 deletions
423
tests/ratchet.rs
423
tests/ratchet.rs
|
|
@ -2,16 +2,19 @@
|
|||
//! replay/tamper failure, serialization and zeroize.
|
||||
|
||||
use onionwire::ratchet::{
|
||||
Error, FRAME_PREFIX, FRAME_VERSION, HEADER_LEN, HEADER_OFFSET, MAX_SKIP, MAX_SKIPPED_KEYS,
|
||||
RatchetKeyPair, RatchetState, STATE_VERSION, kdf_ck,
|
||||
Error, FRAME_PREFIX, FRAME_VERSION, FRAME_VERSION_HYBRID, HEADER_LEN, HEADER_LEN_HYBRID,
|
||||
HEADER_OFFSET, MAX_SKIP, MAX_SKIPPED_KEYS, RatchetKeyPair, RatchetState, STATE_VERSION, kdf_ck,
|
||||
kdf_rk, kdf_rk_hybrid,
|
||||
};
|
||||
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||
|
||||
const ROOT: [u8; 32] = [0x7au8; 32];
|
||||
|
||||
/// Two peers from one bootstrap root. `a` is always the peer whose ratchet key
|
||||
/// sorts lower, so the documented bootstrap tie-break (lower key rotates first)
|
||||
/// is predictable instead of coin-flip dependent.
|
||||
/// Two hybrid peers from one bootstrap root: each knows the other's initial
|
||||
/// ratchet ML-KEM key, the same way a v2 friend row lets both sides derive it.
|
||||
/// `a` is always the peer whose ratchet key sorts lower, so the documented
|
||||
/// bootstrap tie-break (lower key rotates first) is predictable instead of
|
||||
/// coin-flip dependent.
|
||||
fn peers() -> (RatchetState, RatchetState) {
|
||||
let k1 = RatchetKeyPair::from_secret([0x11u8; 32]);
|
||||
let k2 = RatchetKeyPair::from_secret([0x22u8; 32]);
|
||||
|
|
@ -21,10 +24,28 @@ fn peers() -> (RatchetState, RatchetState) {
|
|||
(k2, k1)
|
||||
};
|
||||
let (lo_pub, hi_pub) = (lo.public(), hi.public());
|
||||
let (lo_kem, hi_kem) = (lo.kem_public().to_vec(), hi.kem_public().to_vec());
|
||||
assert_ne!(lo_pub, hi_pub, "test keypairs must differ");
|
||||
(
|
||||
RatchetState::bootstrap(ROOT, lo, hi_pub),
|
||||
RatchetState::bootstrap(ROOT, hi, lo_pub),
|
||||
RatchetState::bootstrap(ROOT, lo, hi_pub, Some(&hi_kem)),
|
||||
RatchetState::bootstrap(ROOT, hi, lo_pub, Some(&lo_kem)),
|
||||
)
|
||||
}
|
||||
|
||||
/// The same pair for a legacy friend whose roster row carries no ML-KEM key:
|
||||
/// every step stays classical.
|
||||
fn classical_peers() -> (RatchetState, RatchetState) {
|
||||
let k1 = RatchetKeyPair::from_secret([0x11u8; 32]);
|
||||
let k2 = RatchetKeyPair::from_secret([0x22u8; 32]);
|
||||
let (lo, hi) = if k1.public() < k2.public() {
|
||||
(k1, k2)
|
||||
} else {
|
||||
(k2, k1)
|
||||
};
|
||||
let (lo_pub, hi_pub) = (lo.public(), hi.public());
|
||||
(
|
||||
RatchetState::bootstrap(ROOT, lo, hi_pub, None),
|
||||
RatchetState::bootstrap(ROOT, hi, lo_pub, None),
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -124,6 +145,262 @@ fn both_peers_send_first_converges_in_either_receive_order() {
|
|||
assert_eq!(a.decrypt(&b2).expect("a"), b"four");
|
||||
}
|
||||
|
||||
/// Both sides of a hybrid ratchet step must land on the same root and the same
|
||||
/// two chain keys. The classical halves are the two sides' view of one X25519
|
||||
/// DH and the ML-KEM secret is a real encaps/decaps round trip, so this pins
|
||||
/// the mixing in `KDF_RK`, not a deterministic function called twice.
|
||||
#[test]
|
||||
fn hybrid_ratchet_step_derives_identical_roots_on_both_sides() {
|
||||
use onionwire::kem;
|
||||
use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
|
||||
|
||||
let a_secret = StaticSecret::from([0x11u8; 32]);
|
||||
let b_secret = StaticSecret::from([0x22u8; 32]);
|
||||
let a_pub = X25519Public::from(&a_secret).to_bytes();
|
||||
let b_pub = X25519Public::from(&b_secret).to_bytes();
|
||||
let dh_a = a_secret
|
||||
.diffie_hellman(&X25519Public::from(b_pub))
|
||||
.to_bytes();
|
||||
let dh_b = b_secret
|
||||
.diffie_hellman(&X25519Public::from(a_pub))
|
||||
.to_bytes();
|
||||
assert_eq!(dh_a, dh_b, "the classical halves must agree first");
|
||||
|
||||
// The stepper encapsulates to the receiver's ratchet KEM key; the receiver
|
||||
// decapsulates the same ciphertext with the seed it holds.
|
||||
let receiver = kem::generate();
|
||||
let (ct, ss_sealer) = kem::encapsulate(&receiver.pk).expect("encapsulate");
|
||||
let ss_opener = kem::decapsulate(&receiver.seed[..], &ct).expect("decapsulate");
|
||||
let ss_sealer: [u8; 32] = ss_sealer.try_into().expect("32-byte secret");
|
||||
let ss_opener: [u8; 32] = ss_opener.try_into().expect("32-byte secret");
|
||||
assert_eq!(ss_sealer, ss_opener, "ML-KEM round trip must agree");
|
||||
|
||||
// `epoch_chains` is two KDF_RK calls on the same pair, second on the first
|
||||
// call's root. Both sides must reproduce it exactly.
|
||||
let (root1_a, ck_lo_a) = kdf_rk_hybrid(&ROOT, &dh_a, &ss_sealer);
|
||||
let (root2_a, ck_hi_a) = kdf_rk_hybrid(&root1_a, &dh_a, &ss_sealer);
|
||||
let (root1_b, ck_lo_b) = kdf_rk_hybrid(&ROOT, &dh_b, &ss_opener);
|
||||
let (root2_b, ck_hi_b) = kdf_rk_hybrid(&root1_b, &dh_b, &ss_opener);
|
||||
|
||||
assert_eq!(
|
||||
root2_a, root2_b,
|
||||
"both sides must derive the same epoch root"
|
||||
);
|
||||
assert_eq!(ck_lo_a, ck_lo_b, "lo chain key differs between peers");
|
||||
assert_eq!(ck_hi_a, ck_hi_b, "hi chain key differs between peers");
|
||||
|
||||
// A different input shape under a different domain: a classical-only
|
||||
// derivation can never collide with (or stand in for) the hybrid one.
|
||||
let (classical_root, _) = kdf_rk(&ROOT, &dh_a);
|
||||
assert_ne!(
|
||||
root1_a, classical_root,
|
||||
"hybrid and classical domains collide"
|
||||
);
|
||||
}
|
||||
|
||||
/// The regression the whole card turns on: both peers send on the bootstrap
|
||||
/// epoch before either has received anything, then keep exchanging while the
|
||||
/// steps are hybrid.
|
||||
#[test]
|
||||
fn both_peers_send_first_converges_with_hybrid_ratchet_keys() {
|
||||
let (mut a, mut b) = peers();
|
||||
|
||||
let a1 = a.encrypt(b"a-first").expect("a encrypt");
|
||||
let b1 = b.encrypt(b"b-first").expect("b encrypt");
|
||||
assert_eq!(
|
||||
a1[4], FRAME_VERSION,
|
||||
"epoch 0 is classical: the bootstrap root is prekey-bound, not per-session"
|
||||
);
|
||||
|
||||
assert_eq!(b.decrypt(&a1).expect("b decrypt a1"), b"a-first");
|
||||
assert_eq!(a.decrypt(&b1).expect("a decrypt b1"), b"b-first");
|
||||
|
||||
// Only the lower-key peer rotated on establishment; its next frame is the
|
||||
// first hybrid step, and it carries a KEM section rather than a bare DH.
|
||||
let a2 = a.encrypt(b"a-second").expect("a encrypt");
|
||||
assert_eq!(
|
||||
a2[4], FRAME_VERSION_HYBRID,
|
||||
"the first rotation after bootstrap must be a hybrid step"
|
||||
);
|
||||
let b2 = b.encrypt(b"b-second").expect("b encrypt");
|
||||
assert_eq!(b.decrypt(&a2).expect("b decrypt a2"), b"a-second");
|
||||
assert_eq!(a.decrypt(&b2).expect("a decrypt b2"), b"b-second");
|
||||
|
||||
// Both directions are hybrid from here, and the conversation keeps flowing.
|
||||
let a3 = a.encrypt(b"a-third").expect("a encrypt");
|
||||
let b3 = b.encrypt(b"b-third").expect("b encrypt");
|
||||
assert_eq!(b3[4], FRAME_VERSION_HYBRID, "b's reply must step hybrid");
|
||||
assert_eq!(b.decrypt(&a3).expect("b decrypt a3"), b"a-third");
|
||||
assert_eq!(a.decrypt(&b3).expect("a decrypt b3"), b"b-third");
|
||||
|
||||
let a4 = a.encrypt(b"a-fourth").expect("a encrypt");
|
||||
assert_eq!(b.decrypt(&a4).expect("b decrypt a4"), b"a-fourth");
|
||||
}
|
||||
|
||||
/// Drive both peers through the bootstrap exchange until `a` (the lower key)
|
||||
/// has rotated its sending chain onto a hybrid step. Returns that step frame
|
||||
/// together with the receiving peer, which has not adopted the new key yet.
|
||||
fn hybrid_step_frame() -> (RatchetState, RatchetState, Vec<u8>) {
|
||||
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<u8> {
|
||||
assert_eq!(frame[4], FRAME_VERSION_HYBRID, "not a hybrid frame");
|
||||
let mut out = Vec::with_capacity(frame.len() - HEADER_LEN_HYBRID + HEADER_LEN);
|
||||
out.extend_from_slice(FRAME_PREFIX);
|
||||
out.push(FRAME_VERSION);
|
||||
out.extend_from_slice(&frame[HEADER_OFFSET..HEADER_OFFSET + HEADER_LEN]);
|
||||
out.extend_from_slice(&frame[HEADER_OFFSET + HEADER_LEN_HYBRID..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// A→B, B→A, A→B with the DH ratchet stepping along the way.
|
||||
#[test]
|
||||
fn round_trip_across_two_dh_ratchet_steps() {
|
||||
|
|
@ -353,6 +630,33 @@ fn n_beyond_max_skip_is_rejected_and_the_state_is_untouched() {
|
|||
assert_eq!(after_limit_check, b.to_bytes());
|
||||
}
|
||||
|
||||
/// The same bound on a chain established by a hybrid step: the KEM section
|
||||
/// shifts the nonce, not `N`, so a rewritten `N` is still the bound the
|
||||
/// receiver sees, and a rejected jump leaves the state untouched.
|
||||
#[test]
|
||||
fn max_skip_is_still_enforced_on_a_hybrid_chain() {
|
||||
let (mut a, mut b, step) = hybrid_step_frame();
|
||||
assert_eq!(b.decrypt(&step).expect("step"), b"step");
|
||||
assert!(b.recv_index() > 0);
|
||||
|
||||
let frame = a.encrypt(b"far").expect("encrypt");
|
||||
assert_eq!(frame[4], FRAME_VERSION_HYBRID, "still a hybrid chain");
|
||||
let next = b.recv_index();
|
||||
|
||||
let before = b.to_bytes();
|
||||
let too_far = patch(&frame, 32, &(next + MAX_SKIP + 1).to_be_bytes());
|
||||
assert_eq!(b.decrypt(&too_far), Err(Error::MaxSkipExceeded));
|
||||
assert_eq!(before, b.to_bytes(), "state changed on a rejected jump");
|
||||
|
||||
// `MAX_SKIP` itself is legal: it gets as far as the AEAD and fails there.
|
||||
let at_limit = patch(&frame, 32, &(next + MAX_SKIP).to_be_bytes());
|
||||
assert_eq!(b.decrypt(&at_limit), Err(Error::Authentication));
|
||||
assert_eq!(before, b.to_bytes());
|
||||
|
||||
// No silent eviction from the rejected bound: the real frame still opens.
|
||||
assert_eq!(b.decrypt(&frame).expect("far"), b"far");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_fails_closed() {
|
||||
let (mut a, mut b) = peers();
|
||||
|
|
@ -423,8 +727,15 @@ fn skipped_keys_never_exceed_the_cap_and_evict_oldest_first() {
|
|||
|
||||
#[test]
|
||||
fn header_tamper_fails_authentication() {
|
||||
// dh_pub[0], N low byte, PN low byte: each is covered by the AEAD's AAD.
|
||||
for offset in [0usize, 35, 39] {
|
||||
// N and PN are covered by the AEAD's AAD. A flipped dh_pub looks like an
|
||||
// unadopted step, and a classical step into a KEM-capable session is a
|
||||
// downgrade: rejected before any chain is derived, which is at least as
|
||||
// strong as an AEAD failure.
|
||||
for (offset, expected) in [
|
||||
(0usize, Error::BadFrame("hybrid step required")),
|
||||
(35, Error::Authentication),
|
||||
(39, Error::Authentication),
|
||||
] {
|
||||
let (mut a, mut b) = peers();
|
||||
let frame = a.encrypt(b"secret").expect("encrypt");
|
||||
let mut tampered = frame.clone();
|
||||
|
|
@ -433,13 +744,7 @@ fn header_tamper_fails_authentication() {
|
|||
let err = b
|
||||
.decrypt(&tampered)
|
||||
.expect_err("tampered header must not decrypt");
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
Error::Authentication | Error::MaxSkipExceeded | Error::UsedMessageKey
|
||||
),
|
||||
"unexpected error for header byte {offset}: {err:?}"
|
||||
);
|
||||
assert_eq!(err, expected, "unexpected error for header byte {offset}");
|
||||
|
||||
// State was not advanced by the rejected frame: the real one still opens.
|
||||
assert_eq!(b.decrypt(&frame).expect("untampered"), b"secret");
|
||||
|
|
@ -492,55 +797,79 @@ fn state_round_trips_and_rejects_garbage() {
|
|||
// An absurd skipped-key count is a truncation error, not a panic or an
|
||||
// allocation of 4 billion entries.
|
||||
let mut huge_count = bytes.clone();
|
||||
huge_count[206..210].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
huge_count[207..211].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
assert!(RatchetState::from_bytes(&huge_count).is_err());
|
||||
}
|
||||
|
||||
/// Fixed size of a v1 state blob's prefix: the version byte, the root key, the
|
||||
/// Fixed size of a v2 state blob's prefix: the version byte, the root key, the
|
||||
/// local secret and public, the remote public, both chain keys, both counters,
|
||||
/// `prev_send_len`, the established flag and the skipped-key count.
|
||||
/// `prev_send_len`, the established flag, the KEM flags and the skipped-key
|
||||
/// count. Any optional KEM fields follow it.
|
||||
/// Documented in `src/ratchet.rs`'s `to_bytes` layout.
|
||||
const STATE_PREFIX_LEN: usize = 1 + 32 + 32 + 32 + 32 + 32 + 4 + 32 + 4 + 4 + 1 + 4;
|
||||
const STATE_PREFIX_LEN: usize = 1 + 32 + 32 + 32 + 32 + 32 + 4 + 32 + 4 + 4 + 1 + 1 + 4;
|
||||
|
||||
/// Freeze guard for the persisted wire format. A stored session is only
|
||||
/// meaningful if both sides agree byte for byte on the layout, so a version
|
||||
/// bump or a field insertion must break this test on purpose.
|
||||
///
|
||||
/// `0x01` is asserted as a literal: asserting `STATE_VERSION` would silently
|
||||
/// `0x02` is asserted as a literal: asserting `STATE_VERSION` would silently
|
||||
/// follow a bump instead of catching it, which is the whole point of the
|
||||
/// guard.
|
||||
/// guard. Version 1 is the pre-hybrid layout that the hard cut drops.
|
||||
#[test]
|
||||
fn ratchet_state_blob_is_frozen_at_version_v1() {
|
||||
fn ratchet_state_blob_is_frozen_at_version_v2() {
|
||||
let local = RatchetKeyPair::from_secret([0x11u8; 32]);
|
||||
let remote = RatchetKeyPair::from_secret([0x22u8; 32]);
|
||||
let state = RatchetState::bootstrap(ROOT, local, remote.public());
|
||||
let bytes = state.to_bytes();
|
||||
|
||||
let classical = RatchetState::bootstrap(ROOT, local, remote.public(), None);
|
||||
let bytes = classical.to_bytes();
|
||||
assert_eq!(
|
||||
STATE_VERSION, 1,
|
||||
STATE_VERSION, 2,
|
||||
"the frozen version byte changed: this is a wire-format break, not a refactor"
|
||||
);
|
||||
assert_eq!(
|
||||
bytes[0], 0x01,
|
||||
"a state blob must start with the v1 version byte"
|
||||
bytes[0], 0x02,
|
||||
"a state blob must start with the v2 version byte"
|
||||
);
|
||||
assert_eq!(
|
||||
bytes.len(),
|
||||
STATE_PREFIX_LEN,
|
||||
"the fixed part of the v1 layout changed (a field was added, removed or resized)"
|
||||
"the fixed part of the v2 layout changed (a field was added, removed or resized)"
|
||||
);
|
||||
assert_eq!(
|
||||
bytes.len(),
|
||||
210,
|
||||
"the documented v1 prefix is 210 bytes; a different number means the \
|
||||
211,
|
||||
"the documented v2 prefix is 211 bytes; a different number means the \
|
||||
format moved and stored sessions need a migration path"
|
||||
);
|
||||
assert_eq!(
|
||||
bytes[206], 0x00,
|
||||
"flags: no KEM material for a classical friend"
|
||||
);
|
||||
|
||||
let hybrid_local = RatchetKeyPair::from_secret([0x11u8; 32]);
|
||||
let hybrid_remote = RatchetKeyPair::from_secret([0x22u8; 32]);
|
||||
let hybrid = RatchetState::bootstrap(
|
||||
ROOT,
|
||||
hybrid_local,
|
||||
hybrid_remote.public(),
|
||||
Some(hybrid_remote.kem_public()),
|
||||
);
|
||||
let hbytes = hybrid.to_bytes();
|
||||
assert_eq!(
|
||||
hbytes[206], 0x01,
|
||||
"flag bit0 marks the peer's ML-KEM ratchet key; pending ct is bit1"
|
||||
);
|
||||
assert_eq!(
|
||||
hbytes.len(),
|
||||
STATE_PREFIX_LEN + 1184,
|
||||
"the KEM ratchet public key is 1184 bytes and has no length prefix"
|
||||
);
|
||||
}
|
||||
|
||||
/// A blob written by another version must come back as a typed
|
||||
/// `UnsupportedStateVersion`, never as a panic and never as a state decoded
|
||||
/// under the wrong layout. The guard must also not be over-eager: the
|
||||
/// untouched v1 blob still loads.
|
||||
/// untouched v2 blob still loads.
|
||||
#[test]
|
||||
fn ratchet_state_foreign_version_is_rejected_not_misread() {
|
||||
let (mut a, mut b) = peers();
|
||||
|
|
@ -557,7 +886,7 @@ fn ratchet_state_foreign_version_is_rejected_not_misread() {
|
|||
bytes.len()
|
||||
);
|
||||
|
||||
for version in [0x00u8, 0x02, 0x7f, 0xff] {
|
||||
for version in [0x00u8, 0x01, 0x7f, 0xff] {
|
||||
let mut foreign = bytes.clone();
|
||||
foreign[0] = version;
|
||||
assert_eq!(
|
||||
|
|
@ -567,8 +896,8 @@ fn ratchet_state_foreign_version_is_rejected_not_misread() {
|
|||
);
|
||||
}
|
||||
|
||||
let reloaded = RatchetState::from_bytes(&bytes).expect("the untouched v1 blob still loads");
|
||||
assert_eq!(reloaded.to_bytes(), bytes, "v1 round trip is not stable");
|
||||
let reloaded = RatchetState::from_bytes(&bytes).expect("the untouched v2 blob still loads");
|
||||
assert_eq!(reloaded.to_bytes(), bytes, "v2 round trip is not stable");
|
||||
}
|
||||
|
||||
/// Mirrors the private `MIN_FRAME_LEN` in `src/ratchet.rs`
|
||||
|
|
@ -583,7 +912,7 @@ const MIN_FRAME_LEN: usize = HEADER_OFFSET + HEADER_LEN + 12 + 16;
|
|||
fn short_frames_are_rejected_without_panicking() {
|
||||
let local = RatchetKeyPair::from_secret([0x11u8; 32]);
|
||||
let remote = RatchetKeyPair::from_secret([0x22u8; 32]);
|
||||
let mut state = RatchetState::bootstrap(ROOT, local, remote.public());
|
||||
let mut state = RatchetState::bootstrap(ROOT, local, remote.public(), None);
|
||||
let before = state.to_bytes();
|
||||
|
||||
// The bare prefix: a prefix hit, so it must fall through to the length
|
||||
|
|
@ -623,12 +952,13 @@ fn short_frames_are_rejected_without_panicking() {
|
|||
fn a_wrong_frame_version_is_rejected() {
|
||||
let local = RatchetKeyPair::from_secret([0x11u8; 32]);
|
||||
let remote = RatchetKeyPair::from_secret([0x22u8; 32]);
|
||||
let mut state = RatchetState::bootstrap(ROOT, local, remote.public());
|
||||
let mut state = RatchetState::bootstrap(ROOT, local, remote.public(), None);
|
||||
let before = state.to_bytes();
|
||||
|
||||
let foreign = 0x7f; // neither the classical nor the hybrid version
|
||||
let mut wrong = Vec::new();
|
||||
wrong.extend_from_slice(FRAME_PREFIX);
|
||||
wrong.push(FRAME_VERSION + 1);
|
||||
wrong.push(foreign);
|
||||
wrong.resize(MIN_FRAME_LEN, 0);
|
||||
|
||||
assert_eq!(
|
||||
|
|
@ -644,12 +974,23 @@ fn a_wrong_frame_version_is_rejected() {
|
|||
// Below the minimum the length check wins, whatever the version byte says:
|
||||
// a frame that cannot hold a header, nonce and tag is truncated.
|
||||
let mut short_wrong = FRAME_PREFIX.to_vec();
|
||||
short_wrong.push(FRAME_VERSION + 1);
|
||||
short_wrong.push(foreign);
|
||||
assert!(matches!(
|
||||
state.decrypt(&short_wrong),
|
||||
Err(Error::BadFrame(_))
|
||||
));
|
||||
assert_eq!(state.to_bytes(), before);
|
||||
|
||||
// A hybrid-version frame shorter than a hybrid header is truncated, not a
|
||||
// version error and never an out-of-bounds read of the KEM section.
|
||||
let mut short_hybrid = FRAME_PREFIX.to_vec();
|
||||
short_hybrid.push(FRAME_VERSION_HYBRID);
|
||||
short_hybrid.resize(MIN_FRAME_LEN, 0);
|
||||
assert_eq!(
|
||||
state.decrypt(&short_hybrid).expect_err("short hybrid"),
|
||||
Error::BadFrame("truncated")
|
||||
);
|
||||
assert_eq!(state.to_bytes(), before);
|
||||
}
|
||||
|
||||
fn assert_zeroize_on_drop<T: ZeroizeOnDrop>() {}
|
||||
|
|
@ -674,7 +1015,7 @@ fn ratchet_state_wipes_its_secrets() {
|
|||
before[33..65].iter().any(|byte| *byte != 0),
|
||||
"ratchet secret should be live before zeroize"
|
||||
);
|
||||
assert!(before[206..210] != 0u32.to_be_bytes(), "no skipped keys");
|
||||
assert!(before[207..211] != 0u32.to_be_bytes(), "no skipped keys");
|
||||
|
||||
b.zeroize();
|
||||
|
||||
|
|
@ -693,7 +1034,7 @@ fn ratchet_state_wipes_its_secrets() {
|
|||
"chain keys survived zeroize"
|
||||
);
|
||||
assert_eq!(
|
||||
after[206..210],
|
||||
after[207..211],
|
||||
0u32.to_be_bytes(),
|
||||
"skipped message keys survived zeroize"
|
||||
);
|
||||
|
|
|
|||
Loading…
Reference in a new issue