chat: pad plaintext to a normative length ladder
Chat plaintext is padded inside the ratchet AEAD to one of 256/512/1024/2048/4096/8192/16384/32768 bytes, with an explicit big-endian uint16 pad_len followed by the body and random fill. An observer sees only the bucket; the padding is authenticated by ChaCha20-Poly1305 and by the Noise session. The receiver trusts pad_len only, rejects an overrun before appending or persisting anything, and never infers a boundary from trailing bytes. fil chunks are unchanged. docs/PROTOCOL.md gains a normative Length buckets section, THREAT_MODEL replaces the no-padding limit, README notes the bucketed chat length.
This commit is contained in:
parent
c741b660e4
commit
7fa3edcdb4
8 changed files with 517 additions and 11 deletions
|
|
@ -8,6 +8,7 @@ pub mod kem;
|
|||
pub mod loc;
|
||||
pub mod node;
|
||||
pub mod outbox;
|
||||
pub mod padding;
|
||||
pub mod pay;
|
||||
pub mod profile;
|
||||
pub mod qr;
|
||||
|
|
|
|||
241
src/node.rs
241
src/node.rs
|
|
@ -2380,6 +2380,10 @@ fn ratchet_for(store: &Store, keys: &Keys, friend_pk: &[u8]) -> Result<RatchetSt
|
|||
|
||||
/// Encode one chat send as a `rat ` frame, then persist the advanced state.
|
||||
///
|
||||
/// The chat line is padded to a length bucket (`crate::padding`) before the
|
||||
/// ratchet encrypts it, so the padding is authenticated and the frame length
|
||||
/// reveals only the bucket.
|
||||
///
|
||||
/// Exactly one frame per call, and the caller passes those bytes to
|
||||
/// `Outbox::send_payload`, so a retry re-sends them verbatim instead of
|
||||
/// advancing the sending chain a second time.
|
||||
|
|
@ -2393,8 +2397,11 @@ pub fn encode_chat_frame(
|
|||
friend_pk: &[u8],
|
||||
plaintext: &[u8],
|
||||
) -> Result<Vec<u8>, 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(plaintext).map_err(|e| e.to_string())?;
|
||||
let frame = state.encrypt(&padded).map_err(|e| e.to_string())?;
|
||||
let blob = Zeroizing::new(state.to_bytes());
|
||||
store
|
||||
.save_ratchet(friend_pk, &blob)
|
||||
|
|
@ -2410,6 +2417,10 @@ 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.
|
||||
|
|
@ -2420,8 +2431,11 @@ pub fn ingest_chat_frame(
|
|||
frame: &[u8],
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let mut state = ratchet_for(store, keys, peer_pk)?;
|
||||
let plaintext = state.decrypt(frame).map_err(|e| e.to_string())?;
|
||||
let line = Zeroizing::new(sanitize::display_text(&plaintext).as_bytes().to_vec());
|
||||
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());
|
||||
store
|
||||
.append_message(peer_pk, "in", &line[..])
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
|
@ -2926,6 +2940,227 @@ 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<u8> {
|
||||
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");
|
||||
}
|
||||
|
||||
// The ML-KEM ciphertext is a handshake prelude, not part of the `rat `
|
||||
// header: the chat frame still fits the 256-byte bucket.
|
||||
let frame =
|
||||
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"pq").expect("encode");
|
||||
assert_eq!(
|
||||
frame.len(),
|
||||
RAT_OVERHEAD + 256,
|
||||
"the hybrid prelude does not widen the ratchet frame"
|
||||
);
|
||||
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();
|
||||
|
|
|
|||
67
src/padding.rs
Normal file
67
src/padding.rs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
//! 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<usize> {
|
||||
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<Vec<u8>, 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])
|
||||
}
|
||||
Loading…
Reference in a new issue