diff --git a/README.md b/README.md index 78c1c54..af33957 100644 --- a/README.md +++ b/README.md @@ -307,10 +307,6 @@ session carries. Wire format: [docs/PROTOCOL.md](docs/PROTOCOL.md). about it is transmitted. - **Only chat is ratcheted.** `loc`, `prf`, `inv`, `rcp`, `tip`, `png`, and `fil` keep the one-shot Noise shape. -- **Chat length is bucketed.** The chat line is padded inside the ratchet - ciphertext to one fixed ladder size (256 B to 32 KiB), so the wire shows a - bucket rather than the exact message length. Timing and retry cadence are - still observable; this hides length only. - Out-of-order delivery works (bounded skipped keys: 2000 per chain jump, 2000 stored). A queued chat message re-sends the *same* `rat ` frame. - `/wipe` clears chat, payments and outbox but **keeps** ratchet state. `/wipe-all` diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 72ffd93..b5a82b5 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -96,98 +96,6 @@ uint8 body[length] - Other `version` values are a hard fail (close the stream). - Length that does not match the bytes on the wire is a hard fail. -`length` still reveals the exact ciphertext size. Chat hides it by padding the -plaintext to a bucket before encryption (see [Length buckets](#length-buckets)). -Other frame types are not padded. - -## Length buckets - -Normative for chat. A chat line is padded to one fixed ladder **before** the -ratchet encrypts it, so the padding is inside ChaCha20-Poly1305, inside the -Noise session, and authenticated by both. An observer sees a ciphertext whose -length is one of the ladder values (plus constant overhead), never the body -length. - -Ladder — padded-plaintext sizes in bytes: - -``` -256, 512, 1024, 2048, 4096, 8192, 16384, 32768 -``` - -Ratchet plaintext encoding: - -``` -uint16 pad_len big-endian -uint8 body[..] the chat line -uint8 fill[pad_len] random bytes, contents ignored -``` - -- The padded plaintext MUST be exactly the smallest ladder value that is at - least `2 + body_len`. `pad_len = bucket - 2 - body_len`. -- Empty and short bodies both pad to 256; a 254-byte body fits the 256 bucket - with `pad_len = 0`. -- `fill` is fresh random bytes. Its contents carry no meaning. -- A body larger than 32766 bytes does not fit the ladder and MUST fail closed - (it is a protocol error, never queued). - -Receiver rules: - -- The total decrypted length is **not** required to be a ladder value. Only the - header is normative, so a peer with a different ladder still interoperates. -- `pad_len` is the only authority for the body length. A receiver MUST NOT trim - trailing zeros, strip a repeated fill byte, or otherwise infer the boundary - from content: a body that legitimately ends in the same byte as the fill - round-trips unchanged. -- A plaintext shorter than 2 bytes, or one whose `pad_len` exceeds - `len - 2`, MUST be rejected as a hard failure before anything is appended, - rendered, or persisted. The ratchet state is not advanced. -- Unpadded frames are not accepted as if they were a bucket: if the first two - bytes do not describe a consistent `pad_len`, the frame fails closed. -- Padding is a plaintext-layer change and is independent of the `rat ` frame - version: a classical (`0x01`) and a hybrid (`0x02`) frame carry the same - padded plaintext. See [Ratchet (chat layer)](#ratchet-chat-layer) for the - header each version adds. - -The ladder floor stays at **256** even though a hybrid frame's floor is over -2.6 KB. The ladder schedules the *plaintext*, and a hybrid step's size is -dominated by its 2312-byte header — the 256 bucket is a rounding error there, -so raising the floor would not conceal the header and would only inflate -classical (`0x01`) chat, which is still the epoch-0 and legacy-friend path. A -second, version-specific ladder would double the normative surface for no -privacy gain; the bucket boundaries remain observable within each size class -either way. - -Minimum observable size depends on the `rat ` header version: - -- Classical (`0x01`): `rat ` 4 + version 1 + header 40 + nonce 12 + bucket 256 - + tag 16 = **329-byte `rat ` frame**; the Noise transport adds its 16-byte - tag and the framing header adds 5 bytes, so the smallest classical chat frame - on the wire is **350 bytes**. -- Hybrid (`0x02`): `rat ` 4 + version 1 + header 2312 + nonce 12 + bucket 256 - + tag 16 = **2601-byte `rat ` frame**, i.e. **2622 bytes on the wire**. The - 2272 extra header bytes are the sender's ML-KEM-768 ratchet key and the - ciphertext to the receiver's; the 256-byte bucket applies unchanged inside - them. - -Both floors hold whatever the body length. The 32768 bucket yields a -32862-byte classical frame and a 35113-byte hybrid frame, both under the 65535 -Noise body cap. - -The ML-KEM-768 ciphertext appears in two places: the one-shot handshake prelude -(`version = 2`, 1095 bytes once per session), and every `rat ` header after the -first hybrid ratchet step (`kem_pub[1184] || kem_ct[1088]`). Epoch 0 of a chat -is always classical, so the first `rat ` frame of a friend relationship uses -the 40-byte header. - -`fil ` chunks are deliberately **not** padded. They are raw file bytes paced -through the accept token bucket, and padding them would either cut the usable -chunk size or spend the 65535 frame cap on fill; the chunk size stays as -specified under `fil ` — file chunk. - -This hides length, not timing: one Noise session per message, retry cadence and -circuit timing are unchanged and remain accepted costs (see -`docs/THREAT_MODEL.md`). - ## Handshake Noise pattern: `Noise_IK_25519_ChaChaPoly_BLAKE2s` @@ -488,9 +396,8 @@ is a chat line `[file] name (N bytes)`, never the raw frame. A chat send is ratcheted: the wire form of a chat message is a `rat ` frame (see “Ratchet (chat layer)”), and the plaintext inside that frame is the chat -line below, padded to a length bucket first (see -[Length buckets](#length-buckets)). A bare chat frame with no typed prefix is -still accepted inbound as a chat line (older peers), but MUST NOT be emitted. +line below. A bare chat frame with no typed prefix is still accepted inbound as +a chat line (older peers), but MUST NOT be emitted. UTF-8 is not enforced for chat text: invalid bytes become U+FFFD (the implementation does not drop the row). Control and bidi formatting @@ -499,9 +406,7 @@ tab and newline, DEL (0x7F), C1 U+0080–U+009F, U+202A–U+202E, U+2066–U+2069, U+200E, U+200F, U+200B, U+200C. U+200D (ZWJ) is kept so emoji sequences stay intact. `fil ` filenames must not contain those characters (tab and newline included). Displayed as a line. -A chat line is at most 32766 bytes (the largest bucket minus the 2-byte -`pad_len` header); a longer body is a protocol error, not a queued message. See -[Length buckets](#length-buckets). +No length limit beyond the frame cap. ## Ratchet (chat layer) @@ -549,17 +454,10 @@ ciphertext n+16 ChaCha20-Poly1305 ciphertext || tag therefore fails closed. - The ChaCha20-Poly1305 key is the message key from `KDF_CK`. The 12-byte nonce is random per message, not a chain counter. -- A chat frame's minimum size depends on the header version, not the body: an - empty chat line still pads to the 256-byte bucket. Version `0x01` is 329 - bytes (5 + 40 + 12 + 256 + 16); version `0x02` is 2601 bytes - (5 + 2312 + 12 + 256 + 16). A hybrid message therefore carries 2272 more - header bytes than a classical one. See [Length buckets](#length-buckets). -- On the wire those become 350 bytes for `0x01` (329 + the Noise 16-byte tag + - the 5-byte framing header) and 2622 bytes for `0x02`. The 350-byte floor is - the classical case only. -- A `rat ` frame with no padding at all cannot occur for chat; the bare frame - overhead (empty ciphertext plaintext) is 73 bytes for `0x01` - (5 + 40 + 12 + 16) and 2345 bytes for `0x02` (5 + 2312 + 12 + 16). +- Minimum frame (empty plaintext) is 73 bytes for version `0x01` + (5 + 40 + 12 + 16) and 2345 bytes for version `0x02` + (5 + 2312 + 12 + 16). A hybrid message carries 2272 more header bytes than a + classical one. - A receiver MUST reject a frame without the `rat ` prefix, a version other than `0x01`/`0x02`, or a frame shorter than its version's minimum. - The frame must fit the Noise body cap (65535 bytes, including the 16-byte diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index b618876..b282760 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -208,17 +208,11 @@ device. history. `/wipe` clears chat, payments and outbox rows but **keeps** the ratchet state (roster and identity stay), so chat resumes on the same epoch; `/wipe-all` removes the data dir with it. -- *Length is bucketed; timing is not.* One Noise session per message, and chat - plaintext is padded inside the ratchet ciphertext to a fixed ladder (256 B to - 32 KiB — `docs/PROTOCOL.md`, “Length buckets”), so an observer sees only the - bucket and not the body length. That is all it hides: message timing, retry - cadence, the one-shot-per-message circuits, and the timing of the handshake - are unchanged, and no cover traffic or jitter is generated. The frame header - is not padded: a classical `rat ` frame is 350 bytes at its smallest, while a - hybrid step's 2312-byte ML-KEM header makes its smallest frame 2622 bytes on - the wire. That is a size class, not a message count, and it does not leak the - body length inside the bucket. Non-chat frames (`loc `, `prf `, `inv `, - `rcp `, `tip `, `fil `) are not padded and still reveal their own sizes. +- *No metadata protection beyond Noise.* One Noise session per message, no + padding. Ratchet frame size is visible to the transport layer even though its + contents are not: a hybrid chat frame carries a 2312-byte header instead of + 40, so it is 2272 bytes larger than a classical one. That is a size class, not + a message count; timing is still one session per message. - *The ratchet does not re-open the "no server-side outbox" lock.* The state is device-local, one row per friend in the encrypted store, and nothing about it is transmitted. The local retry queue's two accepted consequences (device diff --git a/src/lib.rs b/src/lib.rs index c80956c..70a7059 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,7 +8,6 @@ pub mod kem; pub mod loc; pub mod node; pub mod outbox; -pub mod padding; pub mod pay; pub mod profile; pub mod qr; diff --git a/src/node.rs b/src/node.rs index 86b6412..13c2ce4 100644 --- a/src/node.rs +++ b/src/node.rs @@ -2407,10 +2407,6 @@ fn ratchet_for(store: &Store, keys: &Keys, friend_pk: &[u8]) -> Result Result, String> { - // Pad to the normative ladder *inside* the AEAD, so an observer sees only - // the bucket and the padding itself is authenticated. - let padded = crate::padding::encode(plaintext)?; let mut state = ratchet_for(store, keys, friend_pk)?; - let frame = state.encrypt(&padded).map_err(|e| e.to_string())?; + let frame = state.encrypt(plaintext).map_err(|e| e.to_string())?; let blob = Zeroizing::new(state.to_bytes()); store .save_ratchet(friend_pk, &blob) @@ -2444,10 +2437,6 @@ pub fn encode_chat_frame( /// untouched, because `RatchetState` validates fully before it mutates. The /// ciphertext is never stored and there is no plaintext fallback. /// -/// The decrypted plaintext is then unpadded by `crate::padding`, whose -/// `uint16 pad_len` is the only authority for the body boundary. A `pad_len` -/// that overruns the buffer fails closed here, before any row is written. -/// /// Public for the same reason as [`encode_chat_frame`]. Callers hold the store /// lock across load → decrypt → append → save, which is what makes the /// read-modify-write atomic against a second inbound session on the same peer. @@ -2458,11 +2447,8 @@ pub fn ingest_chat_frame( frame: &[u8], ) -> Result, String> { let mut state = ratchet_for(store, keys, peer_pk)?; - let padded = state.decrypt(frame).map_err(|e| e.to_string())?; - // `pad_len` is authoritative and never inferred from trailing bytes. An - // overrun fails closed here, before anything is appended or persisted. - let plaintext = crate::padding::decode(&padded)?; - let line = Zeroizing::new(sanitize::display_text(plaintext).as_bytes().to_vec()); + let plaintext = state.decrypt(frame).map_err(|e| e.to_string())?; + let line = Zeroizing::new(sanitize::display_text(&plaintext).as_bytes().to_vec()); store .append_message(peer_pk, "in", &line[..]) .map_err(|e| e.to_string())?; @@ -3064,230 +3050,6 @@ pub(crate) mod tests { ); } - /// A `rat ` frame's fixed overhead: prefix, version, header, nonce, tag. - const RAT_OVERHEAD: usize = 4 + 1 + crate::ratchet::HEADER_LEN + 12 + 16; - - /// One peer→node chat frame plus the stores both sides need. - fn chat_frame(dir: &tempfile::TempDir, node: &Node, peer: &Keys, body: &[u8]) -> Vec { - let peer_store = - Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store"); - befriend( - &peer_store, - &node.identity_pk(), - &node_prekey(node), - "node.onion", - ); - encode_chat_frame(&peer_store, peer, &node.identity_pk(), body).expect("encode") - } - - #[tokio::test] - async fn chat_frames_are_padded_to_the_normative_length_ladder() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); - let peer = Keys::generate(); - befriend( - &node.store.lock().unwrap(), - &peer.identity_pk, - &peer.prekey_pk, - "peer.onion", - ); - - // 1-byte, empty and exactly-bucket-sized bodies all collapse into the - // smallest bucket; 255 bytes is the first body that needs the second. - for body in [&b"x"[..], &b""[..], &vec![b'a'; 254][..]] { - let frame = chat_frame(&dir, &node, &peer, body); - assert_eq!( - frame.len(), - RAT_OVERHEAD + 256, - "a {}-byte body rides in the 256-byte bucket", - body.len() - ); - } - let frame = chat_frame(&dir, &node, &peer, &vec![b'a'; 255]); - assert_eq!( - frame.len(), - RAT_OVERHEAD + 512, - "255 bytes no longer fit the 256-byte bucket" - ); - } - - #[tokio::test] - async fn an_oversize_chat_send_fails_closed_before_the_outbox() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); - let peer = Keys::generate(); - befriend( - &node.store.lock().unwrap(), - &peer.identity_pk, - &peer.prekey_pk, - "peer.onion", - ); - - let body = vec![b'a'; crate::padding::MAX_BODY + 1]; - let err = node - .send(&peer.identity_pk, &body) - .await - .expect_err("a body past the largest bucket is a protocol error"); - assert!(err.contains("too large"), "unexpected error: {err}"); - assert!( - node.outbox_pending(&peer.identity_pk).unwrap().is_empty(), - "a protocol error is never queued" - ); - } - - #[tokio::test] - async fn a_one_byte_chat_round_trips_in_the_smallest_bucket() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); - let peer = Keys::generate(); - befriend( - &node.store.lock().unwrap(), - &peer.identity_pk, - &peer.prekey_pk, - "peer.onion", - ); - - let frame = chat_frame(&dir, &node, &peer, b"x"); - deliver_frame(&node, &peer, &frame, None) - .await - .expect("receive"); - - assert_eq!( - chat_lines(&node, &peer), - vec![("in".to_string(), "x".to_string())], - "one byte in, the same byte out — no padding in history" - ); - } - - #[tokio::test] - async fn a_chat_body_ending_in_the_pad_fill_byte_round_trips() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); - let peer = Keys::generate(); - befriend( - &node.store.lock().unwrap(), - &peer.identity_pk, - &peer.prekey_pk, - "peer.onion", - ); - let peer_store = - Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store"); - befriend( - &peer_store, - &node.identity_pk(), - &node_prekey(&node), - "node.onion", - ); - - // `pad_len` is authoritative, so a body that ends in the same byte as - // the fill is never trimmed: header says two bytes of 'A' fill, the - // body itself ends in an 'A'. - let mut padded = vec![0x00, 0x02]; - padded.extend_from_slice(b"tailA"); - padded.extend_from_slice(b"AA"); - let mut state = ratchet_for(&peer_store, &peer, &node.identity_pk()).expect("state"); - let frame = state.encrypt(&padded).expect("encrypt"); - - deliver_frame(&node, &peer, &frame, None) - .await - .expect("receive"); - - let lines = chat_lines(&node, &peer); - assert_eq!(lines.len(), 1); - assert_eq!(lines[0].1, "tailA"); - } - - #[tokio::test] - async fn a_pad_len_that_overruns_the_plaintext_writes_no_chat_row() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); - let peer = Keys::generate(); - befriend( - &node.store.lock().unwrap(), - &peer.identity_pk, - &peer.prekey_pk, - "peer.onion", - ); - let peer_store = - Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store"); - befriend( - &peer_store, - &node.identity_pk(), - &node_prekey(&node), - "node.onion", - ); - - // A *validly authenticated* frame whose pad_len claims more fill than - // the plaintext holds: the AEAD cannot catch this, the padding layer - // must, and it must fail before a row is appended. - let mut state = ratchet_for(&peer_store, &peer, &node.identity_pk()).expect("state"); - let bad = state.encrypt(&[0xff, 0xff, b'h', b'i']).expect("encrypt"); - - let store = node.store.lock().unwrap(); - let keys = node.keys.lock().unwrap(); - let err = ingest_chat_frame(&store, &keys, &peer.identity_pk, &bad) - .expect_err("an overrunning pad_len must fail closed"); - assert!(err.contains("overrun"), "unexpected error: {err}"); - drop(keys); - drop(store); - - assert!( - chat_lines(&node, &peer).is_empty(), - "no partial plaintext may be rendered or stored" - ); - } - - #[tokio::test] - async fn a_hybrid_rat_frame_round_trips_inside_the_smallest_bucket() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); - let peer = Keys::generate(); - { - let store = node.store.lock().unwrap(); - befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion"); - store - .set_friend_kem(&peer.identity_pk, Some(&peer.kem_pk)) - .expect("friend kem"); - } - let peer_store = - Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store"); - { - let nk = node_kem_pk(&node); - befriend( - &peer_store, - &node.identity_pk(), - &node_prekey(&node), - "node.onion", - ); - peer_store - .set_friend_kem(&node.identity_pk(), Some(&nk)) - .expect("node kem"); - } - - // Epoch 0 is always classical, even for a KEM friend: the first `rat ` - // frame carries the 40-byte header and the PQ prelude lives in the - // one-shot handshake. The 2312-byte hybrid header only appears on the - // first rotation (`tests/padding.rs` pins that 2601-byte floor). - let frame = - encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"pq").expect("encode"); - assert_eq!(frame[4], crate::ratchet::FRAME_VERSION); - assert_eq!( - frame.len(), - RAT_OVERHEAD + 256, - "epoch 0 is classical, so the hybrid prelude does not widen it" - ); - let nk = node_kem_pk(&node); - deliver_frame(&node, &peer, &frame, Some(&nk)) - .await - .expect("PQ handshake + rat frame"); - - assert_eq!( - chat_lines(&node, &peer), - vec![("in".to_string(), "pq".to_string())], - "a padded rat frame survives the PQ prelude" - ); - } - #[tokio::test] async fn the_receive_path_keeps_arrival_order_and_drops_replays_and_garbage() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/padding.rs b/src/padding.rs deleted file mode 100644 index 4b6e15f..0000000 --- a/src/padding.rs +++ /dev/null @@ -1,67 +0,0 @@ -//! Length buckets for chat plaintext. Normative spec: `docs/PROTOCOL.md`, -//! “Length buckets”. -//! -//! Chat bodies are padded to one of eight sizes *before* the ratchet encrypts -//! them, so the padding is authenticated by ChaCha20-Poly1305 and by the Noise -//! session around it. An observer sees only the bucket. The encoding is -//! explicit and never trimmed: -//! -//! ```text -//! uint16 pad_len = big-endian length of the random fill that follows -//! uint8 body[..] = the chat line -//! uint8 fill[pad_len] = random bytes -//! ``` -//! -//! The padded plaintext is exactly `bucket_for(body.len())` bytes, so -//! `pad_len = bucket - 2 - body.len()`. A receiver accepts any total length (a -//! peer implementation may use another ladder) but requires a consistent -//! `pad_len`; an overrun fails closed instead of rendering a partial body. - -use rand::RngCore; -use rand::rngs::OsRng; - -/// The explicit padding header: `uint16 pad_len`. -pub const PAD_HEADER_LEN: usize = 2; - -/// The one ladder. Sizes are padded-plaintext lengths, not frame lengths. -pub const BUCKETS: [usize; 8] = [256, 512, 1024, 2048, 4096, 8192, 16384, 32768]; - -/// The largest body that fits the largest bucket (`32768 - 2`). -pub const MAX_BODY: usize = BUCKETS[BUCKETS.len() - 1] - PAD_HEADER_LEN; - -/// The ladder value a body of `body_len` bytes is padded to, or `None` when it -/// does not fit the largest bucket. -pub fn bucket_for(body_len: usize) -> Option { - BUCKETS - .iter() - .copied() - .find(|bucket| bucket - PAD_HEADER_LEN >= body_len) -} - -/// `uint16 pad_len || body || random fill`, sized to one ladder value. -pub fn encode(body: &[u8]) -> Result, String> { - let bucket = bucket_for(body.len()).ok_or_else(|| { - format!("chat message too large for the largest length bucket ({MAX_BODY} bytes)") - })?; - let pad_len = bucket - PAD_HEADER_LEN - body.len(); - let mut out = Vec::with_capacity(bucket); - out.extend_from_slice(&(pad_len as u16).to_be_bytes()); - out.extend_from_slice(body); - out.resize(bucket, 0); - OsRng.fill_bytes(&mut out[PAD_HEADER_LEN + body.len()..]); - Ok(out) -} - -/// Strip the padding. Total length is not checked against the ladder on -/// purpose; only the header and its bound are normative. -pub fn decode(padded: &[u8]) -> Result<&[u8], String> { - let header = padded - .get(..PAD_HEADER_LEN) - .ok_or("chat padding: no pad_len header")?; - let pad_len = u16::from_be_bytes([header[0], header[1]]) as usize; - let body_len = padded - .len() - .checked_sub(PAD_HEADER_LEN + pad_len) - .ok_or("chat padding: pad_len overruns the plaintext")?; - Ok(&padded[PAD_HEADER_LEN..PAD_HEADER_LEN + body_len]) -} diff --git a/tests/padding.rs b/tests/padding.rs deleted file mode 100644 index c9464a9..0000000 --- a/tests/padding.rs +++ /dev/null @@ -1,234 +0,0 @@ -//! Normative chat length buckets: the ladder, the plaintext encoding, and the -//! receiver's bounds. The wire behaviour these prove (a `rat ` frame of a -//! bucketed size, a tampered field failing closed) lives in `src/node.rs`'s -//! unit tests, because `tests/*.rs` cannot build a `Node`. - -use onionwire::padding::{self, BUCKETS, MAX_BODY, PAD_HEADER_LEN}; -use onionwire::ratchet::{ - FRAME_VERSION, FRAME_VERSION_HYBRID, HEADER_LEN, HEADER_LEN_HYBRID, RatchetKeyPair, - RatchetState, -}; - -const ROOT: [u8; 32] = [0x7au8; 32]; - -#[test] -fn the_ladder_is_the_documented_one() { - assert_eq!(BUCKETS, [256, 512, 1024, 2048, 4096, 8192, 16384, 32768]); - assert_eq!(PAD_HEADER_LEN, 2); - assert_eq!(MAX_BODY, 32766); -} - -#[test] -fn buckets_follow_the_body_plus_the_two_byte_header() { - let cases = [ - (0, Some(256)), - (1, Some(256)), - (253, Some(256)), - (254, Some(256)), - (255, Some(512)), - (510, Some(512)), - (511, Some(1024)), - (1022, Some(1024)), - (1023, Some(2048)), - (2046, Some(2048)), - (2047, Some(4096)), - (4094, Some(4096)), - (4095, Some(8192)), - (8190, Some(8192)), - (8191, Some(16384)), - (16382, Some(16384)), - (16383, Some(32768)), - (32766, Some(32768)), - (32767, None), - (65535, None), - ]; - for (body_len, want) in cases { - assert_eq!( - padding::bucket_for(body_len), - want, - "bucket for a {body_len}-byte body" - ); - } -} - -#[test] -fn a_one_byte_message_round_trips_in_the_smallest_bucket() { - let padded = padding::encode(b"x").expect("encode"); - assert_eq!(padded.len(), 256); - assert_eq!(padding::decode(&padded).expect("decode"), b"x"); -} - -#[test] -fn an_empty_message_round_trips_in_the_smallest_bucket() { - let padded = padding::encode(b"").expect("encode"); - assert_eq!(padded.len(), 256); - assert_eq!(padding::decode(&padded).expect("decode"), b""); -} - -#[test] -fn an_exactly_bucket_sized_message_round_trips_with_no_pad() { - let body = vec![b'a'; 254]; - let padded = padding::encode(&body).expect("encode"); - assert_eq!(padded.len(), 256); - assert_eq!(&padded[..2], &[0u8, 0u8], "pad_len is zero at an exact fit"); - assert_eq!(padding::decode(&padded).expect("decode"), &body[..]); -} - -#[test] -fn an_oversize_message_fails_closed() { - let err = padding::encode(&vec![b'a'; MAX_BODY + 1]).expect_err("must not fit a bucket"); - assert!(err.contains("too large"), "{err}"); -} - -#[test] -fn a_body_ending_in_the_pad_fill_byte_round_trips() { - // Hand-built: `pad_len` is authoritative, so trailing bytes are never - // trimmed and a body that ends in the same value as the fill survives. - // The total is deliberately not a ladder value: receivers accept any size. - let mut padded = Vec::new(); - padded.extend_from_slice(&3u16.to_be_bytes()); - padded.extend_from_slice(b"body\xaa"); - padded.extend_from_slice(&[0xaa; 3]); - assert_eq!(padded.len(), 2 + 5 + 3); - assert_eq!(padding::decode(&padded).expect("decode"), b"body\xaa"); -} - -#[test] -fn a_pad_len_that_overruns_the_plaintext_is_rejected() { - // 16 bytes total, pad_len says 15: one byte of body plus header is already - // 3, so it overruns by 1. - let mut bad = Vec::new(); - bad.extend_from_slice(&15u16.to_be_bytes()); - bad.extend_from_slice(&[0u8; 14]); - let err = padding::decode(&bad).expect_err("must fail closed"); - assert!(err.contains("overrun"), "{err}"); -} - -#[test] -fn a_truncated_padding_header_is_rejected() { - assert!(padding::decode(b"").is_err()); - assert!(padding::decode(b"\x00").is_err()); -} - -/// Two hybrid peers from one bootstrap root. `a` holds the lower ratchet key, -/// so the documented tie-break (`a` rotates first) is deterministic instead of -/// a coin flip per run. -fn hybrid_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()); - ( - RatchetState::bootstrap(ROOT, lo, hi_pub, Some(&hi_kem)), - RatchetState::bootstrap(ROOT, hi, lo_pub, Some(&lo_kem)), - ) -} - -/// Burn the bootstrap epoch so the next `a` send is its first hybrid step. -fn hybrid_step() -> (RatchetState, RatchetState) { - let (mut a, mut b) = hybrid_peers(); - let a1 = a.encrypt(b"bootstrap").expect("encrypt"); - let b1 = b.encrypt(b"bootstrap").expect("encrypt"); - assert_eq!(b.decrypt(&a1).expect("b bootstrap"), b"bootstrap"); - assert_eq!(a.decrypt(&b1).expect("a bootstrap"), b"bootstrap"); - (a, b) -} - -/// Padding sits *inside* the AEAD, so the bucket is unchanged by the header -/// version; the header sits outside it, so a hybrid step adds 2272 bytes to -/// the same padded plaintext. This is the true hybrid floor: 2601 in Noise -/// (2622 on the wire), against 329 (350) for the classical case. -#[test] -fn a_padded_plaintext_rides_inside_a_hybrid_header() { - let (mut a, mut b) = hybrid_step(); - let padded = padding::encode(b"pq").expect("encode"); - assert_eq!(padded.len(), 256, "a short body still pads to the floor"); - - let frame = a.encrypt(&padded).expect("encrypt"); - assert_eq!( - frame[4], FRAME_VERSION_HYBRID, - "the first rotation is a hybrid step" - ); - assert_eq!( - frame.len(), - 4 + 1 + HEADER_LEN_HYBRID + 12 + 256 + 16, - "hybrid rat frame" - ); - assert_eq!(frame.len(), 2601); - // The Noise transport adds its 16-byte tag and the framing header 5 bytes. - assert_eq!(frame.len() + 16 + 5, 2622, "hybrid frame on the wire"); - assert_eq!( - HEADER_LEN_HYBRID - HEADER_LEN, - 2272, - "a hybrid step's header is 2272 bytes larger" - ); - - assert_eq!( - padding::decode(&b.decrypt(&frame).expect("decrypt")).expect("decode"), - b"pq" - ); -} - -/// The ceiling: largest bucket (32768) plus the 2312-byte hybrid header plus -/// the frame's fixed overhead still fits one Noise body. -#[test] -fn the_largest_bucket_still_fits_inside_a_hybrid_frame() { - let (mut a, mut b) = hybrid_step(); - let body = vec![b'a'; MAX_BODY]; - let padded = padding::encode(&body).expect("encode"); - assert_eq!(padded.len(), 32768); - - let frame = a.encrypt(&padded).expect("encrypt"); - assert_eq!(frame[4], FRAME_VERSION_HYBRID); - assert_eq!(frame.len(), 4 + 1 + HEADER_LEN_HYBRID + 12 + 32768 + 16); - assert_eq!(frame.len(), 35113, "largest hybrid rat frame"); - assert!( - frame.len() + 16 <= onionwire::frame::MAX_FRAME, - "a hybrid frame must fit one Noise body" - ); - assert!(frame.len() <= 65519, "documented rat frame maximum"); - - assert_eq!( - padding::decode(&b.decrypt(&frame).expect("decrypt")) - .expect("decode") - .len(), - MAX_BODY - ); -} - -/// A classical friend's floor is unchanged by the hybrid work: 329 in Noise. -#[test] -fn a_classical_frame_keeps_the_329_byte_floor() { - let padded = padding::encode(b"").expect("encode"); - 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 hi_pub = hi.public(); - let mut a = RatchetState::bootstrap(ROOT, lo, hi_pub, None); - let frame = a.encrypt(&padded).expect("encrypt"); - assert_eq!(frame[4], FRAME_VERSION, "classical friend, classical frame"); - assert_eq!(frame.len(), 4 + 1 + HEADER_LEN + 12 + 256 + 16); - assert_eq!(frame.len(), 329); - assert_eq!(frame.len() + 16 + 5, 350, "classical frame on the wire"); -} - -#[test] -fn a_receiver_accepts_a_padded_plaintext_of_any_total_length() { - // Interop: another implementation's ladder is not ours, and the receiver - // must not require a bucket-sized total, only a consistent pad_len. - let mut padded = Vec::new(); - padded.extend_from_slice(&30u16.to_be_bytes()); - padded.extend_from_slice(&[b'z'; 268]); - padded.extend_from_slice(&[0u8; 30]); - assert_eq!(padded.len(), 300); - assert_eq!(padding::decode(&padded).expect("decode").len(), 268); -} diff --git a/tests/ratchet_adversarial.rs b/tests/ratchet_adversarial.rs index cad6102..c8927fa 100644 --- a/tests/ratchet_adversarial.rs +++ b/tests/ratchet_adversarial.rs @@ -16,7 +16,6 @@ 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::padding; use onionwire::ratchet::{HEADER_OFFSET, MAX_SKIP, RatchetState}; use onionwire::session::Keys; @@ -251,7 +250,7 @@ async fn a_snapshot_heals_only_once_the_ratchet_key_it_held_has_been_replaced() // What the snapshot can still read: exactly the skipped key it was holding, // once. Everything it already consumed is gone. assert_eq!( - padding::decode(&snapshot.decrypt(&frames[0]).expect("skipped key")).unwrap(), + snapshot.decrypt(&frames[0]).unwrap(), b"m0", "a skipped key it legitimately holds" ); @@ -301,7 +300,7 @@ async fn a_snapshot_heals_only_once_the_ratchet_key_it_held_has_been_replaced() // 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!( - padding::decode(&snapshot.decrypt(&a3).expect("one hop")).unwrap(), + snapshot.decrypt(&a3).unwrap(), b"a3", "the epoch built on the key the snapshot already held" );