From e38472869c5e4d6ffd548b69ae5d43137e7a11f2 Mon Sep 17 00:00:00 2001 From: develicit <16333003+Jeon1691@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:27:11 +0900 Subject: [PATCH] fix(core): authenticate envelope headers and persist replay state 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. --- Cargo.lock | 1 + crates/clipsync-core/src/engine.rs | 252 +++++++-- crates/clipsync-core/src/envelope.rs | 154 ++++++ crates/clipsync-core/src/error.rs | 2 + crates/clipsync-core/src/lib.rs | 2 + .../tests/support/engine_behavior.rs | 127 +++-- .../tests/support/engine_coverage.rs | 47 +- .../tests/support/envelope_security.rs | 502 ++++++++++++++++++ crates/clipsync-protocol/src/envelope.rs | 214 ++++++++ crates/clipsync-protocol/src/lib.rs | 8 + crates/clipsync-protocol/src/limits.rs | 7 +- crates/clipsync-storage/src/config.rs | 10 + crates/clipsync-storage/src/lib.rs | 2 + crates/clipsync-storage/src/paths.rs | 5 + crates/clipsync-storage/src/replay.rs | 237 +++++++++ .../clipsync-storage/tests/config_contract.rs | 4 + crates/clipsync-transfer/Cargo.toml | 1 + crates/clipsync-transfer/src/lib.rs | 200 +++++-- docs/interfaces.md | 6 +- docs/protocol.md | 100 +++- docs/security.md | 50 +- fuzz/fuzz_targets/protocol.rs | 36 +- fuzz/seeds/protocol/text-envelope-v2.json | 1 + 23 files changed, 1811 insertions(+), 157 deletions(-) create mode 100644 crates/clipsync-core/src/envelope.rs create mode 100644 crates/clipsync-core/tests/support/envelope_security.rs create mode 100644 crates/clipsync-protocol/src/envelope.rs create mode 100644 crates/clipsync-storage/src/replay.rs create mode 100644 fuzz/seeds/protocol/text-envelope-v2.json diff --git a/Cargo.lock b/Cargo.lock index 63d4e5d..556ed7e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1180,6 +1180,7 @@ name = "clipsync-transfer" version = "0.2.0" dependencies = [ "blake3", + "chrono", "clipsync-crypto", "clipsync-protocol", "tempfile", diff --git a/crates/clipsync-core/src/engine.rs b/crates/clipsync-core/src/engine.rs index ff00b25..380c7af 100644 --- a/crates/clipsync-core/src/engine.rs +++ b/crates/clipsync-core/src/engine.rs @@ -20,15 +20,21 @@ use clipsync_daemon::{ StatusPayload, }; use clipsync_protocol::{ - AckStatus, ClientRole, ControlMessage, FileManifest, ImageManifest, ItemKind, ManifestPlain, - MessageId, Recipient, RoutingHeader, TransferId, PROTOCOL_VERSION, + decode_chunk_frame, envelope_aad, AckStatus, ClientRole, ControlMessage, DeviceId, + EnvelopeFrame, FileManifest, ImageManifest, ItemKind, ManifestPlain, MessageId, Recipient, + RoutingHeader, TransferId, PROTOCOL_VERSION, }; -use clipsync_storage::{LocalStore, RoomRecord}; +use clipsync_storage::{AppConfig, LocalStore, RoomRecord}; use clipsync_transfer::{ - decrypt_chunk, prune_idle_transfers, split_and_encrypt, IncomingTransfer, StagingArea, + open_chunk, prune_idle_transfers, split_and_encrypt, IncomingTransfer, StagingArea, + TransferError, }; use clipsync_transport::{backoff_delay, http_to_ws, join_ws, Incoming, RelayConnection}; +use crate::envelope::{ + check_header, check_version, commit_sequence, sending_version, sequence_floor, + EnvelopeRejection, +}; use crate::loop_guard::LoopGuard; use crate::notify::Notifier; use crate::{current_os, device_name, CoreError, PullResult}; @@ -99,9 +105,12 @@ pub async fn run_daemon(clipboard: Option) -> Result<(), CoreEr Ok(()) } +/// A manifest accepted by [`Inbound::manifest`], kept until its chunks arrive. +type PendingManifest = (RoutingHeader, ManifestPlain); + fn drop_idle_transfers( incoming: &mut std::collections::HashMap, - manifests: &mut std::collections::HashMap, + manifests: &mut std::collections::HashMap, ) { let ttl = std::time::Duration::from_secs(clipsync_protocol::TRANSFER_IDLE_SECS); let _ = prune_idle_transfers(incoming, std::time::Instant::now(), ttl); @@ -265,8 +274,13 @@ async fn run_session( let staging = StagingArea::new(store.paths.inbox_dir.clone())?; let mut last_sig = clipboard.signature().await.unwrap_or_else(|_| "0".into()); let mut incoming: HashMap = HashMap::new(); - let mut manifests: HashMap = HashMap::new(); - let mut seq = 0u64; + let mut manifests: HashMap = HashMap::new(); + let inbound = Inbound { + store, + room: &room, + local: &identity.device_id, + epoch_key: &epoch_key, + }; let mut noise: Option = None; let mut noise_done = false; handle.connected.store(true, Ordering::Relaxed); @@ -274,7 +288,7 @@ async fn run_session( &hello, &identity, &room, - &epoch_key, + &inbound, clipboard, &mut guard, handle, @@ -315,8 +329,14 @@ async fn run_session( warn!(error = %e, "skip invalid clipboard item"); continue; } - seq += 1; - if let Err(e) = send_item(&conn, &identity, &room, &epoch_key, seq, &item).await { + let stamp = match EnvelopeStamp::next(store, &room, &cfg) { + Ok(stamp) => stamp, + Err(e) => { + warn!(error = %e, "cannot reserve envelope sequence"); + return Err(e); + } + }; + if let Err(e) = send_item(&conn, &identity, &room, &epoch_key, stamp, &item).await { warn!(error = %e, "send failed; reconnecting"); return Err(e); } @@ -333,7 +353,7 @@ async fn run_session( Incoming::Control(ControlMessage::HelloOk { peer_online, queued_text, peers, .. }) => { handle.peer_online.store(peer_online, Ordering::Relaxed); if let Some(q) = queued_text { - if let Ok(item) = open_text(&epoch_key, &q.routing, &q.nonce, &q.ciphertext) { + if let Ok(item) = inbound.text(&q.routing, &q.nonce, &q.ciphertext) { apply_remote(clipboard, &mut guard, handle, ¬ifier, &q.routing.message_id.0, item, &mut last_sig).await; } } @@ -395,7 +415,7 @@ async fn run_session( if guard.seen_message(routing.message_id.as_str()) { continue; } - match open_text(&epoch_key, &routing, &nonce, &ciphertext) { + match inbound.text(&routing, &nonce, &ciphertext) { Ok(item) => { apply_remote(clipboard, &mut guard, handle, ¬ifier, routing.message_id.as_str(), item, &mut last_sig).await; let _ = conn.send_control(ControlMessage::Ack { @@ -405,19 +425,19 @@ async fn run_session( detail: None, }).await; } - Err(e) => warn!(error = %e, "text decrypt"), + Err(e) => warn!(error = %e, "text envelope rejected"), } } Incoming::Control(ControlMessage::Manifest { routing, nonce, ciphertext, .. }) => { drop_idle_transfers(&mut incoming, &mut manifests); - match open_manifest(&epoch_key, &routing, &nonce, &ciphertext) { + match inbound.manifest(&routing, &nonce, &ciphertext) { Ok(manifest) => { let id = routing.transfer_id.clone(); let t = staging.begin(&id, manifest.chunk_count); incoming.insert(id.0.clone(), t); - manifests.insert(id.0, manifest); + manifests.insert(id.0, (routing, manifest)); } - Err(e) => warn!(error = %e, "manifest"), + Err(e) => warn!(error = %e, "manifest rejected"), } } Incoming::Control(ControlMessage::Ack { status, .. }) => { @@ -428,7 +448,7 @@ async fn run_session( } Incoming::Binary(buf) => { drop_idle_transfers(&mut incoming, &mut manifests); - match decrypt_chunk(&epoch_key, &buf) { + match open_pending_chunk(&epoch_key, &manifests, &buf) { Ok((tid, idx, count, pt)) => { if let Some(t) = incoming.get_mut(tid.as_str()) { if t.push(idx, count, pt).is_err() { @@ -436,7 +456,7 @@ async fn run_session( continue; } if t.is_complete() { - if let Some(man) = manifests.remove(tid.as_str()) { + if let Some((_, man)) = manifests.remove(tid.as_str()) { if let Some(xfer) = incoming.remove(tid.as_str()) { match xfer.assemble(&man.content_hash) { Ok(payload) => { @@ -471,7 +491,7 @@ async fn send_item( identity: &DeviceIdentity, room: &RoomRecord, epoch_key: &[u8; 32], - seq: u64, + stamp: EnvelopeStamp, item: &ClipboardItem, ) -> Result<(), CoreError> { let transfer_id = TransferId::new(); @@ -479,7 +499,7 @@ async fn send_item( let now = Utc::now(); let ttl = ChronoDuration::seconds(clipsync_protocol::DEFAULT_TTL_SECS as i64); let routing = RoutingHeader { - version: PROTOCOL_VERSION, + version: stamp.version, message_id, transfer_id: transfer_id.clone(), room_id: room.room_id.clone(), @@ -488,18 +508,15 @@ async fn send_item( sent_at: now, expires_at: now + ttl, item_kind: item.kind(), - seq, + seq: stamp.seq, }; match item { ClipboardItem::Text { text } => { - let content_key = derive_content_key(epoch_key, transfer_id.as_str())?; - let nonce = derive_nonce(&content_key, 0)?; - let aad = format!("{}:text", routing.message_id); - let ct = seal(&content_key, &nonce, aad.as_bytes(), text.as_bytes())?; + let (nonce, ciphertext) = seal_text(epoch_key, &routing, text)?; conn.send_control(ControlMessage::TextEnvelope { routing, - nonce: hex::encode(nonce), - ciphertext: hex::encode(ct), + nonce, + ciphertext, }) .await?; } @@ -566,18 +583,14 @@ async fn send_binary( mut manifest: ManifestPlain, payload: &[u8], ) -> Result<(), CoreError> { - let chunks = split_and_encrypt(epoch_key, &routing.transfer_id, payload)?; + let chunks = split_and_encrypt(epoch_key, &routing, payload)?; manifest.chunk_count = chunks.chunk_count; manifest.total_bytes = chunks.total_bytes; - let content_key = derive_content_key(epoch_key, routing.transfer_id.as_str())?; - let nonce = derive_nonce(&content_key, u32::MAX)?; - let aad = format!("{}:manifest", routing.transfer_id); - let pt = serde_json::to_vec(&manifest)?; - let ct = seal(&content_key, &nonce, aad.as_bytes(), &pt)?; + let (nonce, ciphertext) = seal_manifest(epoch_key, &routing, &manifest)?; conn.send_control(ControlMessage::Manifest { routing: routing.clone(), - nonce: hex::encode(nonce), - ciphertext: hex::encode(ct), + nonce, + ciphertext, chunk_count: chunks.chunk_count, total_bytes: chunks.total_bytes, }) @@ -601,8 +614,8 @@ fn open_text( let content_key = derive_content_key(epoch_key, routing.transfer_id.as_str())?; let nonce = decode_nonce(nonce_hex)?; let ct = hex::decode(ct_hex).map_err(|e| CoreError::Message(e.to_string()))?; - let aad = format!("{}:text", routing.message_id); - let pt = open(&content_key, &nonce, aad.as_bytes(), &ct)?; + let aad = envelope_aad(routing, EnvelopeFrame::Text).map_err(TransferError::from)?; + let pt = open(&content_key, &nonce, &aad, &ct)?; let text = String::from_utf8(pt).map_err(|_| CoreError::Message("text not utf-8".into()))?; Ok(ClipboardItem::Text { text }) } @@ -620,11 +633,145 @@ fn open_manifest( let content_key = derive_content_key(epoch_key, routing.transfer_id.as_str())?; let nonce = decode_nonce(nonce_hex)?; let ct = hex::decode(ct_hex).map_err(|e| CoreError::Message(e.to_string()))?; - let aad = format!("{}:manifest", routing.transfer_id); - let pt = open(&content_key, &nonce, aad.as_bytes(), &ct)?; + let aad = envelope_aad(routing, EnvelopeFrame::Manifest).map_err(TransferError::from)?; + let pt = open(&content_key, &nonce, &aad, &ct)?; Ok(serde_json::from_slice(&pt)?) } +/// Envelope version and sequence number stamped on one outgoing item. +#[derive(Clone, Copy, Debug)] +struct EnvelopeStamp { + version: u16, + seq: u64, +} + +impl EnvelopeStamp { + /// Reserve a persisted, strictly increasing `seq` for `room`. + #[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." + )] + fn next(store: &LocalStore, room: &RoomRecord, cfg: &AppConfig) -> Result { + Ok(Self { + version: sending_version(cfg.sync.legacy_envelopes), + seq: store.next_send_seq(&room.room_id, sequence_floor(Utc::now()))?, + }) + } +} + +/// Receive-side context: every inbound text envelope and manifest passes +/// through here so addressing, expiry, downgrade and replay checks cannot be +/// skipped by one entry point. +struct Inbound<'a> { + store: &'a LocalStore, + room: &'a RoomRecord, + local: &'a DeviceId, + epoch_key: &'a [u8; 32], +} + +impl Inbound<'_> { + #[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." + )] + fn text( + &self, + routing: &RoutingHeader, + nonce_hex: &str, + ct_hex: &str, + ) -> Result { + check_header( + routing, + self.room, + self.local, + Some(ItemKind::Text), + Utc::now(), + )?; + check_version(self.store, routing)?; + let item = open_text(self.epoch_key, routing, nonce_hex, ct_hex)?; + commit_sequence(self.store, routing)?; + Ok(item) + } + + #[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." + )] + fn manifest( + &self, + routing: &RoutingHeader, + nonce_hex: &str, + ct_hex: &str, + ) -> Result { + check_header(routing, self.room, self.local, None, Utc::now())?; + check_version(self.store, routing)?; + let manifest = open_manifest(self.epoch_key, routing, nonce_hex, ct_hex)?; + if manifest.item_kind != routing.item_kind { + return Err(EnvelopeRejection::WrongItemKind.into()); + } + commit_sequence(self.store, routing)?; + Ok(manifest) + } +} + +/// Decrypt a chunk frame only for a transfer whose manifest was accepted, +/// binding it to that manifest's routing header. +fn open_pending_chunk( + epoch_key: &[u8; 32], + manifests: &HashMap, + buf: &[u8], +) -> Result<(TransferId, u32, u32, Vec), TransferError> { + let frame = decode_chunk_frame(buf)?; + let (routing, _) = manifests + .get(frame.transfer_id.as_str()) + .ok_or(TransferError::Chunk("no accepted manifest for chunk"))?; + let plaintext = open_chunk(epoch_key, routing, &frame)?; + Ok(( + frame.transfer_id, + frame.chunk_index, + frame.chunk_count, + plaintext, + )) +} + +#[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." +)] +fn seal_text( + epoch_key: &[u8; 32], + routing: &RoutingHeader, + text: &str, +) -> Result<(String, String), CoreError> { + let content_key = derive_content_key(epoch_key, routing.transfer_id.as_str())?; + let nonce = derive_nonce(&content_key, TEXT_NONCE_INDEX)?; + let aad = envelope_aad(routing, EnvelopeFrame::Text).map_err(TransferError::from)?; + let ct = seal(&content_key, &nonce, &aad, text.as_bytes())?; + Ok((hex::encode(nonce), hex::encode(ct))) +} + +#[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." +)] +fn seal_manifest( + epoch_key: &[u8; 32], + routing: &RoutingHeader, + manifest: &ManifestPlain, +) -> Result<(String, String), CoreError> { + let content_key = derive_content_key(epoch_key, routing.transfer_id.as_str())?; + let nonce = derive_nonce(&content_key, MANIFEST_NONCE_INDEX)?; + let aad = envelope_aad(routing, EnvelopeFrame::Manifest).map_err(TransferError::from)?; + let ct = seal(&content_key, &nonce, &aad, &serde_json::to_vec(manifest)?)?; + Ok((hex::encode(nonce), hex::encode(ct))) +} + +/// Nonce-derivation index for a text envelope (one message per transfer key). +const TEXT_NONCE_INDEX: u32 = 0; +/// Nonce-derivation index for a manifest; chunk indices count up from zero, so +/// the top index never collides with a chunk of a valid transfer. +const MANIFEST_NONCE_INDEX: u32 = u32::MAX; + #[expect( clippy::result_large_err, reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." @@ -738,7 +885,8 @@ pub async fn oneshot_push(store: &LocalStore, item: ClipboardItem) -> Result<(), }) .await?; wait_hello_ok(&mut conn).await?; - send_item(&conn, &identity, &room, &epoch_key, 1, &item).await?; + let stamp = EnvelopeStamp::next(store, &room, &cfg)?; + send_item(&conn, &identity, &room, &epoch_key, stamp, &item).await?; tokio::time::sleep(Duration::from_millis(250)).await; conn.close().await; Ok(()) @@ -784,7 +932,7 @@ async fn apply_hello_ok( hello: &ControlMessage, identity: &DeviceIdentity, room: &RoomRecord, - epoch_key: &[u8; 32], + inbound: &Inbound<'_>, clipboard: &SystemClipboard, guard: &mut LoopGuard, handle: &SyncHandle, @@ -805,7 +953,7 @@ async fn apply_hello_ok( }; handle.peer_online.store(*peer_online, Ordering::Relaxed); if let Some(q) = queued_text { - if let Ok(item) = open_text(epoch_key, &q.routing, &q.nonce, &q.ciphertext) { + if let Ok(item) = inbound.text(&q.routing, &q.nonce, &q.ciphertext) { apply_remote( clipboard, guard, @@ -880,7 +1028,13 @@ pub async fn oneshot_pull( tokio::pin!(timeout); let staging = StagingArea::new(store.paths.inbox_dir.clone())?; let mut incoming: HashMap = HashMap::new(); - let mut manifests: HashMap = HashMap::new(); + let mut manifests: HashMap = HashMap::new(); + let inbound = Inbound { + store, + room: &room, + local: &identity.device_id, + epoch_key: &epoch_key, + }; loop { tokio::select! { _ = &mut timeout => return Err(CoreError::Timeout), @@ -889,7 +1043,7 @@ pub async fn oneshot_pull( match msg { Incoming::Control(ControlMessage::HelloOk { queued_text, .. }) => { if let Some(q) = queued_text { - let item = open_text(&epoch_key, &q.routing, &q.nonce, &q.ciphertext)?; + let item = inbound.text(&q.routing, &q.nonce, &q.ciphertext)?; return finish_pull(item, copy, output).await; } if !wait { @@ -897,26 +1051,26 @@ pub async fn oneshot_pull( } } Incoming::Control(ControlMessage::TextEnvelope { routing, nonce, ciphertext }) => { - let item = open_text(&epoch_key, &routing, &nonce, &ciphertext)?; + let item = inbound.text(&routing, &nonce, &ciphertext)?; return finish_pull(item, copy, output).await; } Incoming::Control(ControlMessage::Manifest { routing, nonce, ciphertext, .. }) => { - if let Ok(manifest) = open_manifest(&epoch_key, &routing, &nonce, &ciphertext) { + if let Ok(manifest) = inbound.manifest(&routing, &nonce, &ciphertext) { let id = routing.transfer_id.clone(); let t = staging.begin(&id, manifest.chunk_count); incoming.insert(id.0.clone(), t); - manifests.insert(id.0, manifest); + manifests.insert(id.0, (routing, manifest)); } } Incoming::Binary(buf) => { - if let Ok((tid, idx, count, pt)) = decrypt_chunk(&epoch_key, &buf) { + if let Ok((tid, idx, count, pt)) = open_pending_chunk(&epoch_key, &manifests, &buf) { if let Some(t) = incoming.get_mut(tid.as_str()) { if t.push(idx, count, pt).is_err() { t.fail(); continue; } if t.is_complete() { - if let Some(man) = manifests.remove(tid.as_str()) { + if let Some((_, man)) = manifests.remove(tid.as_str()) { if let Some(xfer) = incoming.remove(tid.as_str()) { if let Ok(payload) = xfer.assemble(&man.content_hash) { let item = item_from_payload(&man, payload, &staging, &tid).await?; diff --git a/crates/clipsync-core/src/envelope.rs b/crates/clipsync-core/src/envelope.rs new file mode 100644 index 0000000..da401ee --- /dev/null +++ b/crates/clipsync-core/src/envelope.rs @@ -0,0 +1,154 @@ +// Copyright the ClipSync contributors. +// SPDX-License-Identifier: MIT +//! Receive-side admission of envelopes: addressing, expiry, downgrade and replay. +//! +//! Order of checks for every text envelope or manifest: +//! 1. [`check_header`] — cheap checks on the (possibly unauthenticated) header. +//! 2. [`check_version`] — v2 always; v1 only from senders never seen on v2. +//! 3. AEAD open — for v2 this authenticates every header field checked above. +//! 4. [`commit_sequence`] — v2 only: durably require a strictly newer `seq`. +//! +//! The sequence is committed only after AEAD succeeds so forged headers cannot +//! advance the persisted high-water mark. + +use chrono::{DateTime, Duration, Utc}; + +use clipsync_protocol::{ + DeviceId, ItemKind, Recipient, RoutingHeader, CLOCK_SKEW_SECS, ENVELOPE_VERSION_AUTHENTICATED, + ENVELOPE_VERSION_LEGACY, HARD_MAX_TTL_SECS, +}; +use clipsync_storage::{LocalStore, RoomRecord, SeqCheck}; + +use crate::CoreError; + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum EnvelopeRejection { + #[error("unsupported envelope version {0}")] + UnsupportedVersion(u16), + #[error("envelope is for another room")] + WrongRoom, + #[error("envelope is addressed to another device")] + WrongRecipient, + #[error("envelope sender is not a peer of this room")] + UnknownSender, + #[error("envelope item kind does not match its frame")] + WrongItemKind, + #[error("envelope expired")] + Expired, + #[error("envelope sent in the future")] + NotYetValid, + #[error("envelope lifetime exceeds the protocol maximum")] + LifetimeTooLong, + #[error("legacy envelope from a sender that uses authenticated envelopes")] + Downgrade, + #[error("replayed envelope (seq {seq} <= {highest_seq})")] + Replayed { seq: u64, highest_seq: u64 }, +} + +/// Envelope version this device emits, per `sync.legacy_envelopes`. +pub(crate) fn sending_version(legacy_envelopes: bool) -> u16 { + if legacy_envelopes { + ENVELOPE_VERSION_LEGACY + } else { + ENVELOPE_VERSION_AUTHENTICATED + } +} + +/// Floor for outgoing `seq`: microseconds since the Unix epoch, so numbers keep +/// increasing even if the persisted counter is lost or two processes send. +pub(crate) fn sequence_floor(now: DateTime) -> u64 { + u64::try_from(now.timestamp_micros()).unwrap_or(0) +} + +/// Header checks that do not need the key. For v1 they run on unauthenticated +/// values (a relay may rewrite them); for v2 the AEAD open that follows binds +/// every checked value. +pub(crate) fn check_header( + routing: &RoutingHeader, + room: &RoomRecord, + local: &DeviceId, + expected_kind: Option, + now: DateTime, +) -> Result<(), EnvelopeRejection> { + if routing.version != ENVELOPE_VERSION_LEGACY + && routing.version != ENVELOPE_VERSION_AUTHENTICATED + { + return Err(EnvelopeRejection::UnsupportedVersion(routing.version)); + } + if routing.room_id != room.room_id { + return Err(EnvelopeRejection::WrongRoom); + } + match &routing.recipient { + Recipient::Broadcast => {} + Recipient::Device(device) if device == local => {} + Recipient::Device(_) => return Err(EnvelopeRejection::WrongRecipient), + } + if routing.sender_device_id == *local + || !room + .peers + .iter() + .any(|peer| peer.device_id == routing.sender_device_id) + { + return Err(EnvelopeRejection::UnknownSender); + } + if expected_kind.is_some_and(|kind| kind != routing.item_kind) { + return Err(EnvelopeRejection::WrongItemKind); + } + let skew = Duration::seconds(CLOCK_SKEW_SECS); + if routing.sent_at > now + skew { + return Err(EnvelopeRejection::NotYetValid); + } + if routing.expires_at + skew < now { + return Err(EnvelopeRejection::Expired); + } + // Saturate: an unrepresentable TTL can only be "too long". + let max_lifetime = Duration::seconds(i64::try_from(HARD_MAX_TTL_SECS).unwrap_or(i64::MAX)); + if routing.expires_at.signed_duration_since(routing.sent_at) > max_lifetime { + return Err(EnvelopeRejection::LifetimeTooLong); + } + Ok(()) +} + +/// Legacy v1 envelopes are accepted only from senders that have never +/// delivered an authenticated v2 envelope to this device. +#[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." +)] +pub(crate) fn check_version(store: &LocalStore, routing: &RoutingHeader) -> Result<(), CoreError> { + if routing.version == ENVELOPE_VERSION_LEGACY + && store.sender_is_authenticated(&routing.room_id, &routing.sender_device_id)? + { + return Err(EnvelopeRejection::Downgrade.into()); + } + Ok(()) +} + +/// After a successful AEAD open, durably require that a v2 `seq` is newer than +/// every earlier v2 envelope from the same sender. v1 headers are not +/// authenticated and legacy senders restart `seq` at 1, so v1 relies on the +/// in-memory message-ID cache and the header checks only. +#[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." +)] +pub(crate) fn commit_sequence( + store: &LocalStore, + routing: &RoutingHeader, +) -> Result<(), CoreError> { + if routing.version != ENVELOPE_VERSION_AUTHENTICATED { + return Ok(()); + } + match store.accept_authenticated_seq( + &routing.room_id, + &routing.sender_device_id, + routing.seq, + )? { + SeqCheck::Accepted => Ok(()), + SeqCheck::Replayed { highest_seq } => Err(EnvelopeRejection::Replayed { + seq: routing.seq, + highest_seq, + } + .into()), + } +} diff --git a/crates/clipsync-core/src/error.rs b/crates/clipsync-core/src/error.rs index b70a82b..70c4ba9 100644 --- a/crates/clipsync-core/src/error.rs +++ b/crates/clipsync-core/src/error.rs @@ -35,6 +35,8 @@ pub enum CoreError { NotPaired, #[error("timeout")] Timeout, + #[error("envelope rejected: {0}")] + Envelope(#[from] crate::envelope::EnvelopeRejection), } impl From for CoreError { diff --git a/crates/clipsync-core/src/lib.rs b/crates/clipsync-core/src/lib.rs index 09de6d7..f085004 100644 --- a/crates/clipsync-core/src/lib.rs +++ b/crates/clipsync-core/src/lib.rs @@ -4,6 +4,7 @@ //! ClipSync client: pairing, sync engine, loop prevention, and command facade. mod engine; +mod envelope; mod error; mod loop_guard; mod notify; @@ -18,6 +19,7 @@ pub use engine::{ oneshot_pull as engine_oneshot_pull, oneshot_push as engine_oneshot_push, run_daemon, SyncHandle, }; +pub use envelope::EnvelopeRejection; pub use error::{CoreError, ExitCode}; pub use pairing::{ begin_create_room, create_room, join_room, leave_room, PendingCreate, RoomOffer, diff --git a/crates/clipsync-core/tests/support/engine_behavior.rs b/crates/clipsync-core/tests/support/engine_behavior.rs index c447a40..3441bf9 100644 --- a/crates/clipsync-core/tests/support/engine_behavior.rs +++ b/crates/clipsync-core/tests/support/engine_behavior.rs @@ -5,12 +5,16 @@ #[path = "engine_coverage.rs"] mod coverage_expansion; +#[path = "envelope_security.rs"] +mod envelope_security; + use super::*; use crate::{App, AppPaths}; use clipsync_clipboard::{ClipboardBackend, MockClipboard}; use clipsync_protocol::{ CreatePairingRequest, CreatePairingResponse, DeviceRole, JoinPairingRequest, - JoinPairingResponse, PairingSessionId, RoomId, SyncDirection, + JoinPairingResponse, PairingSessionId, RoomId, SyncDirection, ENVELOPE_VERSION_AUTHENTICATED, + ENVELOPE_VERSION_LEGACY, }; use clipsync_storage::{AppConfig, PeerRecord}; use std::net::SocketAddr; @@ -655,7 +659,10 @@ async fn authenticated_but_invalid_text_is_ignored_and_the_next_message_still_ar &pair.a.identity, &room, &EPOCH, - 2, + EnvelopeStamp { + version: ENVELOPE_VERSION_AUTHENTICATED, + seq: 2, + }, &ClipboardItem::Text { text: "valid after rejection".into(), }, @@ -670,7 +677,7 @@ async fn authenticated_but_invalid_text_is_ignored_and_the_next_message_still_ar ); let logs = String::from_utf8(product_logs().lock().clone()).unwrap(); assert!( - logs.contains("text decrypt"), + logs.contains("text envelope rejected"), "decryption failure lost its diagnostic context" ); assert!( @@ -1095,25 +1102,44 @@ fn daemon_answers_commands_and_removes_pid_and_socket_after_interrupt() { }); } -fn text_routing() -> RoutingHeader { +/// Remote peer pinned by [`scripted_peer`]; scripted envelopes come from it. +const SCRIPT_SENDER: &str = "script-device-z"; + +/// Strictly increasing `seq` for scripted envelopes, in creation order. +static SCRIPT_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +/// Authenticated (v2) header a pinned `sender` would emit into `room`. +fn routing_from(room: &RoomId, sender: &str, kind: ItemKind) -> RoutingHeader { let now = Utc::now(); RoutingHeader { - version: PROTOCOL_VERSION, + version: ENVELOPE_VERSION_AUTHENTICATED, message_id: MessageId::new(), transfer_id: TransferId::new(), - room_id: RoomId::new(), - sender_device_id: clipsync_protocol::DeviceId::new(), + room_id: room.clone(), + sender_device_id: sender.into(), recipient: Recipient::Broadcast, sent_at: now, expires_at: now + ChronoDuration::seconds(60), - item_kind: ItemKind::Text, - seq: 1, + item_kind: kind, + seq: SCRIPT_SEQ.fetch_add(1, Ordering::Relaxed), + } +} + +fn text_routing(room: &RoomId) -> RoutingHeader { + routing_from(room, SCRIPT_SENDER, ItemKind::Text) +} + +/// Legacy (v1) header for checks of the AEAD layer alone. +fn legacy_routing() -> RoutingHeader { + RoutingHeader { + version: ENVELOPE_VERSION_LEGACY, + ..routing_from(&RoomId::new(), SCRIPT_SENDER, ItemKind::Text) } } #[test] fn text_envelopes_reject_malformed_nonce_ciphertext_and_changed_message_context() { - let routing = text_routing(); + let routing = legacy_routing(); let key = derive_content_key(&EPOCH, routing.transfer_id.as_str()).unwrap(); let nonce = [4; 12]; let ciphertext = seal( @@ -1156,37 +1182,22 @@ fn manifest(kind: ItemKind, payload: &[u8]) -> ManifestPlain { } } +/// Text envelope sealed exactly as a sender of `routing.version` seals it. fn encrypted_text(routing: RoutingHeader, text: &str) -> ControlMessage { - let key = derive_content_key(&EPOCH, routing.transfer_id.as_str()).unwrap(); - let nonce = derive_nonce(&key, 0).unwrap(); - let ciphertext = seal( - &key, - &nonce, - format!("{}:text", routing.message_id).as_bytes(), - text.as_bytes(), - ) - .unwrap(); + let (nonce, ciphertext) = seal_text(&EPOCH, &routing, text).unwrap(); ControlMessage::TextEnvelope { routing, - nonce: hex::encode(nonce), - ciphertext: hex::encode(ciphertext), + nonce, + ciphertext, } } fn encrypted_manifest(routing: RoutingHeader, manifest: &ManifestPlain) -> ControlMessage { - let key = derive_content_key(&EPOCH, routing.transfer_id.as_str()).unwrap(); - let nonce = derive_nonce(&key, u32::MAX).unwrap(); - let ciphertext = seal( - &key, - &nonce, - format!("{}:manifest", routing.transfer_id).as_bytes(), - &serde_json::to_vec(manifest).unwrap(), - ) - .unwrap(); + let (nonce, ciphertext) = seal_manifest(&EPOCH, &routing, manifest).unwrap(); ControlMessage::Manifest { routing, - nonce: hex::encode(nonce), - ciphertext: hex::encode(ciphertext), + nonce, + ciphertext, chunk_count: manifest.chunk_count, total_bytes: manifest.total_bytes, } @@ -1221,7 +1232,7 @@ async fn live_session_recovers_from_repeated_hello_duplicate_text_and_corrupt_tr ControlMessage::Hello { .. } )); send(&mut socket, hello(&room)).await; - let queued_routing = text_routing(); + let queued_routing = text_routing(&room); let ControlMessage::TextEnvelope { routing, nonce, @@ -1262,7 +1273,7 @@ async fn live_session_recovers_from_repeated_hello_duplicate_text_and_corrupt_tr }, ) .await; - let text = encrypted_text(text_routing(), "deduplicated text"); + let text = encrypted_text(text_routing(&room), "deduplicated text"); send(&mut socket, text.clone()).await; assert!(matches!( receive(&mut socket).await, @@ -1275,7 +1286,7 @@ async fn live_session_recovers_from_repeated_hello_duplicate_text_and_corrupt_tr send( &mut socket, ControlMessage::Manifest { - routing: text_routing(), + routing: text_routing(&room), nonce: "not hex".into(), ciphertext: "invalid".into(), chunk_count: 1, @@ -1287,13 +1298,13 @@ async fn live_session_recovers_from_repeated_hello_duplicate_text_and_corrupt_tr .send(Message::Binary(vec![0, 1, 2].into())) .await .unwrap(); - let orphan = split_and_encrypt(&EPOCH, &TransferId::new(), b"orphan").unwrap(); + let orphan = split_and_encrypt(&EPOCH, &text_routing(&room), b"orphan").unwrap(); socket .send(Message::Binary(orphan.frames[0].clone().into())) .await .unwrap(); for failure in ["count", "hash", "mime"] { - let routing = text_routing(); + let routing = routing_from(&room, SCRIPT_SENDER, ItemKind::Image); let mut manifest = manifest(ItemKind::Image, b"invalid image"); if failure == "count" { manifest.chunk_count = 2; @@ -1301,7 +1312,7 @@ async fn live_session_recovers_from_repeated_hello_duplicate_text_and_corrupt_tr if failure == "hash" { manifest.content_hash = "wrong hash".into(); } - let chunks = split_and_encrypt(&EPOCH, &routing.transfer_id, b"invalid image").unwrap(); + let chunks = split_and_encrypt(&EPOCH, &routing, b"invalid image").unwrap(); send(&mut socket, encrypted_manifest(routing, &manifest)).await; socket .send(Message::Binary(chunks.frames[0].clone().into())) @@ -1320,7 +1331,7 @@ async fn live_session_recovers_from_repeated_hello_duplicate_text_and_corrupt_tr socket.send(Message::Pong(vec![].into())).await.unwrap(); send( &mut socket, - encrypted_text(text_routing(), "recovered after invalid transfers"), + encrypted_text(text_routing(&room), "recovered after invalid transfers"), ) .await; assert!(matches!( @@ -1389,14 +1400,18 @@ async fn pull_reports_empty_closed_and_live_text_states_and_recovers_from_corrup return; } if case == "text" { - send(&mut socket, encrypted_text(text_routing(), "live pull")).await; + send( + &mut socket, + encrypted_text(text_routing(&room), "live pull"), + ) + .await; let _ = release.await; return; } send( &mut socket, ControlMessage::Manifest { - routing: text_routing(), + routing: text_routing(&room), nonce: "!".into(), ciphertext: "!".into(), chunk_count: 1, @@ -1405,13 +1420,13 @@ async fn pull_reports_empty_closed_and_live_text_states_and_recovers_from_corrup ) .await; socket.send(Message::Binary(vec![0].into())).await.unwrap(); - let orphan = split_and_encrypt(&EPOCH, &TransferId::new(), b"orphan").unwrap(); + let orphan = split_and_encrypt(&EPOCH, &text_routing(&room), b"orphan").unwrap(); socket .send(Message::Binary(orphan.frames[0].clone().into())) .await .unwrap(); for failure in ["count", "hash", "valid"] { - let routing = text_routing(); + let routing = text_routing(&room); let mut manifest = manifest(ItemKind::Text, b"binary pull"); if failure == "count" { manifest.chunk_count = 2; @@ -1419,8 +1434,7 @@ async fn pull_reports_empty_closed_and_live_text_states_and_recovers_from_corrup if failure == "hash" { manifest.content_hash = "bad hash".into(); } - let chunks = - split_and_encrypt(&EPOCH, &routing.transfer_id, b"binary pull").unwrap(); + let chunks = split_and_encrypt(&EPOCH, &routing, b"binary pull").unwrap(); send(&mut socket, encrypted_manifest(routing, &manifest)).await; socket .send(Message::Binary(chunks.frames[0].clone().into())) @@ -1620,11 +1634,17 @@ async fn hello_presence_only_starts_noise_for_a_known_online_peer_with_a_valid_p }; let mut noise = None; let mut done = case == "already-done"; + let inbound = Inbound { + store: &peer.app.store, + room: &room, + local: &peer.identity.device_id, + epoch_key: &EPOCH, + }; apply_hello_ok( &message, &peer.identity, &room, - &EPOCH, + &inbound, &clipboard, &mut guard, &handle, @@ -2150,7 +2170,7 @@ async fn pull_reports_output_file_failures_for_each_item_kind_without_overwritin #[test] fn manifest_rejection_distinguishes_encoding_authentication_and_authenticated_json_errors() { - let routing = text_routing(); + let routing = legacy_routing(); let nonce = [6; 12]; assert!(matches!( open_manifest(&EPOCH, &routing, &hex::encode(nonce), "!"), @@ -2220,7 +2240,18 @@ async fn closed_relay_senders_report_failure_for_text_images_and_file_transfers( }, ] { assert!(matches!( - send_item(&connection, &peer.identity, &room, &EPOCH, 1, &item).await, + send_item( + &connection, + &peer.identity, + &room, + &EPOCH, + EnvelopeStamp { + version: ENVELOPE_VERSION_AUTHENTICATED, + seq: 1 + }, + &item + ) + .await, Err(CoreError::Transport( clipsync_transport::TransportError::Closed )) diff --git a/crates/clipsync-core/tests/support/engine_coverage.rs b/crates/clipsync-core/tests/support/engine_coverage.rs index 81546e6..96dcf5e 100644 --- a/crates/clipsync-core/tests/support/engine_coverage.rs +++ b/crates/clipsync-core/tests/support/engine_coverage.rs @@ -78,7 +78,10 @@ async fn sessions_complete_real_noise_as_initiator_and_responder_before_continui send(&mut socket, presence()).await; send( &mut socket, - encrypted_text(text_routing(), "after authentication"), + encrypted_text( + routing_from(&room, "device-m", ItemKind::Text), + "after authentication", + ), ) .await; assert!(matches!( @@ -130,7 +133,7 @@ async fn live_presence_and_untrusted_noise_do_not_replace_the_last_authenticated routing, nonce, mut ciphertext, - } = encrypted_text(text_routing(), "forged queued text") + } = encrypted_text(text_routing(&room), "forged queued text") else { unreachable!() }; @@ -152,7 +155,7 @@ async fn live_presence_and_untrusted_noise_do_not_replace_the_last_authenticated send( &mut socket, ControlMessage::HelloOk { - room_id: room, + room_id: room.clone(), peer_online: true, peers: if case == "no-peers" { vec![] @@ -184,16 +187,31 @@ async fn live_presence_and_untrusted_noise_do_not_replace_the_last_authenticated .await; send( &mut socket, - encrypted_text(text_routing(), "valid after hostile presence"), + encrypted_text( + routing_from( + &room, + if case == "responder" { + "000-first" + } else { + SCRIPT_SENDER + }, + ItemKind::Text, + ), + "valid after hostile presence", + ), ) .await; - assert!(matches!( - receive(&mut socket).await, - ControlMessage::Ack { - status: AckStatus::Delivered, - .. - } - )); + // A room without pinned peers accepts no sender, so nothing is acknowledged; + // closing after the frame still lets the session process it first. + if case != "no-peers" { + assert!(matches!( + receive(&mut socket).await, + ControlMessage::Ack { + status: AckStatus::Delivered, + .. + } + )); + } }) .await; let peer = scripted_peer(&server.url, room_id); @@ -222,6 +240,13 @@ async fn live_presence_and_untrusted_noise_do_not_replace_the_last_authenticated .unwrap_err(); server.finish().await; assert!(error.to_string().contains("relay disconnected"), "{case}"); + if case == "no-peers" { + assert!( + clipboard.get().is_none(), + "unpinned sender reached the clipboard" + ); + continue; + } assert!( matches!(clipboard.get(), Some(ClipboardItem::Text { text }) if text == "valid after hostile presence") ); diff --git a/crates/clipsync-core/tests/support/envelope_security.rs b/crates/clipsync-core/tests/support/envelope_security.rs new file mode 100644 index 0000000..33830a7 --- /dev/null +++ b/crates/clipsync-core/tests/support/envelope_security.rs @@ -0,0 +1,502 @@ +// Copyright the ClipSync contributors. +// SPDX-License-Identifier: MIT +//! Envelope authentication, expiry, and replay behavior through a real relay. + +use super::*; +use crate::envelope::sequence_floor; +use crate::EnvelopeRejection; +use clipsync_protocol::CLOCK_SKEW_SECS; + +/// Routing header a current sender in `pair` would emit from `from` to the room. +fn room_routing(from: &Peer, seq: u64) -> RoutingHeader { + let room = from.app.store.current_room().unwrap(); + let now = Utc::now(); + RoutingHeader { + version: ENVELOPE_VERSION_AUTHENTICATED, + message_id: MessageId::new(), + transfer_id: TransferId::new(), + room_id: room.room_id, + sender_device_id: from.identity.device_id.clone(), + recipient: Recipient::Broadcast, + sent_at: now, + expires_at: now + ChronoDuration::seconds(60), + item_kind: ItemKind::Text, + seq, + } +} + +fn sealed_text(routing: RoutingHeader, text: &str) -> ControlMessage { + encrypted_text(routing, text) +} + +async fn deliver(sender: &mut RelayConnection, message: ControlMessage) { + sender.send_control(message).await.unwrap(); + loop { + if matches!(next_control(sender).await, ControlMessage::Ack { .. }) { + return; + } + } +} + +/// Send a fresh sentinel and wait for it, proving every earlier frame was processed. +async fn settle(sender: &mut RelayConnection, from: &Peer, session: &Session, seq: u64) { + let sentinel = format!("sentinel {seq}"); + deliver(sender, sealed_text(room_routing(from, seq), &sentinel)).await; + session.text(&sentinel).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn replayed_text_is_rejected_within_the_session_and_after_a_restart() { + let pair = Pair::new().await; + let mut sender = pair.member(&pair.a).await; + let original = sealed_text(room_routing(&pair.a, 10), "original clip"); + + let b = Session::start(&pair.b).await; + deliver(&mut sender, original.clone()).await; + b.text("original clip").await; + settle(&mut sender, &pair.a, &b, 11).await; + deliver(&mut sender, original.clone()).await; + settle(&mut sender, &pair.a, &b, 12).await; + assert_eq!( + b.clipboard.signature().await.unwrap(), + "3", + "an in-session replay overwrote the clipboard" + ); + b.stop().await; + + // A restarted daemon has an empty in-memory cache, like one past its TTL. + let restarted = Session::start(&pair.b).await; + deliver(&mut sender, original).await; + settle(&mut sender, &pair.a, &restarted, 13).await; + assert_eq!( + restarted.clipboard.signature().await.unwrap(), + "1", + "a replay after restart overwrote the clipboard with stale content" + ); + sender.close().await; + restarted.stop().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn expired_and_misaddressed_text_envelopes_never_reach_the_clipboard() { + let pair = Pair::new().await; + let mut sender = pair.member(&pair.a).await; + let b = Session::start(&pair.b).await; + + let mut expired = room_routing(&pair.a, 20); + expired.sent_at -= ChronoDuration::minutes(30); + expired.expires_at = expired.sent_at + ChronoDuration::seconds(60); + deliver(&mut sender, sealed_text(expired, "expired clip")).await; + + let mut other_room = room_routing(&pair.a, 21); + other_room.room_id = RoomId::new(); + deliver(&mut sender, sealed_text(other_room, "other room clip")).await; + + let mut other_recipient = room_routing(&pair.a, 22); + other_recipient.recipient = Recipient::Device(clipsync_protocol::DeviceId::new()); + deliver( + &mut sender, + sealed_text(other_recipient, "misaddressed clip"), + ) + .await; + + settle(&mut sender, &pair.a, &b, 23).await; + assert_eq!( + b.clipboard.signature().await.unwrap(), + "1", + "an expired or misaddressed envelope overwrote the clipboard" + ); + sender.close().await; + b.stop().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn relay_rewritten_routing_fields_are_rejected() { + let pair = Pair::new().await; + let mut sender = pair.member(&pair.a).await; + let b = Session::start(&pair.b).await; + + // Seal under the honest header, then let the "relay" rewrite each field. + let honest = room_routing(&pair.a, 30); + let ControlMessage::TextEnvelope { + nonce, ciphertext, .. + } = sealed_text(honest.clone(), "rewritten clip") + else { + unreachable!() + }; + let mut rewritten = Vec::new(); + let mut header = honest.clone(); + header.expires_at += ChronoDuration::seconds(120); + rewritten.push(header); + let mut header = honest.clone(); + header.sent_at -= ChronoDuration::seconds(1); + rewritten.push(header); + let mut header = honest.clone(); + header.seq += 1_000; + rewritten.push(header); + for header in rewritten { + deliver( + &mut sender, + ControlMessage::TextEnvelope { + routing: header, + nonce: nonce.clone(), + ciphertext: ciphertext.clone(), + }, + ) + .await; + } + settle(&mut sender, &pair.a, &b, 31).await; + assert_eq!( + b.clipboard.signature().await.unwrap(), + "1", + "a relay-rewritten routing header was accepted" + ); + sender.close().await; + b.stop().await; +} + +/// Every routing field a relay could rewrite, applied to an honest header. +fn rewritten_headers(honest: &RoutingHeader) -> Vec<(&'static str, RoutingHeader)> { + let mut variants = Vec::new(); + let mut push = |field: &'static str, change: &dyn Fn(&mut RoutingHeader)| { + let mut routing = honest.clone(); + change(&mut routing); + variants.push((field, routing)); + }; + push("version", &|r| r.version = ENVELOPE_VERSION_LEGACY); + push("message_id", &|r| r.message_id = MessageId::new()); + push("transfer_id", &|r| r.transfer_id = TransferId::new()); + push("room_id", &|r| r.room_id = RoomId::new()); + push("sender_device_id", &|r| r.sender_device_id = "other".into()); + push("recipient", &|r| { + r.recipient = Recipient::Device(clipsync_protocol::DeviceId::new()) + }); + push("sent_at", &|r| r.sent_at -= ChronoDuration::seconds(1)); + push("expires_at", &|r| { + r.expires_at += ChronoDuration::seconds(1) + }); + push("item_kind", &|r| r.item_kind = ItemKind::Files); + push("seq", &|r| r.seq += 1); + variants +} + +#[test] +fn tampering_any_authenticated_routing_field_fails_text_and_manifest_decryption() { + let honest = routing_from(&RoomId::new(), SCRIPT_SENDER, ItemKind::Text); + let (text_nonce, text_ct) = seal_text(&EPOCH, &honest, "authenticated").unwrap(); + let mut manifest_header = honest.clone(); + manifest_header.item_kind = ItemKind::Image; + let plain = manifest(ItemKind::Image, b"image"); + let (manifest_nonce, manifest_ct) = seal_manifest(&EPOCH, &manifest_header, &plain).unwrap(); + assert!(open_text(&EPOCH, &honest, &text_nonce, &text_ct).is_ok()); + assert_eq!( + open_manifest(&EPOCH, &manifest_header, &manifest_nonce, &manifest_ct).unwrap(), + plain + ); + for (field, routing) in rewritten_headers(&honest) { + assert!( + matches!( + open_text(&EPOCH, &routing, &text_nonce, &text_ct), + Err(CoreError::Crypto(_)) + ), + "text accepted with rewritten {field}" + ); + } + for (field, mut routing) in rewritten_headers(&manifest_header) { + if field == "item_kind" { + routing.item_kind = ItemKind::Text; + } + assert!( + matches!( + open_manifest(&EPOCH, &routing, &manifest_nonce, &manifest_ct), + Err(CoreError::Crypto(_)) + ), + "manifest accepted with rewritten {field}" + ); + } + let mut unknown = honest; + unknown.version = ENVELOPE_VERSION_AUTHENTICATED + 1; + assert!(open_text(&EPOCH, &unknown, &text_nonce, &text_ct).is_err()); +} + +fn inbound_for(peer: &Peer) -> (RoomRecord, LocalStore) { + let store = LocalStore::open_from(peer.app.store.paths.clone()).unwrap(); + (store.current_room().unwrap(), store) +} + +#[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." +)] +fn admit_text( + peer: &Peer, + routing: &RoutingHeader, + text: &str, +) -> Result { + let (room, store) = inbound_for(peer); + // An unknown version has no AAD; seal under v2 and present the header as is. + let sealing = RoutingHeader { + version: routing.version.min(ENVELOPE_VERSION_AUTHENTICATED), + ..routing.clone() + }; + let (nonce, ciphertext) = seal_text(&EPOCH, &sealing, text).unwrap(); + Inbound { + store: &store, + room: &room, + local: &peer.identity.device_id, + epoch_key: &EPOCH, + } + .text(routing, &nonce, &ciphertext) +} + +#[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." +)] +fn admit_manifest(peer: &Peer, routing: &RoutingHeader) -> Result { + let (room, store) = inbound_for(peer); + let (nonce, ciphertext) = + seal_manifest(&EPOCH, routing, &manifest(routing.item_kind, b"payload")).unwrap(); + Inbound { + store: &store, + room: &room, + local: &peer.identity.device_id, + epoch_key: &EPOCH, + } + .manifest(routing, &nonce, &ciphertext) +} + +fn rejection(result: Result) -> EnvelopeRejection { + match result { + Err(CoreError::Envelope(rejection)) => rejection, + other => panic!("expected an envelope rejection, got {other:?}"), + } +} + +#[test] +fn replays_are_rejected_without_the_memory_cache_and_after_reopening_the_store() { + let room = RoomId::new(); + let peer = scripted_peer("http://127.0.0.1:1", room.clone()); + let text = text_routing(&room); + let image = routing_from(&room, SCRIPT_SENDER, ItemKind::Image); + // Each admission opens a fresh store and holds no LoopGuard, so the + // in-memory message-ID cache (and its TTL) plays no part here. + admit_text(&peer, &text, "first delivery").unwrap(); + admit_manifest(&peer, &image).unwrap(); + for _restart in 0..2 { + assert_eq!( + rejection(admit_text(&peer, &text, "first delivery")), + EnvelopeRejection::Replayed { + seq: text.seq, + highest_seq: image.seq + } + ); + assert!(matches!( + rejection(admit_manifest(&peer, &image)), + EnvelopeRejection::Replayed { .. } + )); + } + let state = peer.app.store.load_replay_state().unwrap(); + assert_eq!( + state.rooms[room.as_str()].senders[SCRIPT_SENDER], + clipsync_storage::SenderReplayState { + highest_seq: image.seq, + authenticated: true + } + ); + // A newer envelope is still accepted, and a rejected forgery cannot raise + // the high-water mark because the sequence commits only after AEAD. + let mut forged = text_routing(&room); + forged.seq = u64::MAX; + let (room_record, store) = inbound_for(&peer); + let inbound = Inbound { + store: &store, + room: &room_record, + local: &peer.identity.device_id, + epoch_key: &EPOCH, + }; + let (nonce, ciphertext) = seal_text(&EPOCH, &text_routing(&room), "honest").unwrap(); + assert!(matches!( + inbound.text(&forged, &nonce, &ciphertext), + Err(CoreError::Crypto(_)) + )); + admit_text(&peer, &text_routing(&room), "newer").unwrap(); +} + +type HeaderChange = Box; + +#[test] +fn header_checks_cover_addressing_lifetime_and_frame_kind() { + let room = RoomId::new(); + let peer = scripted_peer("http://127.0.0.1:1", room.clone()); + let mut direct = text_routing(&room); + direct.recipient = Recipient::Device(peer.identity.device_id.clone()); + admit_text(&peer, &direct, "addressed to this device").unwrap(); + let cases: Vec<(EnvelopeRejection, HeaderChange)> = vec![ + ( + EnvelopeRejection::UnsupportedVersion(ENVELOPE_VERSION_AUTHENTICATED + 1), + Box::new(|r| r.version = ENVELOPE_VERSION_AUTHENTICATED + 1), + ), + ( + EnvelopeRejection::WrongRoom, + Box::new(|r| r.room_id = RoomId::new()), + ), + ( + EnvelopeRejection::WrongRecipient, + Box::new(|r| r.recipient = Recipient::Device("someone-else".into())), + ), + ( + EnvelopeRejection::UnknownSender, + Box::new(|r| r.sender_device_id = "unpinned-device".into()), + ), + ( + EnvelopeRejection::UnknownSender, + Box::new(|r| r.sender_device_id = "script-device-a".into()), + ), + ( + EnvelopeRejection::WrongItemKind, + Box::new(|r| r.item_kind = ItemKind::Image), + ), + ( + EnvelopeRejection::NotYetValid, + Box::new(|r| { + r.sent_at += ChronoDuration::seconds(CLOCK_SKEW_SECS + 60); + r.expires_at = r.sent_at + ChronoDuration::seconds(60); + }), + ), + ( + EnvelopeRejection::Expired, + Box::new(|r| { + r.expires_at = Utc::now() - ChronoDuration::seconds(CLOCK_SKEW_SECS + 1); + r.sent_at = r.expires_at - ChronoDuration::seconds(60); + }), + ), + ( + EnvelopeRejection::LifetimeTooLong, + Box::new(|r| { + r.expires_at = r.sent_at + + ChronoDuration::seconds(clipsync_protocol::HARD_MAX_TTL_SECS as i64 + 1) + }), + ), + ]; + for (expected, change) in cases { + let mut routing = text_routing(&room); + change(&mut routing); + assert_eq!(rejection(admit_text(&peer, &routing, "rejected")), expected); + } + // Within the skew tolerance, a slightly early or late envelope still arrives. + let mut skewed = text_routing(&room); + skewed.sent_at += ChronoDuration::seconds(CLOCK_SKEW_SECS / 2); + skewed.expires_at = Utc::now() - ChronoDuration::seconds(CLOCK_SKEW_SECS / 2); + admit_text(&peer, &skewed, "skewed clocks").unwrap(); + // The decrypted manifest must describe the item kind its header announced. + let image = routing_from(&room, SCRIPT_SENDER, ItemKind::Image); + let (room_record, store) = inbound_for(&peer); + let (nonce, ciphertext) = + seal_manifest(&EPOCH, &image, &manifest(ItemKind::Files, b"payload")).unwrap(); + assert_eq!( + rejection( + Inbound { + store: &store, + room: &room_record, + local: &peer.identity.device_id, + epoch_key: &EPOCH, + } + .manifest(&image, &nonce, &ciphertext) + ), + EnvelopeRejection::WrongItemKind + ); +} + +#[test] +fn legacy_envelopes_are_accepted_until_the_sender_upgrades_then_refused_across_restarts() { + let room = RoomId::new(); + let peer = scripted_peer("http://127.0.0.1:1", room.clone()); + let legacy = |seq_reset: bool| RoutingHeader { + version: ENVELOPE_VERSION_LEGACY, + // Legacy senders restart seq at 1 every session. + seq: if seq_reset { 1 } else { 2 }, + ..text_routing(&room) + }; + // An updated receiver keeps working with a not-yet-updated sender. + admit_text(&peer, &legacy(true), "legacy one").unwrap(); + admit_text(&peer, &legacy(true), "legacy after peer restart").unwrap(); + // Header checks still apply to legacy envelopes. + let mut expired = legacy(false); + expired.expires_at = Utc::now() - ChronoDuration::minutes(10); + expired.sent_at = expired.expires_at - ChronoDuration::seconds(60); + assert_eq!( + rejection(admit_text(&peer, &expired, "expired legacy")), + EnvelopeRejection::Expired + ); + let mut relabeled = legacy(false); + relabeled.sender_device_id = "fresh-unpinned-id".into(); + assert_eq!( + rejection(admit_text(&peer, &relabeled, "relabeled legacy")), + EnvelopeRejection::UnknownSender + ); + assert!(!peer + .app + .store + .sender_is_authenticated(&room, &SCRIPT_SENDER.into()) + .unwrap()); + + // The first authenticated envelope from the sender pins it to v2 for good. + admit_text(&peer, &text_routing(&room), "authenticated").unwrap(); + for _restart in 0..2 { + assert_eq!( + rejection(admit_text(&peer, &legacy(true), "downgraded")), + EnvelopeRejection::Downgrade + ); + } + admit_text(&peer, &text_routing(&room), "authenticated again").unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn senders_emit_v2_by_default_and_legacy_v1_only_when_configured() { + let pair = Pair::new().await; + let mut receiver = pair.member(&pair.b).await; + for legacy in [false, true] { + pair.a + .configure(|config| config.sync.legacy_envelopes = legacy); + let a = Session::start(&pair.a).await; + let text = format!("legacy={legacy}"); + a.clipboard.set(ClipboardItem::Text { text: text.clone() }); + let (routing, nonce, ciphertext) = loop { + if let ControlMessage::TextEnvelope { + routing, + nonce, + ciphertext, + } = next_control(&mut receiver).await + { + break (routing, nonce, ciphertext); + } + }; + // What a receiver from before this change does: v1 AAD, header ignored. + let key = derive_content_key(&EPOCH, routing.transfer_id.as_str()).unwrap(); + let old_receiver = open( + &key, + &decode_nonce(&nonce).unwrap(), + format!("{}:text", routing.message_id).as_bytes(), + &hex::decode(&ciphertext).unwrap(), + ); + if legacy { + assert_eq!(routing.version, ENVELOPE_VERSION_LEGACY); + assert_eq!(old_receiver.unwrap(), text.as_bytes()); + } else { + assert_eq!(routing.version, ENVELOPE_VERSION_AUTHENTICATED); + assert!(old_receiver.is_err(), "v2 must not open under the v1 AAD"); + } + assert!( + matches!(open_text(&EPOCH, &routing, &nonce, &ciphertext).unwrap(), + ClipboardItem::Text { text: opened } if opened == text) + ); + // Sequence numbers are persisted and keep increasing across sessions. + let last = pair.a.app.store.load_replay_state().unwrap().rooms[routing.room_id.as_str()] + .last_sent_seq; + assert_eq!(routing.seq, last); + assert!(routing.seq >= sequence_floor(routing.sent_at - ChronoDuration::seconds(1))); + a.stop().await; + } + receiver.close().await; +} diff --git a/crates/clipsync-protocol/src/envelope.rs b/crates/clipsync-protocol/src/envelope.rs new file mode 100644 index 0000000..7e9ea08 --- /dev/null +++ b/crates/clipsync-protocol/src/envelope.rs @@ -0,0 +1,214 @@ +// Copyright the ClipSync contributors. +// SPDX-License-Identifier: MIT +//! AEAD associated data for text envelopes, manifests, and chunk frames. +//! +//! Envelope version 1 authenticated only the message or transfer ID. Version 2 +//! authenticates a canonical encoding of the whole [`RoutingHeader`], so a relay +//! cannot alter room, sender, recipient, timestamps, item kind, or sequence +//! number without the receiver's AEAD check failing. + +use crate::messages::{ItemKind, Recipient, RoutingHeader}; +use crate::{ProtocolError, Result}; + +/// Legacy envelope: AAD covers only the message ID (text) or transfer ID. +pub const ENVELOPE_VERSION_LEGACY: u16 = 1; +/// Authenticated envelope: AAD covers the canonical full routing header. +pub const ENVELOPE_VERSION_AUTHENTICATED: u16 = 2; + +/// Domain separator so v2 AAD can never collide with another AAD format. +pub const ENVELOPE_AAD_LABEL: &[u8] = b"clipsync-envelope-v2"; + +// Canonical one-byte tags. Values are part of the v2 wire contract. +const RECIPIENT_BROADCAST: u8 = 0; +const RECIPIENT_DEVICE: u8 = 1; +const KIND_TEXT: u8 = 0; +const KIND_IMAGE: u8 = 1; +const KIND_FILES: u8 = 2; +const FRAME_TEXT: u8 = 0; +const FRAME_MANIFEST: u8 = 1; +const FRAME_CHUNK: u8 = 2; + +/// Which encrypted object of an envelope the AAD is for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EnvelopeFrame { + Text, + Manifest, + Chunk { index: u32, count: u32 }, +} + +/// AAD for `frame` under the envelope version named in `routing.version`. +pub fn envelope_aad(routing: &RoutingHeader, frame: EnvelopeFrame) -> Result> { + match routing.version { + ENVELOPE_VERSION_LEGACY => Ok(legacy_aad(routing, frame)), + ENVELOPE_VERSION_AUTHENTICATED => Ok(authenticated_aad(routing, frame)), + other => Err(ProtocolError::Version(other)), + } +} + +fn legacy_aad(routing: &RoutingHeader, frame: EnvelopeFrame) -> Vec { + match frame { + EnvelopeFrame::Text => format!("{}:text", routing.message_id).into_bytes(), + EnvelopeFrame::Manifest => format!("{}:manifest", routing.transfer_id).into_bytes(), + EnvelopeFrame::Chunk { index, .. } => { + let mut aad = routing.transfer_id.as_str().as_bytes().to_vec(); + aad.extend_from_slice(&index.to_be_bytes()); + aad + } + } +} + +fn authenticated_aad(routing: &RoutingHeader, frame: EnvelopeFrame) -> Vec { + let mut aad = ENVELOPE_AAD_LABEL.to_vec(); + aad.extend_from_slice(&routing.version.to_be_bytes()); + put_field(&mut aad, routing.message_id.as_str()); + put_field(&mut aad, routing.transfer_id.as_str()); + put_field(&mut aad, routing.room_id.as_str()); + put_field(&mut aad, routing.sender_device_id.as_str()); + match &routing.recipient { + Recipient::Broadcast => aad.push(RECIPIENT_BROADCAST), + Recipient::Device(device) => { + aad.push(RECIPIENT_DEVICE); + put_field(&mut aad, device.as_str()); + } + } + for at in [routing.sent_at, routing.expires_at] { + aad.extend_from_slice(&at.timestamp().to_be_bytes()); + aad.extend_from_slice(&at.timestamp_subsec_nanos().to_be_bytes()); + } + aad.push(match routing.item_kind { + ItemKind::Text => KIND_TEXT, + ItemKind::Image => KIND_IMAGE, + ItemKind::Files => KIND_FILES, + }); + aad.extend_from_slice(&routing.seq.to_be_bytes()); + match frame { + EnvelopeFrame::Text => aad.push(FRAME_TEXT), + EnvelopeFrame::Manifest => aad.push(FRAME_MANIFEST), + EnvelopeFrame::Chunk { index, count } => { + aad.push(FRAME_CHUNK); + aad.extend_from_slice(&index.to_be_bytes()); + aad.extend_from_slice(&count.to_be_bytes()); + } + } + aad +} + +/// Length-prefixed so adjacent variable-length IDs cannot shift boundaries. +fn put_field(aad: &mut Vec, value: &str) { + aad.extend_from_slice(&(value.len() as u64).to_be_bytes()); + aad.extend_from_slice(value.as_bytes()); +} + +#[cfg(test)] +#[cfg_attr(coverage_nightly, coverage(off))] +mod tests { + use super::*; + use crate::{DeviceId, MessageId, RoomId, TransferId}; + use chrono::{Duration, TimeZone, Utc}; + + fn header(version: u16) -> RoutingHeader { + let sent_at = Utc.timestamp_opt(1_700_000_000, 123_456_789).unwrap(); + RoutingHeader { + version, + message_id: MessageId::from("message"), + transfer_id: TransferId::from("transfer"), + room_id: RoomId::from("room"), + sender_device_id: DeviceId::from("sender"), + recipient: Recipient::Broadcast, + sent_at, + expires_at: sent_at + Duration::seconds(60), + item_kind: ItemKind::Text, + seq: 7, + } + } + + #[test] + fn legacy_aad_matches_the_v1_wire_contract() { + let routing = header(ENVELOPE_VERSION_LEGACY); + assert_eq!( + envelope_aad(&routing, EnvelopeFrame::Text).unwrap(), + b"message:text" + ); + assert_eq!( + envelope_aad(&routing, EnvelopeFrame::Manifest).unwrap(), + b"transfer:manifest" + ); + assert_eq!( + envelope_aad(&routing, EnvelopeFrame::Chunk { index: 2, count: 9 }).unwrap(), + b"transfer\0\0\0\x02" + ); + } + + #[test] + fn authenticated_aad_changes_with_every_routing_field_and_frame() { + let base = header(ENVELOPE_VERSION_AUTHENTICATED); + let reference = envelope_aad(&base, EnvelopeFrame::Text).unwrap(); + assert!(reference.starts_with(ENVELOPE_AAD_LABEL)); + let mut variants: Vec = Vec::new(); + let mut push = |change: &dyn Fn(&mut RoutingHeader)| { + let mut routing = base.clone(); + change(&mut routing); + variants.push(routing); + }; + push(&|r| r.message_id = MessageId::from("message2")); + push(&|r| r.transfer_id = TransferId::from("transfer2")); + push(&|r| r.room_id = RoomId::from("room2")); + push(&|r| r.sender_device_id = DeviceId::from("sender2")); + push(&|r| r.recipient = Recipient::Device(DeviceId::from("sender"))); + push(&|r| r.sent_at += Duration::nanoseconds(1)); + push(&|r| r.expires_at += Duration::seconds(1)); + push(&|r| r.item_kind = ItemKind::Image); + push(&|r| r.item_kind = ItemKind::Files); + push(&|r| r.seq += 1); + // Shifting a byte between adjacent IDs must not produce the same AAD. + push(&|r| { + r.message_id = MessageId::from("messaget"); + r.transfer_id = TransferId::from("ransfer"); + }); + for routing in &variants { + assert_ne!( + envelope_aad(routing, EnvelopeFrame::Text).unwrap(), + reference, + "{routing:?}" + ); + } + let frames = [ + EnvelopeFrame::Text, + EnvelopeFrame::Manifest, + EnvelopeFrame::Chunk { index: 0, count: 1 }, + EnvelopeFrame::Chunk { index: 1, count: 1 }, + EnvelopeFrame::Chunk { index: 0, count: 2 }, + ]; + let encoded: std::collections::HashSet<_> = frames + .iter() + .map(|frame| envelope_aad(&base, *frame).unwrap()) + .collect(); + assert_eq!(encoded.len(), frames.len()); + assert_eq!( + envelope_aad(&base, EnvelopeFrame::Text).unwrap(), + reference, + "canonical encoding must be deterministic" + ); + } + + #[test] + fn authenticated_aad_survives_the_json_wire_roundtrip() { + let routing = header(ENVELOPE_VERSION_AUTHENTICATED); + let decoded: RoutingHeader = + serde_json::from_str(&serde_json::to_string(&routing).unwrap()).unwrap(); + assert_eq!( + envelope_aad(&decoded, EnvelopeFrame::Manifest).unwrap(), + envelope_aad(&routing, EnvelopeFrame::Manifest).unwrap() + ); + } + + #[test] + fn unknown_envelope_versions_have_no_aad() { + for version in [0, ENVELOPE_VERSION_AUTHENTICATED + 1] { + assert!(matches!( + envelope_aad(&header(version), EnvelopeFrame::Text), + Err(ProtocolError::Version(v)) if v == version + )); + } + } +} diff --git a/crates/clipsync-protocol/src/lib.rs b/crates/clipsync-protocol/src/lib.rs index 580c293..9442162 100644 --- a/crates/clipsync-protocol/src/lib.rs +++ b/crates/clipsync-protocol/src/lib.rs @@ -4,15 +4,23 @@ //! ClipSync wire protocol: routing headers, control messages, binary chunks, limits. mod chunk; +mod envelope; mod ids; mod limits; mod messages; pub use chunk::{decode_chunk_frame, encode_chunk_frame, ChunkFrame, CHUNK_MAGIC}; +pub use envelope::{ + envelope_aad, EnvelopeFrame, ENVELOPE_AAD_LABEL, ENVELOPE_VERSION_AUTHENTICATED, + ENVELOPE_VERSION_LEGACY, +}; pub use ids::{DeviceId, MessageId, PairingSessionId, RoomId, TransferId}; pub use limits::*; pub use messages::*; +/// Hello/pairing protocol version checked by the relay. Envelope AAD is +/// versioned separately in `RoutingHeader.version`, so v2 envelopes work with +/// existing relays. pub const PROTOCOL_VERSION: u16 = 1; pub const PROTOCOL_NAME: &str = "clipsync-v1"; pub const PAIRING_TRANSCRIPT_LABEL: &str = "clipsync-pairing-v1"; diff --git a/crates/clipsync-protocol/src/limits.rs b/crates/clipsync-protocol/src/limits.rs index 1d016fb..1554df5 100644 --- a/crates/clipsync-protocol/src/limits.rs +++ b/crates/clipsync-protocol/src/limits.rs @@ -26,7 +26,12 @@ pub const HEARTBEAT_SECS: u64 = 20; pub const TRANSFER_IDLE_SECS: u64 = 60; pub const REPLAY_CACHE_TTL_SECS: u64 = 120; pub const LOOP_CACHE_TTL_SECS: u64 = 15; -pub const CLOCK_SKEW_SECS: i64 = 5; +/// Tolerated sender/receiver wall-clock difference when a receiver checks an +/// envelope's `sent_at`/`expires_at`. NTP-synced hosts agree to well under a +/// second; 30 s also absorbs loosely synced mobile clocks. Replay protection for +/// authenticated envelopes rests on per-sender sequence numbers, not on expiry, +/// so this margin does not widen the replay window. +pub const CLOCK_SKEW_SECS: i64 = 30; pub const NOTIFY_COOLDOWN_SECS: u64 = 8; diff --git a/crates/clipsync-storage/src/config.rs b/crates/clipsync-storage/src/config.rs index 7b9bda1..067acb8 100644 --- a/crates/clipsync-storage/src/config.rs +++ b/crates/clipsync-storage/src/config.rs @@ -23,6 +23,10 @@ pub struct SyncConfig { pub types: Vec, pub debounce_ms: u64, pub ttl_secs: u64, + /// Rollout aid: send legacy v1 envelopes so peers that have not been + /// updated yet can still decrypt them. Off by default; see docs/protocol.md. + #[serde(default)] + pub legacy_envelopes: bool, } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -59,6 +63,7 @@ impl Default for SyncConfig { types: vec!["text".into(), "image".into(), "files".into()], debounce_ms: clipsync_protocol::DEBOUNCE_MS, ttl_secs: DEFAULT_TTL_SECS, + legacy_envelopes: false, } } } @@ -84,6 +89,7 @@ impl AppConfig { "sync.direction" => Some(format!("{:?}", self.sync.direction).to_lowercase()), "sync.auto_start" => Some(self.sync.auto_start.to_string()), "sync.ttl_secs" => Some(self.sync.ttl_secs.to_string()), + "sync.legacy_envelopes" => Some(self.sync.legacy_envelopes.to_string()), "notify.enabled" => Some(self.notify.enabled.to_string()), "notify.preview" => Some(self.notify.preview.to_string()), _ => None, @@ -104,6 +110,10 @@ impl AppConfig { self.sync.auto_start = parse_bool(value); true } + "sync.legacy_envelopes" => { + self.sync.legacy_envelopes = parse_bool(value); + true + } "sync.direction" => { self.sync.direction = match value { "both" => SyncDirection::Both, diff --git a/crates/clipsync-storage/src/lib.rs b/crates/clipsync-storage/src/lib.rs index 62a24ca..b790494 100644 --- a/crates/clipsync-storage/src/lib.rs +++ b/crates/clipsync-storage/src/lib.rs @@ -5,11 +5,13 @@ mod config; mod paths; +mod replay; mod secrets; mod store; pub use config::{AppConfig, NotifyConfig, SyncConfig}; pub use paths::AppPaths; +pub use replay::{ReplayState, RoomReplayState, SenderReplayState, SeqCheck}; pub use secrets::SecretStore; pub use store::{LocalStore, PairingWait, PeerRecord, RoomRecord, StateFile}; diff --git a/crates/clipsync-storage/src/paths.rs b/crates/clipsync-storage/src/paths.rs index 51a6fe0..bfafe02 100644 --- a/crates/clipsync-storage/src/paths.rs +++ b/crates/clipsync-storage/src/paths.rs @@ -72,6 +72,11 @@ impl AppPaths { self.data_dir.join("state.json") } + /// Private envelope sequence/replay state; see `LocalStore::next_send_seq`. + pub fn replay_state_file(&self) -> PathBuf { + self.data_dir.join("replay-state.json") + } + pub fn identity_file(&self) -> PathBuf { self.data_dir.join("identity.json") } diff --git a/crates/clipsync-storage/src/replay.rs b/crates/clipsync-storage/src/replay.rs new file mode 100644 index 0000000..88d2ced --- /dev/null +++ b/crates/clipsync-storage/src/replay.rs @@ -0,0 +1,237 @@ +// Copyright the ClipSync contributors. +// SPDX-License-Identifier: MIT +//! Persisted envelope sequence state that survives daemon restarts. +//! +//! Senders keep their last issued `seq` per room so it stays monotonic across +//! restarts. Receivers keep, per room and sender, the highest `seq` accepted +//! from an authenticated (v2) envelope, and whether that sender has ever used +//! one; a sender seen on v2 may not fall back to unauthenticated v1 envelopes. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use clipsync_protocol::{DeviceId, RoomId}; + +use crate::store::LocalStore; +use crate::Result; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplayState { + #[serde(default)] + pub rooms: BTreeMap, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RoomReplayState { + /// Last `seq` this device put in an outgoing envelope for the room. + #[serde(default)] + pub last_sent_seq: u64, + /// Receive-side state keyed by sender device ID. + #[serde(default)] + pub senders: BTreeMap, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SenderReplayState { + /// Highest `seq` accepted from an authenticated envelope of this sender. + #[serde(default)] + pub highest_seq: u64, + /// The sender has delivered an authenticated envelope; refuse legacy ones. + #[serde(default)] + pub authenticated: bool, +} + +/// Outcome of offering an authenticated envelope's `seq` to the replay state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SeqCheck { + /// Newer than anything accepted before; now recorded durably. + Accepted, + /// Not newer than an already accepted envelope from the same sender. + Replayed { highest_seq: u64 }, +} + +impl LocalStore { + pub fn load_replay_state(&self) -> Result { + let path = self.paths.replay_state_file(); + if !path.exists() { + return Ok(ReplayState::default()); + } + Ok(serde_json::from_slice(&std::fs::read(path)?)?) + } + + fn save_replay_state(&self, state: &ReplayState) -> Result<()> { + crate::secrets::write_private( + &self.paths.replay_state_file(), + &serde_json::to_vec_pretty(state)?, + )?; + Ok(()) + } + + /// Reserve the next outgoing `seq` for `room_id` and persist it before use. + /// + /// The value is at least `floor` (callers pass a wall-clock reading), so a + /// lost state file or two processes sending concurrently still move forward; + /// it is always above the last persisted value, so a clock stepping back + /// does not reuse a number. + pub fn next_send_seq(&self, room_id: &RoomId, floor: u64) -> Result { + let mut state = self.load_replay_state()?; + let room = state.rooms.entry(room_id.to_string()).or_default(); + let seq = room.last_sent_seq.saturating_add(1).max(floor); + room.last_sent_seq = seq; + self.save_replay_state(&state)?; + Ok(seq) + } + + /// Accept `seq` from an authenticated envelope only if it is newer than + /// every earlier one from `sender`; record it durably before returning. + pub fn accept_authenticated_seq( + &self, + room_id: &RoomId, + sender: &DeviceId, + seq: u64, + ) -> Result { + let mut state = self.load_replay_state()?; + let entry = state + .rooms + .entry(room_id.to_string()) + .or_default() + .senders + .entry(sender.to_string()) + .or_default(); + if entry.authenticated && seq <= entry.highest_seq { + return Ok(SeqCheck::Replayed { + highest_seq: entry.highest_seq, + }); + } + entry.highest_seq = seq; + entry.authenticated = true; + self.save_replay_state(&state)?; + Ok(SeqCheck::Accepted) + } + + /// Whether `sender` has already delivered an authenticated envelope here. + pub fn sender_is_authenticated(&self, room_id: &RoomId, sender: &DeviceId) -> Result { + Ok(self + .load_replay_state()? + .rooms + .get(room_id.as_str()) + .and_then(|room| room.senders.get(sender.as_str())) + .is_some_and(|entry| entry.authenticated)) + } +} + +#[cfg(test)] +#[cfg_attr(coverage_nightly, coverage(off))] +mod tests { + use super::*; + use crate::AppPaths; + + fn store(root: &std::path::Path) -> LocalStore { + LocalStore::open_from(AppPaths::from_root(root.into())).unwrap() + } + + #[test] + fn accepted_sequence_numbers_survive_reopening_the_store() { + let root = tempfile::tempdir().unwrap(); + let room = RoomId::from("room"); + let sender = DeviceId::from("sender"); + let first = store(root.path()); + assert!(!first.sender_is_authenticated(&room, &sender).unwrap()); + assert_eq!( + first.accept_authenticated_seq(&room, &sender, 5).unwrap(), + SeqCheck::Accepted + ); + assert_eq!( + first.accept_authenticated_seq(&room, &sender, 5).unwrap(), + SeqCheck::Replayed { highest_seq: 5 } + ); + drop(first); + + let reopened = store(root.path()); + assert!(reopened.sender_is_authenticated(&room, &sender).unwrap()); + for stale in [0, 4, 5] { + assert_eq!( + reopened + .accept_authenticated_seq(&room, &sender, stale) + .unwrap(), + SeqCheck::Replayed { highest_seq: 5 } + ); + } + assert_eq!( + reopened + .accept_authenticated_seq(&room, &sender, 6) + .unwrap(), + SeqCheck::Accepted + ); + // State is per room and per sender. + let other = DeviceId::from("other"); + assert_eq!( + reopened.accept_authenticated_seq(&room, &other, 1).unwrap(), + SeqCheck::Accepted + ); + assert_eq!( + reopened + .accept_authenticated_seq(&RoomId::from("room2"), &sender, 1) + .unwrap(), + SeqCheck::Accepted + ); + } + + #[test] + fn send_sequence_is_monotonic_across_restarts_clock_steps_and_lost_state() { + let root = tempfile::tempdir().unwrap(); + let room = RoomId::from("room"); + let first = store(root.path()); + assert_eq!(first.next_send_seq(&room, 0).unwrap(), 1); + assert_eq!(first.next_send_seq(&room, 100).unwrap(), 100); + drop(first); + let reopened = store(root.path()); + // A clock that stepped backwards never reuses an issued number. + assert_eq!(reopened.next_send_seq(&room, 50).unwrap(), 101); + std::fs::remove_file(reopened.paths.replay_state_file()).unwrap(); + // Without state the wall-clock floor still moves past old numbers. + assert_eq!(reopened.next_send_seq(&room, 1_000).unwrap(), 1_000); + } + + #[test] + fn legacy_and_partial_files_load_with_defaults_and_corruption_fails_closed() { + let root = tempfile::tempdir().unwrap(); + let store = store(root.path()); + std::fs::write( + store.paths.replay_state_file(), + br#"{"rooms":{"room":{"senders":{"sender":{}}}},"future_field":1}"#, + ) + .unwrap(); + let state = store.load_replay_state().unwrap(); + assert_eq!( + state.rooms["room"].senders["sender"], + SenderReplayState::default() + ); + std::fs::write(store.paths.replay_state_file(), b"{broken").unwrap(); + assert!(store.load_replay_state().is_err()); + assert!(store + .accept_authenticated_seq(&RoomId::from("room"), &DeviceId::from("sender"), 1) + .is_err()); + assert!(store.next_send_seq(&RoomId::from("room"), 1).is_err()); + assert_eq!( + std::fs::read(store.paths.replay_state_file()).unwrap(), + b"{broken", + "a corrupt replay file must not be silently reset" + ); + } + + #[cfg(unix)] + #[test] + fn replay_state_file_is_private() { + use std::os::unix::fs::PermissionsExt; + let root = tempfile::tempdir().unwrap(); + let store = store(root.path()); + store.next_send_seq(&RoomId::from("room"), 1).unwrap(); + let mode = std::fs::metadata(store.paths.replay_state_file()) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600); + } +} diff --git a/crates/clipsync-storage/tests/config_contract.rs b/crates/clipsync-storage/tests/config_contract.rs index 66b92fd..c643e3d 100644 --- a/crates/clipsync-storage/tests/config_contract.rs +++ b/crates/clipsync-storage/tests/config_contract.rs @@ -42,6 +42,8 @@ url = "https://hooks.example.test/π" assert_eq!(config.sync.types, ["files", "image", "text"]); assert_eq!(config.sync.debounce_ms, 341); assert_eq!(config.sync.ttl_secs, 60); + // Files written before the envelope v2 transition omit this key. + assert!(!config.sync.legacy_envelopes); assert!(!config.notify.enabled); assert!(config.notify.preview); let webhook = config.webhook.as_ref().unwrap(); @@ -85,6 +87,8 @@ fn supported_configuration_keys_roundtrip_and_unknown_keys_do_not_mutate() { ("notify.enabled", "1", "true"), ("notify.preview", "on", "true"), ("sync.ttl_secs", "60", "60"), + ("sync.legacy_envelopes", "on", "true"), + ("sync.legacy_envelopes", "no", "false"), ] { assert!(config.set(key, value)); assert_eq!(config.get(key).as_deref(), Some(expected)); diff --git a/crates/clipsync-transfer/Cargo.toml b/crates/clipsync-transfer/Cargo.toml index 3116a31..fa56acf 100644 --- a/crates/clipsync-transfer/Cargo.toml +++ b/crates/clipsync-transfer/Cargo.toml @@ -22,4 +22,5 @@ ulid.workspace = true workspace = true [dev-dependencies] +chrono.workspace = true tempfile.workspace = true diff --git a/crates/clipsync-transfer/src/lib.rs b/crates/clipsync-transfer/src/lib.rs index a2d57e6..c29e1f8 100644 --- a/crates/clipsync-transfer/src/lib.rs +++ b/crates/clipsync-transfer/src/lib.rs @@ -11,7 +11,8 @@ pub use staging::{prune_idle_transfers, IncomingTransfer, StagingArea}; use clipsync_crypto::{blake3_hex, derive_content_key, derive_nonce, open, seal}; use clipsync_protocol::{ - decode_chunk_frame, encode_chunk_frame, ChunkFrame, TransferId, CHUNK_SIZE, FRAME_HARD_CAP, + decode_chunk_frame, encode_chunk_frame, envelope_aad, ChunkFrame, EnvelopeFrame, RoutingHeader, + TransferId, AEAD_NONCE_LEN, CHUNK_SIZE, FRAME_HARD_CAP, }; #[derive(Debug, thiserror::Error)] @@ -44,11 +45,13 @@ pub struct OutgoingChunks { pub chunk_count: u32, } +/// Encrypt `payload` as chunk frames bound to `routing` under its envelope version. pub fn split_and_encrypt( epoch_key: &[u8; 32], - transfer_id: &TransferId, + routing: &RoutingHeader, payload: &[u8], ) -> Result { + let transfer_id = &routing.transfer_id; let content_key = derive_content_key(epoch_key, transfer_id.as_str())?; let content_hash = blake3_hex(payload); let chunks: Vec<&[u8]> = if payload.is_empty() { @@ -59,13 +62,20 @@ pub fn split_and_encrypt( let chunk_count = chunks.len() as u32; let mut frames = Vec::with_capacity(chunks.len()); for (i, chunk) in chunks.iter().enumerate() { - let nonce = derive_nonce(&content_key, i as u32)?; - let aad = aad_bytes(transfer_id, i as u32); + let index = i as u32; + let nonce = derive_nonce(&content_key, index)?; + let aad = envelope_aad( + routing, + EnvelopeFrame::Chunk { + index, + count: chunk_count, + }, + )?; let mut ct = nonce.to_vec(); ct.extend(seal(&content_key, &nonce, &aad, chunk)?); let frame = encode_chunk_frame(&ChunkFrame { transfer_id: transfer_id.clone(), - chunk_index: i as u32, + chunk_index: index, chunk_count, ciphertext: ct, })?; @@ -85,19 +95,14 @@ pub fn split_and_encrypt( }) } +/// Decode and decrypt one chunk frame of the transfer announced by `routing`. pub fn decrypt_chunk( epoch_key: &[u8; 32], + routing: &RoutingHeader, frame: &[u8], ) -> Result<(TransferId, u32, u32, Vec)> { let decoded = decode_chunk_frame(frame)?; - let content_key = derive_content_key(epoch_key, decoded.transfer_id.as_str())?; - if decoded.ciphertext.len() < 12 { - return Err(TransferError::Chunk("ciphertext too short")); - } - let mut nonce = [0u8; 12]; - nonce.copy_from_slice(&decoded.ciphertext[..12]); - let aad = aad_bytes(&decoded.transfer_id, decoded.chunk_index); - let pt = open(&content_key, &nonce, &aad, &decoded.ciphertext[12..])?; + let pt = open_chunk(epoch_key, routing, &decoded)?; Ok(( decoded.transfer_id, decoded.chunk_index, @@ -106,66 +111,185 @@ pub fn decrypt_chunk( )) } -pub fn aad_bytes(transfer_id: &TransferId, chunk_index: u32) -> Vec { - let mut aad = transfer_id.as_str().as_bytes().to_vec(); - aad.extend_from_slice(&chunk_index.to_be_bytes()); - aad +/// Decrypt a decoded chunk frame. The AAD binds the frame's index and count to +/// the manifest's routing header (v2) or to its transfer ID (legacy v1). +pub fn open_chunk( + epoch_key: &[u8; 32], + routing: &RoutingHeader, + frame: &ChunkFrame, +) -> Result> { + if frame.transfer_id != routing.transfer_id { + return Err(TransferError::Chunk("chunk belongs to another transfer")); + } + let content_key = derive_content_key(epoch_key, frame.transfer_id.as_str())?; + if frame.ciphertext.len() < AEAD_NONCE_LEN { + return Err(TransferError::Chunk("ciphertext too short")); + } + let mut nonce = [0u8; AEAD_NONCE_LEN]; + nonce.copy_from_slice(&frame.ciphertext[..AEAD_NONCE_LEN]); + let aad = envelope_aad( + routing, + EnvelopeFrame::Chunk { + index: frame.chunk_index, + count: frame.chunk_count, + }, + )?; + Ok(open( + &content_key, + &nonce, + &aad, + &frame.ciphertext[AEAD_NONCE_LEN..], + )?) } #[cfg(test)] #[cfg_attr(coverage_nightly, coverage(off))] mod tests { use super::*; + use chrono::{Duration, Utc}; use clipsync_crypto::blake3_hex as hash_hex; + use clipsync_protocol::{ + DeviceId, ItemKind, MessageId, Recipient, RoomId, ENVELOPE_VERSION_AUTHENTICATED, + ENVELOPE_VERSION_LEGACY, + }; + + fn routing(version: u16) -> RoutingHeader { + let now = Utc::now(); + RoutingHeader { + version, + message_id: MessageId::new(), + transfer_id: TransferId::new(), + room_id: RoomId::new(), + sender_device_id: DeviceId::new(), + recipient: Recipient::Broadcast, + sent_at: now, + expires_at: now + Duration::seconds(60), + item_kind: ItemKind::Image, + seq: 1, + } + } #[test] fn chunk_roundtrip() { let epoch = [7u8; 32]; - let id = TransferId::new(); - let payload = vec![9u8; 300 * 1024]; - let out = split_and_encrypt(&epoch, &id, &payload).unwrap(); - assert!(out.chunk_count >= 2); - let mut assembled = Vec::new(); - let mut seen = std::collections::BTreeMap::new(); - for frame in &out.frames { - let (tid, idx, count, pt) = decrypt_chunk(&epoch, frame).unwrap(); - assert_eq!(tid, id); - assert_eq!(count, out.chunk_count); - seen.insert(idx, pt); + for version in [ENVELOPE_VERSION_LEGACY, ENVELOPE_VERSION_AUTHENTICATED] { + let routing = routing(version); + let payload = vec![9u8; 300 * 1024]; + let out = split_and_encrypt(&epoch, &routing, &payload).unwrap(); + assert!(out.chunk_count >= 2); + let mut assembled = Vec::new(); + let mut seen = std::collections::BTreeMap::new(); + for frame in &out.frames { + let (tid, idx, count, pt) = decrypt_chunk(&epoch, &routing, frame).unwrap(); + assert_eq!(tid, routing.transfer_id); + assert_eq!(count, out.chunk_count); + seen.insert(idx, pt); + } + for i in 0..out.chunk_count { + assembled.extend(seen.get(&i).unwrap()); + } + assert_eq!(assembled, payload); + assert_eq!(hash_hex(&assembled), out.content_hash); + } + } + + #[test] + fn legacy_chunks_keep_the_v1_aad() { + let epoch = [3u8; 32]; + let routing = routing(ENVELOPE_VERSION_LEGACY); + let key = derive_content_key(&epoch, routing.transfer_id.as_str()).unwrap(); + let nonce = derive_nonce(&key, 0).unwrap(); + let mut aad = routing.transfer_id.as_str().as_bytes().to_vec(); + aad.extend_from_slice(&0u32.to_be_bytes()); + let mut ciphertext = nonce.to_vec(); + ciphertext.extend(seal(&key, &nonce, &aad, b"legacy").unwrap()); + let frame = encode_chunk_frame(&ChunkFrame { + transfer_id: routing.transfer_id.clone(), + chunk_index: 0, + chunk_count: 1, + ciphertext, + }) + .unwrap(); + assert_eq!( + decrypt_chunk(&epoch, &routing, &frame).unwrap().3, + b"legacy" + ); + } + + #[test] + fn authenticated_chunks_reject_any_routing_or_frame_header_change() { + let epoch = [5u8; 32]; + let honest = routing(ENVELOPE_VERSION_AUTHENTICATED); + let out = split_and_encrypt(&epoch, &honest, &vec![1u8; CHUNK_SIZE + 1]).unwrap(); + let mut changed: Vec = Vec::new(); + for change in [ + (|r: &mut RoutingHeader| r.room_id = RoomId::new()) as fn(&mut RoutingHeader), + |r| r.sender_device_id = DeviceId::new(), + |r| r.recipient = Recipient::Device(DeviceId::new()), + |r| r.message_id = MessageId::new(), + |r| r.sent_at -= Duration::seconds(1), + |r| r.expires_at += Duration::seconds(1), + |r| r.item_kind = ItemKind::Files, + |r| r.seq += 1, + |r| r.version = ENVELOPE_VERSION_LEGACY, + ] { + let mut routing = honest.clone(); + change(&mut routing); + changed.push(routing); } - for i in 0..out.chunk_count { - assembled.extend(seen.get(&i).unwrap()); + for routing in &changed { + assert!( + decrypt_chunk(&epoch, routing, &out.frames[0]).is_err(), + "{routing:?}" + ); } - assert_eq!(assembled, payload); - assert_eq!(hash_hex(&assembled), out.content_hash); + let mut other_transfer = honest.clone(); + other_transfer.transfer_id = TransferId::new(); + assert!(matches!( + decrypt_chunk(&epoch, &other_transfer, &out.frames[0]), + Err(TransferError::Chunk("chunk belongs to another transfer")) + )); + let mut frame = decode_chunk_frame(&out.frames[1]).unwrap(); + frame.chunk_index = 0; + assert!(open_chunk(&epoch, &honest, &frame).is_err(), "reordered"); + let mut frame = decode_chunk_frame(&out.frames[1]).unwrap(); + frame.chunk_count = 3; + assert!(open_chunk(&epoch, &honest, &frame).is_err(), "recounted"); + let mut unknown = honest; + unknown.version = ENVELOPE_VERSION_AUTHENTICATED + 1; + assert!(matches!( + decrypt_chunk(&epoch, &unknown, &out.frames[0]), + Err(TransferError::Protocol(_)) + )); } #[test] fn empty_transfers_have_one_authenticated_chunk_and_short_or_tampered_chunks_fail() { let epoch = [19; 32]; - let id = TransferId::new(); - let outgoing = split_and_encrypt(&epoch, &id, &[]).unwrap(); + let routing = routing(ENVELOPE_VERSION_AUTHENTICATED); + let id = routing.transfer_id.clone(); + let outgoing = split_and_encrypt(&epoch, &routing, &[]).unwrap(); assert_eq!(outgoing.chunk_count, 1); assert_eq!(outgoing.total_bytes, 0); assert_eq!( - decrypt_chunk(&epoch, &outgoing.frames[0]).unwrap(), + decrypt_chunk(&epoch, &routing, &outgoing.frames[0]).unwrap(), (id.clone(), 0, 1, vec![]) ); let short = encode_chunk_frame(&ChunkFrame { transfer_id: id, chunk_index: 0, chunk_count: 1, - ciphertext: vec![0; 11], + ciphertext: vec![0; AEAD_NONCE_LEN - 1], }) .unwrap(); assert!(matches!( - decrypt_chunk(&epoch, &short), + decrypt_chunk(&epoch, &routing, &short), Err(TransferError::Chunk("ciphertext too short")) )); let mut changed = outgoing.frames[0].clone(); *changed.last_mut().unwrap() ^= 1; assert!(matches!( - decrypt_chunk(&epoch, &changed), + decrypt_chunk(&epoch, &routing, &changed), Err(TransferError::Aead(_)) )); } diff --git a/docs/interfaces.md b/docs/interfaces.md index 2b17621..a9a3fb0 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -101,7 +101,8 @@ not printed. Clipboard write failures in `pull --copy` are currently best effort The full configuration has `relay_url: string`, `sync: {enabled, auto_start: boolean, direction: "both"|"send_only"|"receive_only", types: string[], -debounce_ms, ttl_secs: unsigned integer}`, `notify: {enabled, preview: boolean}`, +debounce_ms, ttl_secs: unsigned integer, legacy_envelopes: boolean}`, `notify: +{enabled, preview: boolean}`, and `webhook: null|{url: string, secret: string}`. [Configuration source](../crates/clipsync-storage/src/config.rs) defines these records and defaults; [stored records](../crates/clipsync-storage/src/store.rs) @@ -114,6 +115,7 @@ define room/peer output. | `notify.preview` | Same boolean syntax; default false. | | `sync.direction` | `both`, `send-only`/`send_only`, `receive-only`/`receive_only`; default `both`. Single-key `get` currently returns `sendonly`/`receiveonly`, while full JSON uses underscores. | | `sync.ttl_secs` | Unsigned seconds, clamped to 10–300; default 60. Current sending code uses 60 regardless of this setting. | +| `sync.legacy_envelopes` | Same boolean syntax; default false. True makes this device send legacy v1 envelopes so peers that have not been updated can still read them; see [envelope versions](protocol.md#envelope-versions). Receiving is unaffected. | `sync.types` (default text/image/files), `sync.debounce_ms` (default 200), and `webhook` appear in the full config but have no `config set` key. An unknown key @@ -266,7 +268,7 @@ null transfer ID. Peers can emit further acknowledgements. | Nested record | Fields / representation | | --- | --- | | `PeerInfo` | `device_id`, `device_name`, `os: string`; `role: DeviceRole`; `online: boolean`. | -| `RoutingHeader` | `version: u16`; `message_id`, `transfer_id`, `room_id`, `sender_device_id: string`; `recipient`: `"broadcast"` or `{"device":"DEVICE_ID"}`; `sent_at`, `expires_at: time`; `item_kind`: `text`/`image`/`files`; `seq: u64`. | +| `RoutingHeader` | `version: u16` (envelope version: 1 legacy, 2 authenticated; see [protocol](protocol.md#envelope-versions)); `message_id`, `transfer_id`, `room_id`, `sender_device_id: string`; `recipient`: `"broadcast"` or `{"device":"DEVICE_ID"}`; `sent_at`, `expires_at: time`; `item_kind`: `text`/`image`/`files`; `seq: u64`. | | `QueuedEnvelope` | `routing: RoutingHeader`, `nonce`, `ciphertext: string`. | | `EpochWrap` | `device_id`, `eph_public`, `nonce`, `ciphertext: string`. | diff --git a/docs/protocol.md b/docs/protocol.md index 5e19e25..066a9a7 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -32,7 +32,8 @@ Tagged `type` field: `hello`, `hello_ok`, `peer_joined`, `peer_left`, Relay-visible routing header includes room/device IDs, transfer ID, chunk index, item kind, timestamps. File names, MIME types, hashes, and dimensions -live only in the encrypted manifest. +live only in the encrypted manifest. The relay can read the routing header; +under envelope v2 it cannot change it undetected (see below). ## Binary chunk frames @@ -41,6 +42,96 @@ magic "CSY1" | version u8 | type u8=2 | transfer_id 16 | chunk_index u32be | chunk_count u32be | ciphertext_len u32be | nonce||ciphertext ``` +The frame layout (and its version byte, 1) is the same for both envelope +versions; only the AEAD associated data differs. + +## Envelope versions + +`RoutingHeader.version` selects the AEAD associated data (AAD) for the text +envelope, manifest, and chunk frames of one clipboard item. It is separate from +`hello.protocol_version`, which stays `1` so updated clients keep working with +existing relays; relays forward routing headers unchanged. + +| `version` | AAD | Header fields authenticated | +| --- | --- | --- | +| 1 (legacy) | text `"{message_id}:text"`; manifest `"{transfer_id}:manifest"`; chunk `transfer_id \|\| u32be(chunk_index)` | message ID (text) or transfer ID only | +| 2 (authenticated) | canonical header encoding below | all fields | + +Version 2 AAD, where `lp(x) = u64be(byte_len(x)) || utf8(x)`: + +``` +"clipsync-envelope-v2" || u16be(version) +|| lp(message_id) || lp(transfer_id) || lp(room_id) || lp(sender_device_id) +|| recipient: 0x00 (broadcast) | 0x01 || lp(device_id) +|| i64be(sent_at Unix seconds) || u32be(sent_at nanoseconds) +|| i64be(expires_at Unix seconds) || u32be(expires_at nanoseconds) +|| item_kind: 0x00 text | 0x01 image | 0x02 files +|| u64be(seq) +|| frame: 0x00 text | 0x01 manifest | 0x02 || u32be(chunk_index) || u32be(chunk_count) +``` + +Chunk frames carry no routing header. A receiver opens a chunk only for a +transfer whose manifest it accepted, using that manifest's header, so a v2 +chunk is bound to the header, its position, and the chunk count. + +### Receiver checks + +Every text envelope and manifest, of either version, is rejected unless: + +1. `version` is 1 or 2; +2. `room_id` is the receiver's current room; +3. `recipient` is `broadcast` or the receiver's device ID; +4. `sender_device_id` is a pinned peer of the room and not the receiver; +5. `item_kind` is `text` for a text envelope, and a decrypted manifest + describes the same `item_kind` as its header; +6. `sent_at` is at most `CLOCK_SKEW_SECS` (30 s) in the future, `expires_at` + at most 30 s in the past, and `expires_at - sent_at` at most 300 s; +7. a v1 envelope does not come from a sender that has already delivered a v2 + envelope to this device (downgrade); +8. AEAD opens; +9. for v2, `seq` is strictly greater than the highest `seq` previously accepted + from that sender in that room. The new value is stored durably before the + item is applied. It is stored only after AEAD succeeds, so a forged header + cannot raise it. + +For v2, AEAD authenticates every value checks 1–6 read. For v1 the same checks +run on values a relay can rewrite, and step 9 does not apply. + +### Sequence numbers and replay state + +Senders use `seq = max(last_sent + 1, current Unix time in microseconds)` per +room and store it before sending. Numbers therefore keep increasing across +restarts, a clock stepping back, a deleted state file, and a daemon and one-shot +push sending at once. Receivers store, per room and sender, the highest accepted +v2 `seq` and whether the sender has used v2. + +Both live in `replay-state.json` in the private data directory (mode `0600` on +Unix). Missing fields default, so older or partial files load. An unreadable +file stops sending and receiving with an error instead of being reset; deleting +it limits replay protection to the expiry window until each sender's next +envelope is accepted. + +Because acceptance is strictly increasing, an older item that arrives after a +newer one from the same sender is dropped. One relay connection delivers in +order; this can affect two processes of one device sending concurrently. + +### Transition from v1 + +- Updated devices send v2 by default. +- Updated receivers always accept v2. They accept v1 from a sender only until + they accept a v2 envelope from that sender. The state is stored, so the sender + cannot be downgraded later, including after a restart. v1 envelopes still get + checks 1–6 on unauthenticated values and only the in-memory message-ID cache + (120 s) against replay: legacy senders restart `seq` at 1 every session. +- Devices from before this change cannot decrypt v2. They log a decryption + failure and drop the item. Update both devices of a room. To keep an + updated device readable by a not-yet-updated peer, set + `sync.legacy_envelopes = true` on the updated device and restart its daemon. + This affects sending only. Set it back to `false` after the peer is updated. + Enable it only while the peer is not updated: an updated peer that has + already received v2 from this device rejects its later v1 envelopes as a + downgrade. + ## Pairing transcript ``` @@ -60,5 +151,8 @@ HKDF-SHA-256 labels: ## Reconnect -Noise pattern `Noise_KK_25519_AESGCM_SHA256` using long-term X25519 device -keys. Payload encryption continues to use the current `roomEpochKey`. +When a pinned peer is online, clients run `Noise_KK_25519_AESGCM_SHA256` with +their long-term X25519 device keys. The handshake result is currently unused: +no payload is encrypted under the Noise session, and sync neither waits for nor +depends on a completed handshake. Payload encryption uses the current +`roomEpochKey` and the envelope AAD above. diff --git a/docs/security.md b/docs/security.md index d56afc2..951da86 100644 --- a/docs/security.md +++ b/docs/security.md @@ -29,11 +29,44 @@ receivers decrypt using the nonce carried by the v1 message. This prevents the two updated pairing participants, or a legacy/updated pair, from encrypting different binding messages with the same key and nonce. +## Envelope authenticity, expiry, and replay + +Envelope v2 (see [protocol](protocol.md#envelope-versions)) authenticates the +whole routing header: version, message and transfer IDs, room, sender, +recipient, `sent_at`, `expires_at`, item kind, and `seq`. It binds each chunk to +that header, its index, and the chunk count. A relay that rewrites any of these +fields makes AEAD fail. Receivers reject envelopes for another room or +recipient, from a sender that is not a pinned room peer, or past +`expires_at` (with a 30-second clock-skew tolerance). They also reject a `seq` +that is not newer than the last accepted one from the same sender. That +high-water mark is stored in the private data directory, so a replay is +rejected after the in-memory cache expires and after a daemon restart. + +Limits: + +- Sender identity is not cryptographically bound to a device. Every room + member holds the same epoch key, so any member can produce a valid envelope + that names any `sender_device_id`. What v2 adds is that the relay, which + lacks the key, cannot change the claimed sender. Receivers accept only + pinned peers other than themselves; in a two-device room that is the other + device. No per-device signature is added. +- Legacy v1 envelopes authenticate only the message or transfer ID. Updated + receivers accept them from a sender until that sender's first v2 envelope; + later v1 envelopes from it are rejected as a downgrade. Until then, a relay + can replay a recorded v1 envelope after the 120-second in-memory window or a + restart, and extend its expiry. v1 checks run on unauthenticated values. +- An older item that arrives after a newer one from the same sender is dropped. + Delivery and ordering by a malicious relay are not guaranteed: it can still + drop or delay envelopes within their lifetime. +- Deleting `replay-state.json` resets the high-water marks. Replay protection + then falls back to the expiry window until each sender's next accepted + envelope. + ## Keys | Key | Purpose | | --- | --- | -| Device X25519 | Long-term identity, Noise static key, epoch wrap | +| Device X25519 | Long-term identity, Noise static key (handshake only), epoch wrap | | `roomRootKey` | First-epoch derivation only | | `roomEpochKey` | Payload AEAD; current clients retain the initial key until re-pairing | | Per-transfer content key | HKDF from epoch key + transfer ID | @@ -42,9 +75,13 @@ The relay rejects revoked device tokens. The crypto library provides epoch-key wrapping, but the current client does not automatically rotate room keys on membership changes. Re-pair to establish a new room key. -Full forward secrecy for stored payloads is not provided. Noise handshakes use -ephemeral keys, but payloads continue to use persistent room epoch keys; -compromise of an epoch secret exposes the payload keys derived from it. The +Full forward secrecy for stored payloads is not provided. When both devices are +online they run a Noise `KK` handshake with their long-term keys. Its result is +currently unused: payloads are not encrypted under the Noise session, sync does +not wait for it, and a missing or failed handshake does not stop sync. Noise +therefore provides no payload confidentiality, integrity, sender +authentication, or forward secrecy here. Payloads use persistent room epoch +keys; compromise of an epoch secret exposes the payload keys derived from it. The library's epoch-wrapping mechanism also allows a recorded wrap to be decrypted after compromise of the recipient's long-term identity. Treat device and room secrets as sensitive, and re-pair to replace old room keys. @@ -72,6 +109,11 @@ mode `0600` on Unix. Unix data/inbox directories use `0700`; Windows relies on the user's profile-directory access controls rather than POSIX modes. Received filenames are sanitized to basenames. +`replay-state.json` in the data directory holds envelope sequence numbers, not +secrets. It is written atomically as a private file. Its integrity matters +for replay protection (see above). An unreadable file stops sync with an error +instead of being reset. + Device tokens are stored separately as `device-token-.secret`; webhook credentials use `webhook.secret`. These credentials use canonical private files without OS-keychain fallback; missing or empty files are errors. New `state.json` and `config.toml` serialization omits these values. Loading a legacy inline credential writes diff --git a/fuzz/fuzz_targets/protocol.rs b/fuzz/fuzz_targets/protocol.rs index 649bef5..fab12ed 100644 --- a/fuzz/fuzz_targets/protocol.rs +++ b/fuzz/fuzz_targets/protocol.rs @@ -2,7 +2,10 @@ // Copyright the ClipSync contributors. // SPDX-License-Identifier: MIT -use clipsync_protocol::{decode_chunk_frame, encode_chunk_frame, ControlMessage}; +use clipsync_protocol::{ + decode_chunk_frame, encode_chunk_frame, envelope_aad, ControlMessage, EnvelopeFrame, + RoutingHeader, +}; use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { @@ -16,6 +19,37 @@ fuzz_target!(|data: &[u8]| { let encoded = message.encode().expect("decoded message must encode"); let decoded = ControlMessage::decode(&encoded).expect("encoded message must decode"); assert_eq!(message, decoded); + if let Some(routing) = routing_of(&message) { + check_aad(routing); + } } } }); + +fn routing_of(message: &ControlMessage) -> Option<&RoutingHeader> { + match message { + ControlMessage::TextEnvelope { routing, .. } | ControlMessage::Manifest { routing, .. } => { + Some(routing) + } + ControlMessage::HelloOk { + queued_text: Some(queued), + .. + } => Some(&queued.routing), + _ => None, + } +} + +/// Untrusted headers must yield deterministic AAD (or a version error), never panic. +fn check_aad(routing: &RoutingHeader) { + for frame in [ + EnvelopeFrame::Text, + EnvelopeFrame::Manifest, + EnvelopeFrame::Chunk { + index: routing.seq as u32, + count: u32::MAX, + }, + ] { + let first = envelope_aad(routing, frame).ok(); + assert_eq!(first, envelope_aad(routing, frame).ok()); + } +} diff --git a/fuzz/seeds/protocol/text-envelope-v2.json b/fuzz/seeds/protocol/text-envelope-v2.json new file mode 100644 index 0000000..2823c13 --- /dev/null +++ b/fuzz/seeds/protocol/text-envelope-v2.json @@ -0,0 +1 @@ +{"type":"text_envelope","routing":{"version":2,"message_id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","transfer_id":"01ARZ3NDEKTSV4RRFFQ69G5FAW","room_id":"01ARZ3NDEKTSV4RRFFQ69G5FAX","sender_device_id":"01ARZ3NDEKTSV4RRFFQ69G5FAY","recipient":"broadcast","sent_at":"2026-11-15T00:00:00.123456789Z","expires_at":"2026-11-15T00:01:00.123456789Z","item_kind":"text","seq":1763164800123456},"nonce":"000000000000000000000000","ciphertext":"00"} \ No newline at end of file