Skip to content

fix(core): authenticate envelope headers and persist replay state - #27

Draft
Jeon1691 wants to merge 1 commit into
masterfrom
Jeon1691/sec-envelope-auth-replay
Draft

Jeon1691 wants to merge 1 commit into
masterfrom
Jeon1691/sec-envelope-auth-replay

Conversation

@Jeon1691

Copy link
Copy Markdown
Owner

Problem

Text AEAD associated data was only "{message_id}:text", manifests used "{transfer_id}:manifest", and chunks used transfer_id || index. The routing header fields room_id, sender_device_id, recipient, sent_at, expires_at, item_kind and seq were not authenticated. Receivers never checked expires_at. Replay protection was the in-memory LoopGuard message-ID cache: 120 s TTL, empty after every restart. docs/security.md lists replay as an in-scope threat, and it implied protections that Noise and sender IDs do not provide.

Attack scenario

A relay operator records a text envelope (or a manifest and its chunks) and re-sends it more than 120 s later or after the receiving daemon restarts. The receiver decrypts it and overwrites the user's clipboard with stale content. The relay can also extend expires_at or rewrite sender/recipient/room metadata, and the receiver still accepts the envelope.

Resulting behavior

  • Envelope v2 (RoutingHeader.version = 2): the AAD is a canonical, length-prefixed encoding of the whole routing header plus a frame tag. It is used for text, manifest and every chunk. Chunks are bound to the accepted manifest's header, index and count. The encoding is specified in docs/protocol.md.
  • Receiver checks (both versions): room, recipient, sender must be a pinned peer of the room and not the receiver, item kind, sent_at/expires_at with a named CLOCK_SKEW_SECS = 30 s, lifetime ≤ HARD_MAX_TTL_SECS.
  • Restart-proof replay protection: per room and sender, the highest accepted v2 seq is stored in the private replay-state.json (0600, atomic write). It is committed only after AEAD succeeds, so forged headers cannot raise it. Sender seq = max(last_sent + 1, unix_micros) is persisted before sending, so it stays monotonic across restarts, clock steps back, lost state, and concurrent daemon/one-shot sends.
  • One Inbound entry point covers the daemon loop, the hello_ok queued text, and pull. The mobile path uses the same engine.

Compatibility impact

  • hello.protocol_version stays 1; the relay is unchanged and forwards v2 headers as is. The chunk frame layout and its version byte are unchanged.
  • Updated receivers always accept v2. They accept legacy v1 from a sender only until that sender's first accepted v2 envelope; the state is persisted, and later v1 from that sender is rejected as a downgrade. v1 still gets the header checks, but on unauthenticated values, and only the in-memory replay cache.
  • Clients from before this change cannot decrypt v2. During a staggered upgrade, sync.legacy_envelopes = true (new, default false) makes an updated device send v1 to a not-yet-updated peer. Receiving is unaffected.
  • Persisted formats: new config key and new state file, both with serde defaults; existing files load unchanged. Pairing is untouched.

Verification

  • Regression tests were written first. On unchanged code all three failed: replay after restart (left: "2" right: "1"), expired/misaddressed envelopes ("4" vs "1"), and a relay-rewritten header accepted ("2" vs "1"). They pass with the fix.
  • New tests:
    • every routing field tampered fails decryption for text, manifest and chunks; chunk reorder and recount fail;
    • expired, future, over-long, wrong-room/recipient/kind and unpinned-sender envelopes are rejected;
    • a replay is rejected without the in-memory cache and after reopening the store;
    • v1 is accepted from a not-yet-upgraded sender and rejected as a downgrade after its first v2, also across reopen;
    • the sender emits v2 by default, which v1 AAD cannot open, and v1 with sync.legacy_envelopes;
    • replay-state defaults, corruption failing closed, and private file mode.
  • cargo +1.100.0 fmt --all -- --check: pass.
  • cargo +1.100.0 clippy --workspace --all-targets --locked -- -D warnings: pass.
  • cargo +1.100.0 test --locked: protocol, transfer, storage, core (62 lib tests), mobile and relay all pass. One relay test, secure_listener::verified_https_keeps_certificate_and_private_key_symlink_support, failed once during the parallel full run; this PR does not touch the relay, and it passed 3/3 reruns.
  • cargo +1.95.0 check --workspace --all-targets --locked: pass.
  • The fuzz target now also derives AAD from decoded headers, and a v2 text-envelope seed was added. cargo +nightly fuzz build protocol passes, and a 30 s run found no crashes.
  • scripts/check-source-headers.py and scripts/check-regressions.py pass.

Remaining limitations

  • Sender identity is not cryptographically bound per device: every room member holds the epoch key. v2 only stops the relay from changing the claimed sender. No per-device signature is added.
  • The Noise KK handshake result is still unused for payloads. The docs now say so.
  • Before a sender's first v2 envelope, v1 replay and expiry extension remain possible, as today.
  • Acceptance is strictly increasing per sender, so an older item that arrives after a newer one is dropped. The daemon and one-shot processes do not share a file lock.
  • A malicious relay can still drop or delay envelopes within their lifetime.
  • Deleting replay-state.json limits protection to the expiry window until each sender's next accepted envelope.

Text, manifest and chunk AAD covered only the message or transfer ID, so a
relay could rewrite room, sender, recipient, timestamps, item kind or seq,
extend expiry, and replay old envelopes once the 120 s in-memory cache
expired or the daemon restarted.

Envelope v2 (RoutingHeader.version = 2) authenticates a canonical encoding
of the full routing header for every frame; chunks are bound to the
accepted manifest's header, index and count. Receivers reject envelopes for
another room or recipient, from unpinned senders, outside the expiry window
(30 s skew), or with a seq not newer than the last accepted v2 seq of that
sender. Sender seq and receiver high-water marks persist in the private
replay-state.json, so protection survives restarts.

Hello stays at protocol version 1 for relay compatibility. Updated
receivers accept legacy v1 from a sender until its first v2 envelope and
reject it afterwards as a downgrade; sync.legacy_envelopes lets an updated
device keep sending v1 to a not-yet-updated peer. Docs now state that the
Noise handshake result is unused and sender identity is not bound per
device.
@coderabbitai

coderabbitai Bot commented Nov 16, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

if frame.ciphertext.len() < AEAD_NONCE_LEN {
return Err(TransferError::Chunk("ciphertext too short"));
}
let mut nonce = [0u8; AEAD_NONCE_LEN];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants