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
|
|
@ -307,6 +307,10 @@ session carries. Wire format: [docs/PROTOCOL.md](docs/PROTOCOL.md).
|
||||||
about it is transmitted.
|
about it is transmitted.
|
||||||
- **Only chat is ratcheted.** `loc`, `prf`, `inv`, `rcp`, `tip`, `png`, and
|
- **Only chat is ratcheted.** `loc`, `prf`, `inv`, `rcp`, `tip`, `png`, and
|
||||||
`fil` keep the one-shot Noise shape.
|
`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
|
- Out-of-order delivery works (bounded skipped keys: 2000 per chain jump, 2000
|
||||||
stored). A queued chat message re-sends the *same* `rat ` frame.
|
stored). A queued chat message re-sends the *same* `rat ` frame.
|
||||||
- `/wipe` clears chat, payments and outbox but **keeps** ratchet state. `/wipe-all`
|
- `/wipe` clears chat, payments and outbox but **keeps** ratchet state. `/wipe-all`
|
||||||
|
|
|
||||||
|
|
@ -96,6 +96,75 @@ uint8 body[length]
|
||||||
- Other `version` values are a hard fail (close the stream).
|
- 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 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.
|
||||||
|
- The `rat ` frame version stays `0x01`; padding is a plaintext-layer change.
|
||||||
|
|
||||||
|
Minimum observable size: a 256-byte bucket plus the `rat ` frame overhead
|
||||||
|
(`rat ` 4 + version 1 + header 40 + nonce 12 + tag 16 = 73) is a 329-byte
|
||||||
|
ratchet frame; the Noise transport adds its 16-byte tag and the framing header
|
||||||
|
adds 5 bytes, so the **smallest chat frame on the wire is 350 bytes**, whatever
|
||||||
|
the body length. The 32768 bucket is a 32862-byte frame, under the 65535 cap.
|
||||||
|
|
||||||
|
The ML-KEM-768 ciphertext is confined to the one-shot handshake prelude
|
||||||
|
(`version = 2`, 1095 bytes on the wire once per session). It is not part of a
|
||||||
|
`rat ` header: ratchet keys in a chat frame are X25519 (32 bytes), so the
|
||||||
|
hybrid transport does not widen this floor.
|
||||||
|
|
||||||
|
`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
|
## Handshake
|
||||||
|
|
||||||
Noise pattern: `Noise_IK_25519_ChaChaPoly_BLAKE2s`
|
Noise pattern: `Noise_IK_25519_ChaChaPoly_BLAKE2s`
|
||||||
|
|
@ -396,8 +465,9 @@ 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
|
A chat send is ratcheted: the wire form of a chat message is a `rat ` frame
|
||||||
(see “Ratchet (v1 chat layer)”), and the plaintext inside that frame is the chat
|
(see “Ratchet (v1 chat layer)”), and the plaintext inside that frame is the chat
|
||||||
line below. A bare chat frame with no typed prefix is still accepted inbound as
|
line below, padded to a length bucket first (see
|
||||||
a chat line (older peers), but MUST NOT be emitted.
|
[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.
|
||||||
|
|
||||||
UTF-8 is not enforced for chat text: invalid bytes become U+FFFD (the
|
UTF-8 is not enforced for chat text: invalid bytes become U+FFFD (the
|
||||||
implementation does not drop the row). Control and bidi formatting
|
implementation does not drop the row). Control and bidi formatting
|
||||||
|
|
@ -406,7 +476,9 @@ 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
|
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
|
so emoji sequences stay intact. `fil ` filenames must not contain
|
||||||
those characters (tab and newline included). Displayed as a line.
|
those characters (tab and newline included). Displayed as a line.
|
||||||
No length limit beyond the frame cap.
|
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).
|
||||||
|
|
||||||
## Ratchet (v1 chat layer)
|
## Ratchet (v1 chat layer)
|
||||||
|
|
||||||
|
|
@ -441,7 +513,10 @@ ciphertext n+16 ChaCha20-Poly1305 ciphertext || tag
|
||||||
therefore fails closed.
|
therefore fails closed.
|
||||||
- The ChaCha20-Poly1305 key is the message key from `KDF_CK`. The 12-byte nonce
|
- The ChaCha20-Poly1305 key is the message key from `KDF_CK`. The 12-byte nonce
|
||||||
is random per message, not a chain counter.
|
is random per message, not a chain counter.
|
||||||
- Minimum frame (empty plaintext) is 73 bytes: 5 + 40 + 12 + 16.
|
- Minimum *ratchet* frame is 73 bytes: 5 + 40 + 12 + 16. A chat frame is larger
|
||||||
|
because its plaintext is padded to a bucket (see
|
||||||
|
[Length buckets](#length-buckets)); an empty chat line is a 329-byte `rat `
|
||||||
|
frame.
|
||||||
- A receiver MUST reject a frame without the `rat ` prefix, a version other than
|
- A receiver MUST reject a frame without the `rat ` prefix, a version other than
|
||||||
`0x01`, or less than 73 bytes.
|
`0x01`, or less than 73 bytes.
|
||||||
- The frame must fit the Noise body cap (65535 bytes, including the 16-byte
|
- The frame must fit the Noise body cap (65535 bytes, including the 16-byte
|
||||||
|
|
|
||||||
|
|
@ -177,8 +177,14 @@ device.
|
||||||
history. `/wipe` clears chat, payments and outbox rows but **keeps** the
|
history. `/wipe` clears chat, payments and outbox rows but **keeps** the
|
||||||
ratchet state (roster and identity stay), so chat resumes on the same epoch;
|
ratchet state (roster and identity stay), so chat resumes on the same epoch;
|
||||||
`/wipe-all` removes the data dir with it.
|
`/wipe-all` removes the data dir with it.
|
||||||
- *No metadata protection beyond Noise.* One Noise session per message, no
|
- *Length is bucketed; timing is not.* One Noise session per message, and chat
|
||||||
padding: sizes and timing are what they were before the ratchet.
|
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. Non-chat frames
|
||||||
|
(`loc `, `prf `, `inv `, `rcp `, `tip `, `fil `) are not padded and still
|
||||||
|
reveal their own sizes.
|
||||||
- *The ratchet does not re-open the "no server-side outbox" lock.* The state is
|
- *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
|
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
|
is transmitted. The local retry queue's two accepted consequences (device
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ pub mod kem;
|
||||||
pub mod loc;
|
pub mod loc;
|
||||||
pub mod node;
|
pub mod node;
|
||||||
pub mod outbox;
|
pub mod outbox;
|
||||||
|
pub mod padding;
|
||||||
pub mod pay;
|
pub mod pay;
|
||||||
pub mod profile;
|
pub mod profile;
|
||||||
pub mod qr;
|
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.
|
/// 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
|
/// Exactly one frame per call, and the caller passes those bytes to
|
||||||
/// `Outbox::send_payload`, so a retry re-sends them verbatim instead of
|
/// `Outbox::send_payload`, so a retry re-sends them verbatim instead of
|
||||||
/// advancing the sending chain a second time.
|
/// advancing the sending chain a second time.
|
||||||
|
|
@ -2393,8 +2397,11 @@ pub fn encode_chat_frame(
|
||||||
friend_pk: &[u8],
|
friend_pk: &[u8],
|
||||||
plaintext: &[u8],
|
plaintext: &[u8],
|
||||||
) -> Result<Vec<u8>, String> {
|
) -> 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 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());
|
let blob = Zeroizing::new(state.to_bytes());
|
||||||
store
|
store
|
||||||
.save_ratchet(friend_pk, &blob)
|
.save_ratchet(friend_pk, &blob)
|
||||||
|
|
@ -2410,6 +2417,10 @@ pub fn encode_chat_frame(
|
||||||
/// untouched, because `RatchetState` validates fully before it mutates. The
|
/// untouched, because `RatchetState` validates fully before it mutates. The
|
||||||
/// ciphertext is never stored and there is no plaintext fallback.
|
/// 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
|
/// Public for the same reason as [`encode_chat_frame`]. Callers hold the store
|
||||||
/// lock across load → decrypt → append → save, which is what makes the
|
/// lock across load → decrypt → append → save, which is what makes the
|
||||||
/// read-modify-write atomic against a second inbound session on the same peer.
|
/// read-modify-write atomic against a second inbound session on the same peer.
|
||||||
|
|
@ -2420,8 +2431,11 @@ pub fn ingest_chat_frame(
|
||||||
frame: &[u8],
|
frame: &[u8],
|
||||||
) -> Result<Vec<u8>, String> {
|
) -> Result<Vec<u8>, String> {
|
||||||
let mut state = ratchet_for(store, keys, peer_pk)?;
|
let mut state = ratchet_for(store, keys, peer_pk)?;
|
||||||
let plaintext = state.decrypt(frame).map_err(|e| e.to_string())?;
|
let padded = state.decrypt(frame).map_err(|e| e.to_string())?;
|
||||||
let line = Zeroizing::new(sanitize::display_text(&plaintext).as_bytes().to_vec());
|
// `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
|
store
|
||||||
.append_message(peer_pk, "in", &line[..])
|
.append_message(peer_pk, "in", &line[..])
|
||||||
.map_err(|e| e.to_string())?;
|
.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]
|
#[tokio::test]
|
||||||
async fn the_receive_path_keeps_arrival_order_and_drops_replays_and_garbage() {
|
async fn the_receive_path_keeps_arrival_order_and_drops_replays_and_garbage() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
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])
|
||||||
|
}
|
||||||
117
tests/padding.rs
Normal file
117
tests/padding.rs
Normal file
|
|
@ -0,0 +1,117 @@
|
||||||
|
//! 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};
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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);
|
||||||
|
}
|
||||||
|
|
@ -16,6 +16,7 @@ use std::sync::{Arc, Mutex};
|
||||||
use onionwire::Store;
|
use onionwire::Store;
|
||||||
use onionwire::node::{encode_chat_frame, ingest_chat_frame};
|
use onionwire::node::{encode_chat_frame, ingest_chat_frame};
|
||||||
use onionwire::outbox::{BoxFut, Deliverer, Outbox, OutboxStatus};
|
use onionwire::outbox::{BoxFut, Deliverer, Outbox, OutboxStatus};
|
||||||
|
use onionwire::padding;
|
||||||
use onionwire::ratchet::{HEADER_OFFSET, MAX_SKIP, RatchetState};
|
use onionwire::ratchet::{HEADER_OFFSET, MAX_SKIP, RatchetState};
|
||||||
use onionwire::session::Keys;
|
use onionwire::session::Keys;
|
||||||
|
|
||||||
|
|
@ -250,7 +251,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,
|
// What the snapshot can still read: exactly the skipped key it was holding,
|
||||||
// once. Everything it already consumed is gone.
|
// once. Everything it already consumed is gone.
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
snapshot.decrypt(&frames[0]).unwrap(),
|
padding::decode(&snapshot.decrypt(&frames[0]).expect("skipped key")).unwrap(),
|
||||||
b"m0",
|
b"m0",
|
||||||
"a skipped key it legitimately holds"
|
"a skipped key it legitimately holds"
|
||||||
);
|
);
|
||||||
|
|
@ -300,7 +301,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
|
// documented Double Ratchet hop, and it is why the claim below is worded
|
||||||
// about the epoch that requires a secret minted after the compromise.
|
// about the epoch that requires a secret minted after the compromise.
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
snapshot.decrypt(&a3).unwrap(),
|
padding::decode(&snapshot.decrypt(&a3).expect("one hop")).unwrap(),
|
||||||
b"a3",
|
b"a3",
|
||||||
"the epoch built on the key the snapshot already held"
|
"the epoch built on the key the snapshot already held"
|
||||||
);
|
);
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue