//! What the chat ratchet refuses: attacks, bounds, desync, corruption. //! //! Same offline harness as `tests/ratchet_e2e.rs` — real encrypted stores, real //! identity keys, the real `encode_chat_frame` / `ingest_chat_frame` pair that //! `Node::send` and `Node::handle_incoming` call, and a capture-and-release //! `Deliverer` so the test decides what arrives, when, and how often. //! //! The load-bearing assertions are that a rejected frame is *dropped* (no chat //! line) and that it leaves the persisted `ratchet_sessions` blob byte-identical //! — not merely that a message did not appear. use std::collections::{HashMap, VecDeque}; use std::path::Path; use std::sync::{Arc, Mutex}; use onionwire::Store; use onionwire::node::{encode_chat_frame, ingest_chat_frame}; use onionwire::outbox::{BoxFut, Deliverer, Outbox, OutboxStatus}; use onionwire::ratchet::{HEADER_OFFSET, MAX_SKIP, RatchetState}; use onionwire::session::Keys; const PASS: &str = "ratchet-adv-pass"; const ONION: &str = "peer.onion"; /// Capture-and-release transport: a delivery is recorded for its recipient and /// reported successful, so the test controls arrival order and drops. #[derive(Default)] struct Wire { queues: Mutex, VecDeque>>>, } impl Wire { fn new() -> Arc { Arc::new(Self::default()) } fn take(&self, to: &[u8]) -> Vec> { self.queues .lock() .unwrap() .remove(to) .map(|q| q.into_iter().collect()) .unwrap_or_default() } } impl Deliverer for Wire { fn deliver<'a>( &'a self, _onion: &'a str, pinned_id: &'a [u8], _prekey: &'a [u8], payload: &'a [u8], ) -> BoxFut<'a, Result<(), String>> { self.queues .lock() .unwrap() .entry(pinned_id.to_vec()) .or_default() .push_back(payload.to_vec()); Box::pin(async { Ok(()) }) } } struct Peer { store: Arc>, keys: Keys, } impl Peer { fn open_at(home: &Path) -> Self { let store = Store::open_at_with_passphrase(home, PASS).expect("open store"); let me = store.self_identity().expect("self identity"); let keys = Keys::from_self(&me).expect("keys from store identity"); Self { store: Arc::new(Mutex::new(store)), keys, } } fn pk(&self) -> Vec { self.keys.identity_pk.to_vec() } fn add_friend(&self, other: &Peer) { let s = self.store.lock().unwrap(); s.upsert_friend(&other.pk(), ONION, None) .expect("upsert friend"); s.set_friend_prekey(&other.pk(), &other.keys.prekey_pk) .expect("set friend prekey"); } async fn send(&self, outbox: &Outbox, to: &Peer, text: &[u8]) -> OutboxStatus { let frame = { let s = self.store.lock().unwrap(); encode_chat_frame(&s, &self.keys, &to.pk(), text).expect("encode chat frame") }; outbox .send_payload(&to.pk(), text, &frame) .await .expect("send payload") } fn ingest(&self, from: &Peer, frame: &[u8]) -> Result, String> { let s = self.store.lock().unwrap(); ingest_chat_frame(&s, &self.keys, &from.pk(), frame) } fn lines(&self, other: &Peer) -> Vec<(String, String)> { self.store .lock() .unwrap() .list_messages(&other.pk()) .expect("list messages") .into_iter() .map(|m| { ( m.dir, String::from_utf8(m.plaintext).expect("utf8 chat line"), ) }) .collect() } fn ratchet_blob(&self, other: &Peer) -> Option> { self.store .lock() .unwrap() .load_ratchet(&other.pk()) .expect("load ratchet") } fn clear_ratchet(&self, other: &Peer) { self.store .lock() .unwrap() .clear_ratchet(&other.pk()) .expect("clear ratchet"); } } /// Send `count` chat lines from `from` and hand back the captured frames. async fn send_n(from: &Peer, to: &Peer, wire: &Arc, count: usize) -> Vec> { let outbox = Outbox::new(Arc::clone(&from.store), wire.clone()); for i in 0..count { let text = format!("m{i}"); assert_eq!( from.send(&outbox, to, text.as_bytes()).await, OutboxStatus::Sent ); } let frames = wire.take(&to.pk()); assert_eq!(frames.len(), count, "one captured frame per send"); frames } /// The `N` (sender's index in its sending chain) carried by a frame header. fn frame_n(frame: &[u8]) -> u32 { let at = HEADER_OFFSET + 32; u32::from_be_bytes(frame[at..at + 4].try_into().expect("4 bytes")) } /// A frame with a rewritten `N`, still well-formed: whatever rejects it in /// `decrypt` is the bound, not the parser. fn with_n(frame: &[u8], n: u32) -> Vec { let mut out = frame.to_vec(); let at = HEADER_OFFSET + 32; out[at..at + 4].copy_from_slice(&n.to_be_bytes()); out } fn two_peers(dir: &Path) -> (Peer, Peer, Arc) { let wire = Wire::new(); let alice = Peer::open_at(&dir.join("alice")); let bob = Peer::open_at(&dir.join("bob")); alice.add_friend(&bob); bob.add_friend(&alice); (alice, bob, wire) } #[tokio::test] async fn a_frame_claiming_a_skip_past_max_skip_is_dropped_with_the_state_untouched() { let dir = tempfile::tempdir().unwrap(); let (alice, bob, wire) = two_peers(dir.path()); let frames = send_n(&alice, &bob, &wire, 2).await; assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0"); // The next frame Alice would send claims index 1 on the chain Bob is on. let fresh = frames[1].clone(); assert_eq!(frame_n(&fresh), 1, "the sender's chain index"); let before = bob.ratchet_blob(&alice).expect("bob has a session"); let lines_before = bob.lines(&alice); // A well-formed frame claiming 2001 messages further along the chain. let crafted = with_n(&fresh, 1 + MAX_SKIP + 1); let err = bob .ingest(&alice, &crafted) .expect_err("a jump past MAX_SKIP must be dropped"); assert!( err.contains("MAX_SKIP"), "the bound must reject it, not the AEAD: {err}" ); assert_eq!(bob.lines(&alice), lines_before, "no chat line"); assert_eq!( bob.ratchet_blob(&alice).expect("session still there"), before, "the persisted ratchet state is byte-identical" ); // The bound is exclusive of the limit: a jump of exactly MAX_SKIP is inside // it, so that frame is rejected for its tag, not for its length. This pins // the off-by-one in the other direction. let at_limit = with_n(&fresh, 1 + MAX_SKIP); let err = bob .ingest(&alice, &at_limit) .expect_err("a tampered header still fails to authenticate"); assert!( !err.contains("MAX_SKIP"), "MAX_SKIP itself is allowed through the bound: {err}" ); assert_eq!( bob.ratchet_blob(&alice).expect("session still there"), before, "and it too left the state byte-identical" ); // Nothing is wedged: the real frame still lands. assert_eq!(bob.ingest(&alice, &fresh).unwrap(), b"m1"); } #[tokio::test] async fn a_snapshot_heals_only_once_the_ratchet_key_it_held_has_been_replaced() { let dir = tempfile::tempdir().unwrap(); let (alice, bob, wire) = two_peers(dir.path()); let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone()); let to_alice = Outbox::new(Arc::clone(&bob.store), wire.clone()); // Three frames on one chain; Bob takes the last two, so his state also // legitimately holds the skipped key for the first. let frames = send_n(&alice, &bob, &wire, 3).await; assert_eq!(bob.ingest(&alice, &frames[1]).unwrap(), b"m1"); assert_eq!(bob.ingest(&alice, &frames[2]).unwrap(), b"m2"); // The compromise: everything Bob's session was at this point. let snapshot_blob = bob.ratchet_blob(&alice).expect("bob has a session"); let mut snapshot = RatchetState::from_bytes(&snapshot_blob).expect("snapshot parses"); // What the snapshot can still read: exactly the skipped key it was holding, // once. Everything it already consumed is gone. assert_eq!( snapshot.decrypt(&frames[0]).unwrap(), b"m0", "a skipped key it legitimately holds" ); let again = snapshot .decrypt(&frames[0]) .expect_err("the skipped key is used up") .to_string(); assert!(again.contains("already used"), "{again}"); let used = snapshot .decrypt(&frames[1]) .expect_err("a consumed message key is gone") .to_string(); assert!(used.contains("already used"), "{used}"); // Round one: Bob speaks, Alice adopts his key and answers. That epoch is // built on Bob's ratchet key, which the snapshot still holds — a Double // Ratchet heals on the *next* step, not this one. assert_eq!(bob.send(&to_alice, &alice, b"r0").await, OutboxStatus::Sent); let r0 = wire.take(&alice.pk()).remove(0); assert_eq!(alice.ingest(&bob, &r0).unwrap(), b"r0"); assert_eq!(alice.send(&to_bob, &bob, b"a3").await, OutboxStatus::Sent); let a3 = wire.take(&bob.pk()).remove(0); assert_eq!(bob.ingest(&alice, &a3).unwrap(), b"a3"); // Round two: Bob answers on the key he minted when he adopted `a3`, and // Alice adopts that. This epoch needs a ratchet secret the snapshot never // had — Bob generated it after the compromise. assert_eq!(bob.send(&to_alice, &alice, b"r1").await, OutboxStatus::Sent); let r1 = wire.take(&alice.pk()).remove(0); assert_eq!(alice.ingest(&bob, &r1).unwrap(), b"r1"); assert_eq!(alice.send(&to_bob, &bob, b"a4").await, OutboxStatus::Sent); let a4 = wire.take(&bob.pk()).remove(0); assert_eq!( bob.ingest(&alice, &a4).unwrap(), b"a4", "the live session, which minted a new ratchet key, keeps working" ); let live = RatchetState::from_bytes(&bob.ratchet_blob(&alice).expect("live session")) .expect("live state parses"); assert!( live.public() != snapshot.public() && live.remote_pub() != snapshot.remote_pub(), "at least one DH ratchet step happened after the snapshot" ); // The epoch built on the snapshot's own key is still readable: that is the // documented Double Ratchet hop, and it is why the claim below is worded // about the epoch that requires a secret minted after the compromise. assert_eq!( snapshot.decrypt(&a3).unwrap(), b"a3", "the epoch built on the key the snapshot already held" ); let after = snapshot .decrypt(&a4) .expect_err("the compromised snapshot must not read the healed epoch") .to_string(); assert!( !after.contains("MAX_SKIP") && !after.contains("bad frame"), "it fails on the keys, not the framing: {after}" ); // The live session's history is the whole conversation and nothing extra. assert_eq!( bob.lines(&alice) .iter() .map(|(_, t)| t.as_str()) .collect::>(), ["m1", "m2", "r0", "a3", "r1", "a4"] ); } #[tokio::test] async fn a_ratchet_frame_for_an_unknown_friend_is_dropped_without_a_session() { let dir = tempfile::tempdir().unwrap(); let (alice, bob, wire) = two_peers(dir.path()); // A third identity Bob has never scanned an invite from. let stranger = Peer::open_at(&dir.path().join("stranger")); stranger.add_friend(&bob); let outbox = Outbox::new(Arc::clone(&stranger.store), wire.clone()); assert_eq!( stranger.send(&outbox, &bob, b"who am i").await, OutboxStatus::Sent ); let frames = wire.take(&bob.pk()); assert_eq!(frames.len(), 1); let err = bob .ingest(&stranger, &frames[0]) .expect_err("no friend row"); assert!(err.contains("unknown friend"), "{err}"); assert!(bob.lines(&stranger).is_empty(), "no chat line"); assert!( bob.ratchet_blob(&stranger).is_none(), "a dropped frame writes no session row" ); // Bob's real conversation is unaffected. let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone()); assert_eq!(alice.send(&to_bob, &bob, b"m0").await, OutboxStatus::Sent); let frames = wire.take(&bob.pk()); assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0"); } #[tokio::test] async fn a_frame_from_a_retired_epoch_is_dropped_and_the_resynced_epoch_works() { let dir = tempfile::tempdir().unwrap(); let (alice, bob, wire) = two_peers(dir.path()); let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone()); let to_alice = Outbox::new(Arc::clone(&bob.store), wire.clone()); // Get both sides off the bootstrap epoch. assert_eq!(alice.send(&to_bob, &bob, b"m0").await, OutboxStatus::Sent); let m0 = wire.take(&bob.pk()).remove(0); assert_eq!(bob.ingest(&alice, &m0).unwrap(), b"m0"); assert_eq!(bob.send(&to_alice, &alice, b"r0").await, OutboxStatus::Sent); let r0 = wire.take(&alice.pk()).remove(0); assert_eq!(alice.ingest(&bob, &r0).unwrap(), b"r0"); // A refreshed invite: Bob's friend row now carries Alice's *new* signed // prekey, and the bootstrap epoch is derived from exactly that prekey — so // `Node::add_friend_payload` drops the stored session on this change. Bob's // side of the old epoch is gone, and the epoch he would now derive is a // different one. let refreshed = Keys::generate(); bob.clear_ratchet(&alice); bob.store .lock() .unwrap() .set_friend_prekey(&alice.pk(), &refreshed.prekey_pk) .expect("refresh the prekey"); let lines_before = bob.lines(&alice); assert_eq!( alice.send(&to_bob, &bob, b"stale").await, OutboxStatus::Sent ); let stale = wire.take(&bob.pk()).remove(0); let err = bob .ingest(&alice, &stale) .expect_err("an epoch derived from a prekey Bob no longer holds"); assert!( err.contains("authentication"), "well-formed, but its keys come from an epoch Bob cannot derive: {err}" ); assert_eq!(bob.lines(&alice), lines_before, "no chat line"); assert!( bob.ratchet_blob(&alice).is_none(), "the rejected frame must not leave a half-built session behind" ); // Recovery is the documented one: the invite is scanned again with the right // prekey and both sides re-derive from it, then keep talking both ways. bob.store .lock() .unwrap() .set_friend_prekey(&alice.pk(), &alice.keys.prekey_pk) .expect("re-scan the invite"); alice.clear_ratchet(&bob); assert_eq!( alice.send(&to_bob, &bob, b"fresh").await, OutboxStatus::Sent ); let fresh = wire.take(&bob.pk()).remove(0); assert_eq!(bob.ingest(&alice, &fresh).unwrap(), b"fresh"); assert_eq!( bob.send(&to_alice, &alice, b"fresh-reply").await, OutboxStatus::Sent ); let reply = wire.take(&alice.pk()).remove(0); assert_eq!(alice.ingest(&bob, &reply).unwrap(), b"fresh-reply"); } #[tokio::test] async fn corrupted_frames_are_dropped_without_touching_the_state() { let dir = tempfile::tempdir().unwrap(); let (alice, bob, wire) = two_peers(dir.path()); let frames = send_n(&alice, &bob, &wire, 2).await; assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0"); let before = bob.ratchet_blob(&alice).expect("bob has a session"); let lines_before = bob.lines(&alice); let good = frames[1].clone(); let mut bad_version = good.clone(); bad_version[4] ^= 0xff; let mut flipped_key = good.clone(); flipped_key[HEADER_OFFSET] ^= 0x01; let mut flipped_n = good.clone(); flipped_n[HEADER_OFFSET + 32 + 3] ^= 0x01; let mut flipped_ct = good.clone(); let last = flipped_ct.len() - 1; flipped_ct[last] ^= 0x01; let cases: [(&str, Vec); 6] = [ ("truncated", good[..good.len() - 1].to_vec()), ("header only", b"rat \x01".to_vec()), ("bad version", bad_version), ("flipped dh_pub", flipped_key), ("flipped N", flipped_n), ("flipped ciphertext", flipped_ct), ]; for (label, frame) in cases { assert!( bob.ingest(&alice, &frame).is_err(), "{label}: must be dropped" ); assert_eq!( bob.lines(&alice), lines_before, "{label}: must log no chat line" ); assert_eq!( bob.ratchet_blob(&alice).expect("session still there"), before, "{label}: must leave the persisted state byte-identical" ); } assert_eq!(bob.ingest(&alice, &good).unwrap(), b"m1"); }