From b8f5b5563b8cfdbc8262cfb5f5004c6847c7c4e7 Mon Sep 17 00:00:00 2001 From: develicit <16333003+Jeon1691@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:36:58 +0900 Subject: [PATCH] fix(pairing): require SAS confirmation before committing a pairing Derive a 6-digit short authentication string from the SPAKE2 secret and transcript (HKDF label clipsync/v1/sas). Send DeviceBind and persist room keys, room record, and credentials only after the local user confirms that both devices show the same code; rejection or timeout stores nothing. Add CLI prompts, room confirm/reject for background create, and --insecure-skip-sas; a desktop verification panel; and a mobile SasVerifier callback API while keeping the existing exports. No wire or relay change. --- Cargo.lock | 1 + README.md | 26 +- crates/clipsync-cli/src/cli.rs | 21 +- crates/clipsync-cli/src/main.rs | 88 ++- crates/clipsync-cli/src/pairing_bg.rs | 25 +- crates/clipsync-cli/src/sas_prompt.rs | 463 +++++++++++++ .../clipsync-cli/tests/background_create.rs | 347 +++++++++- crates/clipsync-core/src/lib.rs | 44 +- crates/clipsync-core/src/pairing.rs | 626 ++++++++++++++++-- .../tests/support/engine_behavior.rs | 59 +- .../tests/support/facade_behavior.rs | 33 +- crates/clipsync-crypto/Cargo.toml | 2 + crates/clipsync-crypto/src/lib.rs | 5 +- crates/clipsync-crypto/src/pairing.rs | 242 +++++++ crates/clipsync-crypto/tests/wire_contract.rs | 1 + crates/clipsync-desktop/src/lib.rs | 122 +++- crates/clipsync-desktop/src/main.rs | 199 +++++- crates/clipsync-mobile/src/lib.rs | 384 ++++++++++- crates/clipsync-relay/src/ws_tests.rs | 22 + crates/clipsync-relay/tests/e2e.rs | 185 +++++- crates/clipsync-storage/src/store.rs | 24 +- docs/assurance-case.md | 7 +- docs/interfaces.md | 30 +- docs/mobile.md | 4 + docs/protocol.md | 22 + docs/security.md | 71 +- scripts/e2e-brew.py | 62 +- scripts/local-two-homes.sh | 3 +- 28 files changed, 2922 insertions(+), 196 deletions(-) create mode 100644 crates/clipsync-cli/src/sas_prompt.rs diff --git a/Cargo.lock b/Cargo.lock index 63d4e5d..311347b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1038,6 +1038,7 @@ dependencies = [ "hkdf 0.13.0", "hmac 0.13.0", "rand 0.9.5", + "rand_core 0.6.4", "serde", "serde_json", "sha2 0.11.1", diff --git a/README.md b/README.md index 096cb5c..ae5790b 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,25 @@ On device B (another machine, or another `CLIPSYNC_HOME`): clipsync room join 482913 ``` +Both devices then show a 6-digit verification code. On device A: + +```bash +clipsync room confirm +``` + +Check that the two codes are the same, then confirm on both devices (type the +code shown on the other device, or `yes`). If they differ, answer anything +else, or run `clipsync room reject` on A: pairing stops and nothing is stored. +A mismatch means something other than your device joined, for example a relay +in the middle or someone who guessed the code. With `--foreground`, device A +asks in the same terminal instead of `room confirm`. + +For scripts, `clipsync room confirm ` compares non-interactively, and +`room join` reads its answer from stdin. `--insecure-skip-sas` on +`room create` / `room join` skips the comparison and removes that protection; +use it only for test setups on a relay you trust. Devices on a version without +verification codes still pair, but cannot show a code to compare. + `clipsync init` is optional. Identity is created on Homebrew install and on first use. @@ -166,8 +185,10 @@ clipsync status ``` clipsync init [--relay-url URL] # optional; also runs on install and first use -clipsync room create [--ttl 10m] [--no-auto-sync] [--foreground] -clipsync room join [--no-auto-sync] +clipsync room create [--ttl 10m] [--no-auto-sync] [--foreground] [--insecure-skip-sas] +clipsync room join [--no-auto-sync] [--insecure-skip-sas] +clipsync room confirm [CODE] # answer the verification code of a background create +clipsync room reject clipsync room leave --yes clipsync room list clipsync push [--type auto|text|image|files] [--file ...] @@ -217,6 +238,7 @@ clipsync room create - SPAKE2 balanced PAKE; the 6-digit code is only a one-time password - Mutual key confirmation bound to protocol version, session, device IDs, and SPAKE2 transcript +- 6-digit verification code compared on both devices before anything is stored; it catches a guessed code or a relay in the middle, except a relay that searches offline for matching codes (see docs/security.md) - AES-256-GCM payloads, HKDF-SHA-256, X25519 device identity - Noise `KK` handshake on reconnect - Text latest-one in-memory queue, 60s TTL; images/files are online-only 256 KiB chunks diff --git a/crates/clipsync-cli/src/cli.rs b/crates/clipsync-cli/src/cli.rs index 4e5a755..9f277df 100644 --- a/crates/clipsync-cli/src/cli.rs +++ b/crates/clipsync-cli/src/cli.rs @@ -73,7 +73,8 @@ pub enum Commands { #[derive(Debug, Subcommand)] pub enum RoomCmd { - /// Create a pairing room and print a 6-digit join code (waits in the background) + /// Create a pairing room and print a 6-digit join code (waits in the background; + /// confirm the verification code with `clipsync room confirm`) Create { /// How long the code stays valid (e.g. 2m) #[arg(long)] @@ -90,12 +91,30 @@ pub enum RoomCmd { /// Internal worker used by background room create #[arg(long, hide = true)] background_worker: bool, + /// Pair without comparing the verification code. This removes the + /// protection against a malicious relay or a guessed pairing code; + /// use it only for scripted setups on a network and relay you trust. + #[arg(long)] + insecure_skip_sas: bool, }, + /// Join with a 6-digit code, then confirm the verification code both devices show Join { code: String, #[arg(long)] no_auto_sync: bool, + /// Pair without comparing the verification code. This removes the + /// protection against a malicious relay or a guessed pairing code; + /// use it only for scripted setups on a network and relay you trust. + #[arg(long)] + insecure_skip_sas: bool, + }, + /// Confirm the verification code of a background `room create` + Confirm { + /// Code shown on the other device; prompts when omitted + code: Option, }, + /// Reject a background `room create` whose verification code does not match + Reject, Leave { #[arg(long)] yes: bool, diff --git a/crates/clipsync-cli/src/main.rs b/crates/clipsync-cli/src/main.rs index f3f62e6..c3e1401 100644 --- a/crates/clipsync-cli/src/main.rs +++ b/crates/clipsync-cli/src/main.rs @@ -3,6 +3,7 @@ mod cli; mod output; mod pairing_bg; +mod sas_prompt; use std::io::{self, Write}; @@ -15,6 +16,7 @@ use clipsync_storage::LocalStore; use crate::cli::{Cli, Commands, ConfigCmd, DaemonCmd, RoomCmd, SyncCmd}; use crate::output::{emit, emit_err}; +use crate::sas_prompt::{answer_background, background_confirmer, terminal_confirmer, SasMode}; #[tokio::main] async fn main() { @@ -76,6 +78,7 @@ async fn run(cli: Cli) -> Result<(), CoreError> { foreground, background: _, background_worker, + insecure_skip_sas, }) => { let app = App::open()?; let _ = app.identity()?; @@ -90,30 +93,46 @@ async fn run(cli: Cli) -> Result<(), CoreError> { &app, ttl_raw.as_deref(), no_auto_sync, + insecure_skip_sas, json, ) .await; } - let offer = app - .room_create(dur, no_auto_sync, json, |offer| { - if json { - println!( - "{}", - serde_json::json!({ - "event": "pairing_code", - "pairing_code": offer.pairing_code, - "room_id": offer.room_id, - "expires_at": offer.expires_at, - }) - ); - } else { - println!("pairing code: {}", offer.pairing_code); - println!("room: {}", offer.room_id); - println!("expires: {}", offer.expires_at); - println!("waiting for the other device to join…"); - } - let _ = io::stdout().flush(); + let confirm = if background_worker { + background_confirmer(app.store.clone(), insecure_skip_sas) + } else { + terminal_confirmer(SasMode { + json, + non_interactive: cli.non_interactive, + skip: insecure_skip_sas, }) + }; + let offer = app + .room_create( + dur, + no_auto_sync, + json, + |offer| { + if json { + println!( + "{}", + serde_json::json!({ + "event": "pairing_code", + "pairing_code": offer.pairing_code, + "room_id": offer.room_id, + "expires_at": offer.expires_at, + }) + ); + } else { + println!("pairing code: {}", offer.pairing_code); + println!("room: {}", offer.room_id); + println!("expires: {}", offer.expires_at); + println!("waiting for the other device to join…"); + } + let _ = io::stdout().flush(); + }, + confirm, + ) .await?; emit( json, @@ -128,9 +147,18 @@ async fn run(cli: Cli) -> Result<(), CoreError> { } Ok(()) } - Commands::Room(RoomCmd::Join { code, no_auto_sync }) => { + Commands::Room(RoomCmd::Join { + code, + no_auto_sync, + insecure_skip_sas, + }) => { let app = App::open()?; - let room = app.room_join(&code, no_auto_sync).await?; + let confirm = terminal_confirmer(SasMode { + json: cli.json, + non_interactive: cli.non_interactive, + skip: insecure_skip_sas, + }); + let room = app.room_join(&code, no_auto_sync, confirm).await?; emit( cli.json, serde_json::json!({"room_id": room.room_id, "role": room.role}), @@ -140,6 +168,24 @@ async fn run(cli: Cli) -> Result<(), CoreError> { } Ok(()) } + Commands::Room(RoomCmd::Confirm { code }) => { + let app = App::open()?; + let mode = SasMode { + json: cli.json, + non_interactive: cli.non_interactive, + skip: false, + }; + answer_background(&app, code.as_deref(), false, mode).await + } + Commands::Room(RoomCmd::Reject) => { + let app = App::open()?; + let mode = SasMode { + json: cli.json, + non_interactive: cli.non_interactive, + skip: false, + }; + answer_background(&app, None, true, mode).await + } Commands::Room(RoomCmd::Leave { yes }) => { if !yes && !cli.yes && !cli.non_interactive { eprintln!("pass --yes to leave the current room"); diff --git a/crates/clipsync-cli/src/pairing_bg.rs b/crates/clipsync-cli/src/pairing_bg.rs index 16a555e..d117915 100644 --- a/crates/clipsync-cli/src/pairing_bg.rs +++ b/crates/clipsync-cli/src/pairing_bg.rs @@ -17,13 +17,22 @@ pub async fn spawn_background_create( app: &App, ttl: Option<&str>, no_auto_sync: bool, + insecure_skip_sas: bool, json: bool, ) -> Result<(), CoreError> { if let Ok(Some(existing)) = app.store.load_pairing_wait() { - if existing.status == "waiting" && pid_alive(existing.pid) { + let active = existing.status == "waiting" + || existing.status == crate::sas_prompt::STATUS_CONFIRM_SAS; + if active && !crate::sas_prompt::replaceable(&existing) { + let next = if existing.status == "waiting" { + format!("join with: clipsync room join {}", existing.pairing_code) + } else { + "a device joined; compare codes with: clipsync room confirm (or clipsync room reject)" + .into() + }; return Err(CoreError::Message(format!( - "pairing already waiting in background (pid {}); join with: clipsync room join {}", - existing.pid, existing.pairing_code + "pairing already waiting in background (pid {}); {next}", + existing.pid ))); } } @@ -47,6 +56,9 @@ pub async fn spawn_background_create( if no_auto_sync { cmd.arg("--no-auto-sync"); } + if insecure_skip_sas { + cmd.arg("--insecure-skip-sas"); + } if let Ok(home) = std::env::var("CLIPSYNC_HOME") { cmd.env("CLIPSYNC_HOME", home); } @@ -122,6 +134,7 @@ fn print_offer(wait: &PairingWait, pid: u32, json: bool) { "join from another device: clipsync room join {}", wait.pairing_code ); + println!("then compare verification codes here: clipsync room confirm"); } } @@ -135,7 +148,7 @@ fn extract_error_line(text: &str) -> Option { } #[cfg(unix)] -fn pid_alive(pid: u32) -> bool { +pub(crate) fn pid_alive(pid: u32) -> bool { extern "C" { fn kill(pid: i32, sig: i32) -> i32; } @@ -143,7 +156,7 @@ fn pid_alive(pid: u32) -> bool { } #[cfg(windows)] -fn pid_alive(pid: u32) -> bool { +pub(crate) fn pid_alive(pid: u32) -> bool { extern "system" { fn OpenProcess(access: u32, inherit: i32, pid: u32) -> *mut std::ffi::c_void; fn CloseHandle(handle: *mut std::ffi::c_void) -> i32; @@ -161,7 +174,7 @@ fn pid_alive(pid: u32) -> bool { } #[cfg(not(any(unix, windows)))] -fn pid_alive(_pid: u32) -> bool { +pub(crate) fn pid_alive(_pid: u32) -> bool { false } diff --git a/crates/clipsync-cli/src/sas_prompt.rs b/crates/clipsync-cli/src/sas_prompt.rs new file mode 100644 index 0000000..3931bdc --- /dev/null +++ b/crates/clipsync-cli/src/sas_prompt.rs @@ -0,0 +1,463 @@ +// Copyright the ClipSync contributors. +// SPDX-License-Identifier: MIT +//! Short authentication string (SAS) confirmation for `room create` and +//! `room join`. +//! +//! Pairing is committed only after the local user confirms that the other +//! device shows the same verification code. A foreground command asks on +//! stdin. The background create worker publishes the code in the pairing +//! file and waits for `clipsync room confirm` or `clipsync room reject`. + +use std::future::Future; +use std::io::{self, BufRead, IsTerminal, Write}; +use std::pin::Pin; +use std::time::{Duration, Instant}; + +use clipsync_core::{display_sas, normalize_sas, App, CoreError, SasCheck, SasDecision}; +use clipsync_protocol::PAIRING_TTL_SECS; +use clipsync_storage::{LocalStore, PairingWait}; + +use crate::output::emit; +use crate::pairing_bg::pid_alive; + +/// Pairing-file status while the background worker waits for the SAS answer. +pub const STATUS_CONFIRM_SAS: &str = "confirm_sas"; +const STATUS_WAITING: &str = "waiting"; +const STATUS_PAIRED: &str = "paired"; +const STATUS_FAILED: &str = "failed"; +const DECISION_CONFIRMED: &str = "confirmed"; +const DECISION_REJECTED: &str = "rejected"; + +/// How often the worker and `room confirm` re-read the pairing file: fast +/// enough to feel immediate, slow enough to keep both processes idle. +const PAIRING_FILE_POLL: Duration = Duration::from_millis(100); +/// Upper bound for `room confirm` to wait for a joiner and then for the +/// worker to finish. The worker gives up after the relay pairing TTL, so twice +/// that covers a joiner arriving late plus the commit. +const CONFIRM_COMMAND_DEADLINE: Duration = Duration::from_secs(PAIRING_TTL_SECS * 2); + +pub type SasConfirm = + Box Pin + Send>> + Send>; + +#[derive(Clone, Copy, Debug)] +pub struct SasMode { + pub json: bool, + pub non_interactive: bool, + /// `--insecure-skip-sas`: accept without comparing. + pub skip: bool, +} + +/// Confirm on this terminal: show the SAS and read one answer line from +/// stdin. A non-terminal stdin lets scripts compare codes programmatically. +pub fn terminal_confirmer(mode: SasMode) -> SasConfirm { + Box::new(move |check: SasCheck| { + Box::pin(async move { + if mode.skip { + return skipped(mode, &check.sas, &check.peer_device_name); + } + announce(mode, &check.sas, &check.peer_device_name); + if mode.non_interactive { + eprintln!( + "error: the verification code must be confirmed; rerun without --non-interactive, or pass --insecure-skip-sas" + ); + return SasDecision::Rejected; + } + prompt_line(mode); + let sas = check.sas.clone(); + let answer = tokio::task::spawn_blocking(read_answer_line) + .await + .ok() + .flatten(); + decide(&sas, answer.as_deref()) + }) + }) +} + +/// Background worker: publish the SAS in the pairing file and wait for +/// `clipsync room confirm` or `clipsync room reject` to answer there. +pub fn background_confirmer(store: LocalStore, skip: bool) -> SasConfirm { + Box::new(move |check: SasCheck| { + Box::pin(async move { + if skip { + eprintln!("warning: background pairing accepted without comparing verification codes (--insecure-skip-sas)"); + return SasDecision::Confirmed; + } + let worker = std::process::id(); + // Only answer through a pairing file this worker owns; a newer + // `room create` may have replaced it. + let owned = |wait: &PairingWait| wait.pid == worker; + let Ok(Some(mut wait)) = store.load_pairing_wait() else { + return SasDecision::Rejected; + }; + if !owned(&wait) || rejected(&wait) { + // A rejection recorded before the joiner arrived still applies. + return SasDecision::Rejected; + } + wait.status = STATUS_CONFIRM_SAS.into(); + wait.sas = Some(check.sas.clone()); + wait.peer_device_name = Some(check.peer_device_name.clone()); + // A confirmation can only come from a user who saw this code. + wait.sas_decision = None; + // Re-read right before publishing so a rejection written since + // the first read is not overwritten. + match store.load_pairing_wait() { + Ok(Some(latest)) if owned(&latest) && !rejected(&latest) => {} + _ => return SasDecision::Rejected, + } + if store.save_pairing_wait(&wait).is_err() { + return SasDecision::Rejected; + } + loop { + tokio::time::sleep(PAIRING_FILE_POLL).await; + match store.load_pairing_wait() { + Ok(Some(current)) if owned(¤t) => match current.sas_decision.as_deref() { + Some(DECISION_REJECTED) => return SasDecision::Rejected, + Some(DECISION_CONFIRMED) + if current.sas.as_deref() == Some(check.sas.as_str()) => + { + return SasDecision::Confirmed + } + _ => {} + }, + // `room leave` removed the file, a newer `room create` + // replaced it, or it became unreadable. + _ => return SasDecision::Rejected, + } + } + }) + }) +} + +fn rejected(wait: &PairingWait) -> bool { + wait.sas_decision.as_deref() == Some(DECISION_REJECTED) +} + +/// True when a background pairing file no longer blocks a new `room create`: +/// its worker exited, or the user already rejected it. +pub fn replaceable(wait: &PairingWait) -> bool { + !pid_alive(wait.pid) || rejected(wait) +} + +/// `clipsync room confirm [CODE]` and `clipsync room reject`. +#[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." +)] +pub async fn answer_background( + app: &App, + shown_on_other_device: Option<&str>, + reject: bool, + mode: SasMode, +) -> Result<(), CoreError> { + let deadline = Instant::now() + CONFIRM_COMMAND_DEADLINE; + let mut announced_wait = false; + let wait = loop { + let wait = load_live(app)?; + match wait.status.as_str() { + STATUS_CONFIRM_SAS if wait.sas.is_some() => break wait, + STATUS_WAITING if reject => break wait, + STATUS_WAITING => { + if !announced_wait && !mode.json { + println!("waiting for the other device to join…"); + let _ = io::stdout().flush(); + announced_wait = true; + } + } + _ => return Err(not_answerable(&wait)), + } + if Instant::now() >= deadline { + return Err(CoreError::Timeout); + } + tokio::time::sleep(PAIRING_FILE_POLL).await; + }; + + if reject { + return reject_background(app, wait, deadline, mode).await; + } + let sas = wait.sas.clone().unwrap_or_default(); + let peer = wait.peer_device_name.clone().unwrap_or_default(); + let decision = if let Some(entered) = shown_on_other_device { + decide(&sas, Some(entered)) + } else { + announce(mode, &sas, &peer); + if mode.non_interactive { + return Err(CoreError::Message( + "pass the code shown on the other device: clipsync room confirm ".into(), + )); + } + prompt_line(mode); + let answer = tokio::task::spawn_blocking(read_answer_line) + .await + .ok() + .flatten(); + decide(&sas, answer.as_deref()) + }; + + // The prompt may have taken a while: answer only the same live request. + let mut answered = load_live(app)?; + if answered.status != STATUS_CONFIRM_SAS + || answered.pid != wait.pid + || answered.sas.as_deref() != Some(sas.as_str()) + { + return Err(not_answerable(&answered)); + } + if rejected(&answered) { + return Err(CoreError::Pairing( + "pairing was already rejected; nothing was stored".into(), + )); + } + answered.sas_decision = Some( + match decision { + SasDecision::Confirmed => DECISION_CONFIRMED, + SasDecision::Rejected => DECISION_REJECTED, + } + .into(), + ); + app.store.save_pairing_wait(&answered)?; + if decision == SasDecision::Rejected { + wait_for_worker_exit(app, &answered, deadline).await?; + return Err(CoreError::Pairing( + "verification code does not match the other device; pairing aborted and nothing was stored" + .into(), + )); + } + + loop { + let Some(done) = app.store.load_pairing_wait()? else { + return Err(CoreError::Message("pairing was cancelled".into())); + }; + match done.status.as_str() { + STATUS_PAIRED => { + emit( + mode.json, + serde_json::json!({"ok": true, "room_id": done.room_id}), + ); + if !mode.json { + println!("paired"); + } + return Ok(()); + } + STATUS_FAILED => { + return Err(CoreError::Message( + done.error + .unwrap_or_else(|| "background pairing failed".into()), + )); + } + _ if !pid_alive(done.pid) => { + return Err(CoreError::Message( + "background pairing stopped before completing".into(), + )); + } + _ => {} + } + if Instant::now() >= deadline { + return Err(CoreError::Timeout); + } + tokio::time::sleep(PAIRING_FILE_POLL).await; + } +} + +#[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." +)] +async fn reject_background( + app: &App, + wait: PairingWait, + deadline: Instant, + mode: SasMode, +) -> Result<(), CoreError> { + if wait.sas_decision.as_deref() == Some(DECISION_CONFIRMED) { + return Err(CoreError::Message( + "the verification code was already confirmed and pairing is completing".into(), + )); + } + let mut answered = wait; + answered.sas_decision = Some(DECISION_REJECTED.into()); + app.store.save_pairing_wait(&answered)?; + if answered.status == STATUS_WAITING { + // No joiner yet: the worker rejects as soon as one arrives, and a new + // `room create` may replace this pairing right away. + emit( + mode.json, + serde_json::json!({"ok": true, "rejected": true, "joined": false}), + ); + if !mode.json { + println!( + "pairing rejected; it will stop when a device joins, and nothing will be stored" + ); + } + return Ok(()); + } + wait_for_worker_exit(app, &answered, deadline).await?; + emit(mode.json, serde_json::json!({"ok": true, "rejected": true})); + if !mode.json { + println!("pairing rejected; nothing was stored"); + } + Ok(()) +} + +/// Wait until the worker that owns `answered` gave up, re-asserting the +/// rejection if a concurrent write by the worker dropped it. +#[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." +)] +async fn wait_for_worker_exit( + app: &App, + answered: &PairingWait, + deadline: Instant, +) -> Result<(), CoreError> { + loop { + match app.store.load_pairing_wait()? { + Some(current) if current.pid == answered.pid => match current.status.as_str() { + STATUS_FAILED => return Ok(()), + STATUS_PAIRED => { + return Err(CoreError::Message( + "pairing completed before the rejection was recorded".into(), + )) + } + _ if !pid_alive(current.pid) => return Ok(()), + _ if !rejected(¤t) => { + let mut again = current; + again.sas_decision = Some(DECISION_REJECTED.into()); + app.store.save_pairing_wait(&again)?; + } + _ => {} + }, + // Removed or replaced: that worker can no longer commit through it. + _ => return Ok(()), + } + if Instant::now() >= deadline { + return Err(CoreError::Timeout); + } + tokio::time::sleep(PAIRING_FILE_POLL).await; + } +} + +#[expect( + clippy::result_large_err, + reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." +)] +fn load_live(app: &App) -> Result { + app.store.load_pairing_wait()?.ok_or_else(|| { + CoreError::Message("no pairing in progress; run `clipsync room create` first".into()) + }) +} + +/// Explain why a pairing file can no longer be answered. +fn not_answerable(wait: &PairingWait) -> CoreError { + match wait.status.as_str() { + STATUS_PAIRED => CoreError::Message("pairing already completed".into()), + STATUS_FAILED => CoreError::Message( + wait.error + .clone() + .unwrap_or_else(|| "background pairing failed".into()), + ), + _ if !pid_alive(wait.pid) => CoreError::Message( + "background pairing is no longer running; run `clipsync room create` again".into(), + ), + _ => CoreError::Message( + "the pairing request changed; run `clipsync room confirm` again".into(), + ), + } +} + +fn announce(mode: SasMode, sas: &str, peer_device_name: &str) { + emit( + mode.json, + serde_json::json!({ + "event": "sas_confirmation", + "sas": sas, + "peer_device_name": peer_device_name, + }), + ); + if !mode.json { + println!("verification code: {}", display_sas(sas)); + println!("other device: {}", display_name(peer_device_name)); + println!("Check that the other device shows the same verification code."); + } + let _ = io::stdout().flush(); +} + +fn prompt_line(mode: SasMode) { + if !mode.json { + print!("Type the code shown on the other device, or \"yes\" if it matches: "); + let _ = io::stdout().flush(); + } +} + +fn skipped(mode: SasMode, sas: &str, peer_device_name: &str) -> SasDecision { + eprintln!( + "warning: verification code not compared (--insecure-skip-sas); a malicious relay or a guessed code would go unnoticed" + ); + emit( + mode.json, + serde_json::json!({ + "event": "sas_skipped", + "sas": sas, + "peer_device_name": peer_device_name, + }), + ); + SasDecision::Confirmed +} + +fn display_name(peer_device_name: &str) -> &str { + if peer_device_name.is_empty() { + "(unnamed device)" + } else { + peer_device_name + } +} + +fn read_answer_line() -> Option { + let stdin = io::stdin(); + let mut line = String::new(); + if stdin.is_terminal() { + let _ = io::stdout().flush(); + } + match stdin.lock().read_line(&mut line) { + Ok(0) | Err(_) => None, + Ok(_) => Some(line), + } +} + +/// Accept "y"/"yes", or the code shown on the other device. Anything else, +/// including end of input, rejects. +pub fn decide(sas: &str, answer: Option<&str>) -> SasDecision { + let Some(answer) = answer else { + return SasDecision::Rejected; + }; + let trimmed = answer.trim(); + let entered = normalize_sas(trimmed); + let affirmed = trimmed.eq_ignore_ascii_case("y") || trimmed.eq_ignore_ascii_case("yes"); + if affirmed || (!entered.is_empty() && entered == sas) { + SasDecision::Confirmed + } else { + SasDecision::Rejected + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn answers_accept_yes_or_the_matching_code_and_reject_everything_else() { + for accepted in ["y", "YES", " yes \n", "482913", "482 913\n", "482-913"] { + assert_eq!( + decide("482913", Some(accepted)), + SasDecision::Confirmed, + "{accepted:?}" + ); + } + for rejected in ["", "\n", "n", "no", "482914", "48291", "yess", "1"] { + assert_eq!( + decide("482913", Some(rejected)), + SasDecision::Rejected, + "{rejected:?}" + ); + } + assert_eq!(decide("482913", None), SasDecision::Rejected); + } +} diff --git a/crates/clipsync-cli/tests/background_create.rs b/crates/clipsync-cli/tests/background_create.rs index 6234649..796b6ee 100644 --- a/crates/clipsync-cli/tests/background_create.rs +++ b/crates/clipsync-cli/tests/background_create.rs @@ -129,6 +129,91 @@ fn json_out(out: &std::process::Output) -> serde_json::Value { }) } +/// Start a CLI process whose stdin and stdout the test drives, so it can +/// compare verification codes between two devices the way a user would. +fn spawn_cli(home: &Path, relay: &str, args: &[&str]) -> tokio::process::Child { + use std::process::Stdio; + tokio::process::Command::new(bin()) + .args(args) + .env("HOME", home) + .env("USERPROFILE", home) + .env("RUST_LOG", "error") + .env("CLIPSYNC_HOME", home) + .env("CLIPSYNC_RELAY_URL", relay) + .env("CLIPSYNC_NO_DAEMON", "1") + .env("NO_PROXY", "127.0.0.1,localhost") + .env("no_proxy", "127.0.0.1,localhost") + .env_remove("CLIPSYNC_LISTEN") + .env_remove("CLIPSYNC_CA_FILE") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .expect("run clipsync") +} + +/// Read stdout lines until one starts with `prefix`; return the remainder. +async fn line_with_prefix( + reader: &mut tokio::io::BufReader, + prefix: &str, +) -> String { + use tokio::io::AsyncBufReadExt; + tokio::time::timeout(Duration::from_secs(20), async { + loop { + let mut line = String::new(); + assert_ne!( + reader.read_line(&mut line).await.unwrap(), + 0, + "stdout closed before {prefix:?}" + ); + if let Some(rest) = line.trim_end().strip_prefix(prefix) { + return rest.to_string(); + } + } + }) + .await + .unwrap_or_else(|_| panic!("no {prefix:?} line")) +} + +fn digits(text: &str) -> String { + text.chars().filter(char::is_ascii_digit).collect() +} + +fn waiting_store(home: &Path) -> clipsync_storage::LocalStore { + clipsync_storage::LocalStore::open_from(clipsync_storage::AppPaths::from_root(home.into())) + .unwrap() +} + +/// Poll the background worker's pairing file until it asks for the SAS. +async fn background_sas(home: &Path) -> clipsync_storage::PairingWait { + let store = waiting_store(home); + tokio::time::timeout(Duration::from_secs(20), async { + loop { + if let Ok(Some(wait)) = store.load_pairing_wait() { + if wait.status == "confirm_sas" && wait.sas.is_some() { + return wait; + } + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + }) + .await + .expect("background worker never asked to confirm the verification code") +} + +fn secrets_in(home: &Path) -> Vec { + let store = waiting_store(home); + std::fs::read_dir(&store.paths.data_dir) + .map(|entries| { + entries + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|name| name.ends_with(".secret")) + .collect() + }) + .unwrap_or_default() +} + fn kill_pid(pid: u32) { #[cfg(unix)] { @@ -156,12 +241,13 @@ async fn foreground_offer_is_flushed_before_a_peer_joins() { .env("CLIPSYNC_NO_DAEMON", "1") .env_remove("CLIPSYNC_LISTEN") .env_remove("CLIPSYNC_CA_FILE") - .stdin(Stdio::null()) + .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .kill_on_drop(true) .spawn() .unwrap(); + let mut creator_input = child.stdin.take().unwrap(); let mut output = BufReader::new(child.stdout.take().unwrap()); let mut line = String::new(); tokio::time::timeout(Duration::from_secs(30), output.read_line(&mut line)) @@ -193,7 +279,7 @@ async fn foreground_offer_is_flushed_before_a_peer_joins() { } let peer = TempDir::new().unwrap(); seed_identity_file(peer.path()); - let joined = clipsync( + let mut joiner = spawn_cli( peer.path(), &relay, &[ @@ -204,12 +290,48 @@ async fn foreground_offer_is_flushed_before_a_peer_joins() { "--no-auto-sync", ], ); - assert!( - joined.status.success(), - "{}", - String::from_utf8_lossy(&joined.stderr) - ); - let joined = json_out(&joined); + let mut joiner_input = joiner.stdin.take().unwrap(); + let mut joiner_output = BufReader::new(joiner.stdout.take().unwrap()); + let joiner_sas: serde_json::Value = + serde_json::from_str(&line_with_prefix(&mut joiner_output, "").await).unwrap(); + let mut line = String::new(); + tokio::time::timeout(Duration::from_secs(20), output.read_line(&mut line)) + .await + .unwrap() + .unwrap(); + let creator_sas: serde_json::Value = serde_json::from_str(&line).unwrap(); + for event in [&creator_sas, &joiner_sas] { + assert_eq!(event["event"], "sas_confirmation"); + assert_eq!(event["sas"].as_str().unwrap().len(), 6); + assert!(!event["peer_device_name"].as_str().unwrap().is_empty()); + } + assert_eq!(creator_sas["sas"], joiner_sas["sas"]); + // Each user types the code the other device shows. + use tokio::io::AsyncWriteExt; + for (input, other) in [ + (&mut creator_input, &joiner_sas), + (&mut joiner_input, &creator_sas), + ] { + input + .write_all(format!("{}\n", other["sas"].as_str().unwrap()).as_bytes()) + .await + .unwrap(); + input.flush().await.unwrap(); + } + let mut joined = String::new(); + tokio::time::timeout( + Duration::from_secs(20), + joiner_output.read_to_string(&mut joined), + ) + .await + .unwrap() + .unwrap(); + assert!(tokio::time::timeout(Duration::from_secs(10), joiner.wait()) + .await + .unwrap() + .unwrap() + .success()); + let joined: serde_json::Value = serde_json::from_str(joined.trim()).unwrap(); let mut completed = String::new(); tokio::time::timeout( Duration::from_secs(10), @@ -315,16 +437,54 @@ async fn room_create_background_returns_then_pairs() { "second background create should fail while first is waiting" ); - let join = clipsync(b.path(), &relay, &["room", "join", code, "--no-auto-sync"]); + let mut joiner = spawn_cli(b.path(), &relay, &["room", "join", code, "--no-auto-sync"]); + let mut joiner_input = joiner.stdin.take().unwrap(); + let mut joiner_output = tokio::io::BufReader::new(joiner.stdout.take().unwrap()); + let joiner_sas = digits(&line_with_prefix(&mut joiner_output, "verification code: ").await); + let creator_wait = background_sas(a.path()).await; + assert_eq!(creator_wait.sas.as_deref(), Some(joiner_sas.as_str())); + assert!(!creator_wait + .peer_device_name + .as_deref() + .unwrap_or_default() + .is_empty()); + let status = json_out(&clipsync(a.path(), &relay, &["--json", "status"])); + assert_eq!(status["pairing"]["status"], "confirm_sas"); + assert_eq!(status["pairing"]["sas"], joiner_sas.as_str()); + // The joiner's user types the creator's code; the creator's user passes + // the joiner's code to `room confirm`. + use tokio::io::AsyncWriteExt; + joiner_input + .write_all(format!("{}\n", creator_wait.sas.as_deref().unwrap()).as_bytes()) + .await + .unwrap(); + joiner_input.flush().await.unwrap(); + let confirm = clipsync(a.path(), &relay, &["room", "confirm", &joiner_sas]); + if !confirm.status.success() { + kill_pid(pid); + panic!( + "confirm failed: stdout={} stderr={}", + String::from_utf8_lossy(&confirm.stdout), + String::from_utf8_lossy(&confirm.stderr) + ); + } + assert!(String::from_utf8_lossy(&confirm.stdout).contains("paired")); + let join = tokio::time::timeout(Duration::from_secs(20), joiner.wait_with_output()) + .await + .unwrap() + .unwrap(); + let mut join_stdout = String::new(); + tokio::io::AsyncReadExt::read_to_string(&mut joiner_output, &mut join_stdout) + .await + .unwrap(); if !join.status.success() { kill_pid(pid); panic!( - "join failed: stdout={} stderr={}", - String::from_utf8_lossy(&join.stdout), + "join failed: stdout={join_stdout} stderr={}", String::from_utf8_lossy(&join.stderr) ); } - assert!(String::from_utf8_lossy(&join.stdout).contains("joined room")); + assert!(join_stdout.contains("joined room")); let deadline = Instant::now() + Duration::from_secs(20); let mut room = None; @@ -353,7 +513,91 @@ async fn room_create_background_returns_then_pairs() { panic!("creator never recorded the room after background pairing"); } assert_eq!(room.as_deref(), Some(waiting.room_id.as_str())); - assert!(String::from_utf8_lossy(&join.stdout).contains(&waiting.room_id)); + assert!(join_stdout.contains(&waiting.room_id)); + relay_task.abort(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn mismatched_or_rejected_verification_codes_store_nothing_on_either_device() { + let (relay, relay_task) = start_relay().await; + for reject_command in [false, true] { + let a = TempDir::new().unwrap(); + let b = TempDir::new().unwrap(); + seed_identity_file(a.path()); + seed_identity_file(b.path()); + let create = clipsync( + a.path(), + &relay, + &["--json", "room", "create", "--no-auto-sync"], + ); + assert!( + create.status.success(), + "{}", + String::from_utf8_lossy(&create.stderr) + ); + let offer = json_out(&create); + let code = offer["pairing_code"].as_str().unwrap(); + let pid = offer["pid"].as_u64().unwrap() as u32; + let mut joiner = spawn_cli(b.path(), &relay, &["room", "join", code, "--no-auto-sync"]); + let joiner_input = joiner.stdin.take().unwrap(); + let mut joiner_output = tokio::io::BufReader::new(joiner.stdout.take().unwrap()); + let joiner_sas = digits(&line_with_prefix(&mut joiner_output, "verification code: ").await); + let creator_wait = background_sas(a.path()).await; + assert_eq!(creator_wait.sas.as_deref(), Some(joiner_sas.as_str())); + let answer = if reject_command { + clipsync(a.path(), &relay, &["room", "reject"]) + } else { + // A code that differs from the creator's in every digit. + let wrong: String = joiner_sas + .chars() + .map(|digit| if digit == '0' { '1' } else { '0' }) + .collect(); + clipsync(a.path(), &relay, &["room", "confirm", &wrong]) + }; + let answer_stderr = String::from_utf8_lossy(&answer.stderr).into_owned(); + if reject_command { + assert!(answer.status.success(), "{answer_stderr}"); + assert!(String::from_utf8_lossy(&answer.stdout).contains("nothing was stored")); + } else { + assert!(!answer.status.success()); + assert!(answer_stderr.contains("does not match"), "{answer_stderr}"); + } + // The joiner's user also sees no matching code and gives up. + drop(joiner_input); + let join = tokio::time::timeout(Duration::from_secs(20), joiner.wait_with_output()) + .await + .unwrap() + .unwrap(); + assert!(!join.status.success()); + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let wait = waiting_store(a.path()) + .load_pairing_wait() + .unwrap() + .unwrap(); + if wait.status == "failed" { + assert!( + wait.error + .as_deref() + .unwrap_or_default() + .contains("rejected"), + "{:?}", + wait.error + ); + break; + } + if Instant::now() > deadline { + kill_pid(pid); + panic!("background worker did not abort: {}", wait.status); + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + for home in [a.path(), b.path()] { + let rooms = json_out(&clipsync(home, &relay, &["--json", "room", "list"])); + assert_eq!(rooms, serde_json::json!([])); + assert!(secrets_in(home).is_empty(), "{:?}", secrets_in(home)); + } + } relay_task.abort(); } @@ -363,10 +607,17 @@ async fn room_create_auto_inits_without_explicit_init() { let a = TempDir::new().unwrap(); let b = TempDir::new().unwrap(); let started = Instant::now(); + // Scripted setups may opt out of the comparison explicitly on both sides. let create = clipsync( a.path(), &relay, - &["--json", "room", "create", "--no-auto-sync"], + &[ + "--json", + "room", + "create", + "--no-auto-sync", + "--insecure-skip-sas", + ], ); assert!( started.elapsed() < Duration::from_secs(10), @@ -384,7 +635,14 @@ async fn room_create_auto_inits_without_explicit_init() { let join = clipsync( b.path(), &relay, - &["--json", "room", "join", code, "--no-auto-sync"], + &[ + "--json", + "room", + "join", + code, + "--no-auto-sync", + "--insecure-skip-sas", + ], ); if !join.status.success() { kill_pid(pid); @@ -393,4 +651,63 @@ async fn room_create_auto_inits_without_explicit_init() { String::from_utf8_lossy(&join.stderr) ); } + assert!(String::from_utf8_lossy(&join.stderr).contains("--insecure-skip-sas")); + assert_eq!(json_out(&join)["role"], "member"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn rejecting_before_a_join_lets_a_new_room_create_replace_the_pairing() { + let (relay, relay_task) = start_relay().await; + let a = TempDir::new().unwrap(); + seed_identity_file(a.path()); + let first = clipsync( + a.path(), + &relay, + &["--json", "room", "create", "--no-auto-sync"], + ); + assert!( + first.status.success(), + "{}", + String::from_utf8_lossy(&first.stderr) + ); + let first = json_out(&first); + let first_pid = first["pid"].as_u64().unwrap() as u32; + let blocked = clipsync(a.path(), &relay, &["room", "create", "--no-auto-sync"]); + assert!(!blocked.status.success()); + assert!(String::from_utf8_lossy(&blocked.stderr).contains("room join")); + + let rejected = clipsync(a.path(), &relay, &["--json", "room", "reject"]); + assert!( + rejected.status.success(), + "{}", + String::from_utf8_lossy(&rejected.stderr) + ); + assert_eq!(json_out(&rejected)["joined"], false); + + let second = clipsync( + a.path(), + &relay, + &["--json", "room", "create", "--no-auto-sync"], + ); + assert!( + second.status.success(), + "{}", + String::from_utf8_lossy(&second.stderr) + ); + let second = json_out(&second); + let second_pid = second["pid"].as_u64().unwrap() as u32; + assert_ne!(second_pid, first_pid); + assert_ne!(second["pairing_code"], first["pairing_code"]); + let wait = waiting_store(a.path()) + .load_pairing_wait() + .unwrap() + .unwrap(); + assert_eq!((wait.status.as_str(), wait.pid), ("waiting", second_pid)); + assert!( + wait.sas_decision.is_none(), + "the new pairing starts unanswered" + ); + kill_pid(first_pid); + kill_pid(second_pid); + relay_task.abort(); } diff --git a/crates/clipsync-core/src/lib.rs b/crates/clipsync-core/src/lib.rs index 09de6d7..d0951d2 100644 --- a/crates/clipsync-core/src/lib.rs +++ b/crates/clipsync-core/src/lib.rs @@ -20,7 +20,8 @@ pub use engine::{ }; pub use error::{CoreError, ExitCode}; pub use pairing::{ - begin_create_room, create_room, join_room, leave_room, PendingCreate, RoomOffer, + begin_create_room, create_room, display_sas, join_room, leave_room, normalize_sas, + PendingCreate, RoomOffer, SasCheck, SasDecision, }; use std::io::{IsTerminal, Read}; @@ -81,13 +82,18 @@ impl App { self.init(None) } - pub async fn room_create( + pub async fn room_create( &self, ttl: Option, no_auto_sync: bool, json: bool, print_code: impl Fn(&RoomOffer), - ) -> Result { + confirm: C, + ) -> Result + where + C: FnOnce(SasCheck) -> F + Send, + F: std::future::Future + Send, + { let identity = self.identity()?; let cfg = self.store.load_config()?; let ttl_secs = ttl @@ -106,12 +112,27 @@ impl App { expires_at: offer.expires_at.to_rfc3339(), pid: std::process::id(), error: None, + sas: None, + peer_device_name: None, + sas_decision: None, }; let _ = self.store.save_pairing_wait(&wait_file); print_code(&pending.offer); - match pending.wait(&self.store, &identity).await { + // A rejected background pairing may be replaced by a newer `room + // create` while this one winds down; never overwrite that file. + let finish = |result: PairingWait| { + let replaced = matches!( + self.store.load_pairing_wait(), + Ok(Some(current)) + if current.pid != result.pid || current.room_id != result.room_id + ); + if !replaced { + let _ = self.store.save_pairing_wait(&result); + } + }; + match pending.wait(&self.store, &identity, confirm).await { Ok(()) => { - let _ = self.store.save_pairing_wait(&PairingWait { + finish(PairingWait { status: "paired".into(), ..wait_file }); @@ -122,7 +143,7 @@ impl App { Ok(offer) } Err(e) => { - let _ = self.store.save_pairing_wait(&PairingWait { + finish(PairingWait { status: "failed".into(), error: Some(e.to_string()), ..wait_file @@ -132,14 +153,19 @@ impl App { } } - pub async fn room_join( + pub async fn room_join( &self, code: &str, no_auto_sync: bool, - ) -> Result { + confirm: C, + ) -> Result + where + C: FnOnce(SasCheck) -> F + Send, + F: std::future::Future + Send, + { let identity = self.identity()?; let cfg = self.store.load_config()?; - let room = join_room(&self.store, &identity, &cfg, code).await?; + let room = join_room(&self.store, &identity, &cfg, code, confirm).await?; if !no_auto_sync { maybe_start_daemon(&self.store)?; } diff --git a/crates/clipsync-core/src/pairing.rs b/crates/clipsync-core/src/pairing.rs index 22f0c6d..34bfb06 100644 --- a/crates/clipsync-core/src/pairing.rs +++ b/crates/clipsync-core/src/pairing.rs @@ -1,5 +1,6 @@ // Copyright the ClipSync contributors. // SPDX-License-Identifier: MIT +use std::future::Future; use std::time::Duration; use base64::Engine as _; @@ -7,8 +8,8 @@ use chrono::Utc; use tracing::{info, warn}; use clipsync_crypto::{ - confirm_mac, finish_pairing, initial_epoch_key, open, seal, start_pairing_a, start_pairing_b, - verify_confirm_mac, DeviceIdentity, PairingRole, + confirm_mac, finish_pairing, initial_epoch_key, open, seal, short_authentication_string, + start_pairing_a, start_pairing_b, verify_confirm_mac, DeviceIdentity, PairingRole, }; use clipsync_protocol::{ ClientRole, ControlMessage, CreatePairingRequest, CreatePairingResponse, @@ -20,6 +21,71 @@ use clipsync_transport::{join_ws, Incoming, RelayConnection}; use crate::{current_os, device_name, http_client, CoreError}; +/// Advisory error code sent to the relay when the local user rejects the SAS. +/// The relay aborts the pairing session on any client `Error` frame. +const SAS_REJECTED_CODE: &str = "sas_rejected"; +/// How long a rejecting client keeps reading after queueing its `Error` and +/// `Close` frames. The transport stops forwarding, and drops queued frames, +/// once nobody reads incoming frames, so a late peer frame could otherwise +/// cancel the abort notice. Two queued frames flush in milliseconds on a live +/// socket; the bound keeps a stuck relay from holding the caller. +const SAS_REJECT_FLUSH: Duration = Duration::from_secs(2); + +/// What the local user must compare with the other device before a pairing +/// is committed. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SasCheck { + /// Short authentication string. Both devices show the same value only if + /// they ran SPAKE2 with each other. + pub sas: String, + pub peer_device_id: DeviceId, + /// Name the relay reported for the peer. It is not authenticated and is + /// shown for context only; the SAS is what proves the peer's identity. + pub peer_device_name: String, +} + +impl SasCheck { + /// Compare with the value a user read from the other device, ignoring the + /// spaces or dashes used to group digits on screen. + pub fn matches(&self, shown_on_other_device: &str) -> bool { + let entered = normalize_sas(shown_on_other_device); + !entered.is_empty() && entered == self.sas + } + + /// Digits grouped for reading aloud, such as `482 913`. + pub fn display(&self) -> String { + display_sas(&self.sas) + } +} + +/// Keep only the digits of user-entered SAS text. +pub fn normalize_sas(raw: &str) -> String { + raw.chars().filter(char::is_ascii_digit).collect() +} + +/// Group SAS digits in threes for display. Grouping is presentation only; +/// [`SasCheck::matches`] ignores it. +pub fn display_sas(sas: &str) -> String { + // Three-digit groups keep a six-digit value readable without looking like + // the ungrouped pairing code. + const SAS_DISPLAY_GROUP: usize = 3; + let digits: Vec = sas.chars().collect(); + digits + .chunks(SAS_DISPLAY_GROUP) + .map(|group| group.iter().collect::()) + .collect::>() + .join(" ") +} + +/// The local user's answer to a [`SasCheck`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SasDecision { + /// The other device shows the same SAS: send our binding and store the room. + Confirmed, + /// The values differ, or the user cancelled: abort and store nothing. + Rejected, +} + pub struct RoomOffer { pub pairing_code: String, pub room_id: clipsync_protocol::RoomId, @@ -34,15 +100,22 @@ pub struct PendingCreate { } impl PendingCreate { + /// Wait for a joiner, then ask `confirm` to compare the SAS before + /// anything is sent to the peer or stored locally. #[expect( clippy::result_large_err, reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." )] - pub async fn wait( + pub async fn wait( self, store: &LocalStore, identity: &DeviceIdentity, - ) -> Result<(), CoreError> { + confirm: C, + ) -> Result<(), CoreError> + where + C: FnOnce(SasCheck) -> F + Send, + F: Future + Send, + { run_pairing( store, identity, @@ -52,8 +125,10 @@ impl PendingCreate { self.session_id, identity.device_id.clone(), DeviceId::from(""), + None, self.offer.room_id.clone(), DeviceRole::Owner, + confirm, ) .await } @@ -124,19 +199,24 @@ pub async fn begin_create_room( clippy::result_large_err, reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." )] -pub async fn create_room( +pub async fn create_room( store: &LocalStore, identity: &DeviceIdentity, cfg: &AppConfig, ttl_secs: u64, -) -> Result { + confirm: C, +) -> Result +where + C: FnOnce(SasCheck) -> F + Send, + F: Future + Send, +{ let pending = begin_create_room(identity, cfg, ttl_secs).await?; let offer = RoomOffer { pairing_code: pending.offer.pairing_code.clone(), room_id: pending.offer.room_id.clone(), expires_at: pending.offer.expires_at, }; - pending.wait(store, identity).await?; + pending.wait(store, identity, confirm).await?; Ok(offer) } @@ -144,12 +224,17 @@ pub async fn create_room( clippy::result_large_err, reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." )] -pub async fn join_room( +pub async fn join_room( store: &LocalStore, identity: &DeviceIdentity, cfg: &AppConfig, code: &str, -) -> Result { + confirm: C, +) -> Result +where + C: FnOnce(SasCheck) -> F + Send, + F: Future + Send, +{ let req = JoinPairingRequest { pairing_code: code.to_string(), device_id: identity.device_id.clone(), @@ -201,8 +286,10 @@ pub async fn join_room( joined.pairing_session_id, joined.peer.device_id.clone(), identity.device_id.clone(), + Some(joined.peer.device_name.clone()), joined.room_id, DeviceRole::Member, + confirm, ) .await?; store.current_room().map_err(Into::into) @@ -216,7 +303,7 @@ pub async fn join_room( clippy::result_large_err, reason = "Preserve the public CoreError payload and conversions; see docs/compiler-warnings.md." )] -async fn run_pairing( +async fn run_pairing( store: &LocalStore, identity: &DeviceIdentity, mut conn: RelayConnection, @@ -225,9 +312,16 @@ async fn run_pairing( session_id: PairingSessionId, device_a: DeviceId, device_b: DeviceId, + mut peer_name: Option, room_id: clipsync_protocol::RoomId, our_role: DeviceRole, -) -> Result<(), CoreError> { + confirm: C, +) -> Result<(), CoreError> +where + C: FnOnce(SasCheck) -> F + Send, + F: Future + Send, +{ + // The overall deadline also bounds how long the user may take to compare. let timeout = tokio::time::sleep(Duration::from_secs(clipsync_protocol::PAIRING_TTL_SECS + 5)); tokio::pin!(timeout); @@ -244,10 +338,41 @@ async fn run_pairing( let mut complete: Option = None; let mut our_bind_sent = false; let mut confirm_sent = false; + let mut confirm = Some(confirm); + let mut decision: Option>> = None; + let mut sas_confirmed = false; loop { tokio::select! { _ = &mut timeout => return Err(CoreError::Timeout), + verdict = async { + match decision.as_mut() { + Some(pending) => pending.await, + None => std::future::pending().await, + } + }, if decision.is_some() => { + decision = None; + if verdict == SasDecision::Rejected { + // Nothing has been sent to the peer or stored yet. + let _ = conn + .send_control(ControlMessage::Error { + code: SAS_REJECTED_CODE.into(), + message: "verification code rejected".into(), + }) + .await; + conn.close().await; + // Keep the receiver alive until the transport has sent + // both frames and closed (`recv` then yields `None`). + let _ = tokio::time::timeout(SAS_REJECT_FLUSH, async { + while conn.incoming.recv().await.is_some() {} + }) + .await; + return Err(CoreError::Pairing( + "verification code rejected; nothing was stored".into(), + )); + } + sas_confirmed = true; + } incoming = conn.incoming.recv() => { let Some(incoming) = incoming else { return Err(CoreError::Pairing("relay closed during pairing".into())); @@ -256,6 +381,7 @@ async fn run_pairing( Incoming::Control(ControlMessage::HelloOk { .. }) => {} Incoming::Control(ControlMessage::PeerJoined { device }) => { peer_id = Some(device.device_id.clone()); + peer_name = Some(device.device_name.clone()); } Incoming::Control(ControlMessage::Spake2Msg { message, .. }) => { inbound_spake = Some(b64_decode(&message)?); @@ -270,6 +396,13 @@ async fn run_pairing( complete = Some(msg); } Incoming::Control(ControlMessage::Error { code, message }) => { + if our_bind_sent { + // The relay drops the session when the other device + // rejects, so our binding is refused afterwards. + return Err(CoreError::Pairing(format!( + "the other device rejected the verification code or the pairing expired; nothing was stored ({code}: {message})" + ))); + } return Err(CoreError::Pairing(format!("{code}: {message}"))); } Incoming::Pong | Incoming::Binary(_) => {} @@ -345,7 +478,17 @@ async fn run_pairing( .await; return Err(CoreError::Pairing(e.to_string())); } - if !our_bind_sent { + if let Some(ask) = confirm.take() { + let check = SasCheck { + sas: short_authentication_string(k), + peer_device_id: peer_id + .clone() + .ok_or_else(|| CoreError::Pairing("missing peer identity".into()))?, + peer_device_name: peer_name.clone().unwrap_or_default(), + }; + decision = Some(Box::pin(ask(check))); + } + if sas_confirmed && !our_bind_sent { let epoch_key = initial_epoch_key(&k.room_root_key)?; let plain = BindPlain { device_id: identity.device_id.clone(), @@ -372,31 +515,15 @@ async fn run_pairing( }) .await?; our_bind_sent = true; - let key_store = store.clone(); - let key_room = room_id.clone(); - // Keep the keys' ZeroizeOnDrop ownership in the blocking worker. - // Filesystem durability and platform keychains must not stall - // the runtime that services the pairing socket and watchdog. - let key_material = k.clone(); - tokio::task::spawn_blocking(move || { - // Capture the whole zeroizing owner, not its Copy key field. - let keys = key_material; - let epoch_key = initial_epoch_key(&keys.room_root_key)?; - key_store.save_room_keys( - &key_room, - &hex::encode(keys.room_root_key), - &hex::encode(epoch_key), - )?; - Ok::<(), CoreError>(()) - }) - .await - .map_err(|error| { - CoreError::Pairing(format!("room key persistence task failed: {error}")) - })??; } } } + // Commit only after the local user confirmed the SAS and our binding + // went out; until then a peer binding just waits in `peer_bind`. + if !our_bind_sent { + continue; + } if let (Some(k), Some((nonce_hex, ct_hex))) = (&keys, peer_bind.clone()) { let nonce_bytes = hex::decode(&nonce_hex).map_err(|e| CoreError::Pairing(e.to_string()))?; @@ -413,6 +540,7 @@ async fn run_pairing( &ct, )?; let bind: BindPlain = serde_json::from_slice(&pt)?; + let key_room = room_id.clone(); if let Some(ControlMessage::PairingComplete { room_id, epoch, @@ -437,13 +565,26 @@ async fn run_pairing( peers: vec![peer], }; let room_store = store.clone(); + // Keep the keys' ZeroizeOnDrop ownership in the blocking worker. + // Filesystem durability and platform keychains must not stall + // the runtime that services the pairing socket and watchdog. + let key_material = k.clone(); tokio::task::spawn_blocking(move || { + // Capture the whole zeroizing owner, not its Copy key field. + let keys = key_material; + let epoch_key = initial_epoch_key(&keys.room_root_key)?; + room_store.save_room_keys( + &key_room, + &hex::encode(keys.room_root_key), + &hex::encode(epoch_key), + )?; room_store.upsert_room(room)?; let mut cfg = room_store.load_config()?; cfg.sync.enabled = true; cfg.sync.auto_start = true; cfg.sync.direction = clipsync_protocol::SyncDirection::Both; - room_store.save_config(&cfg) + room_store.save_config(&cfg)?; + Ok::<(), CoreError>(()) }) .await .map_err(|error| { @@ -520,12 +661,405 @@ fn b64_decode(s: &str) -> Result, CoreError> { .map_err(|e| CoreError::Pairing(e.to_string())) } +/// Test-only pair of confirmers that compare SAS values the way two users +/// would: each side shows its value to the other and confirms only on a match. +#[cfg(test)] +pub(crate) type SasPeerConfirm = + Box std::pin::Pin + Send>> + Send>; + +#[cfg(test)] +pub(crate) fn sas_comparison() -> (SasPeerConfirm, SasPeerConfirm) { + fn side( + mine: tokio::sync::oneshot::Sender, + theirs: tokio::sync::oneshot::Receiver, + ) -> SasPeerConfirm { + Box::new(move |check: SasCheck| { + Box::pin(async move { + let _ = mine.send(check.sas.clone()); + match theirs.await { + Ok(other) if check.matches(&other) => SasDecision::Confirmed, + _ => SasDecision::Rejected, + } + }) + }) + } + let (creator_tx, creator_rx) = tokio::sync::oneshot::channel(); + let (joiner_tx, joiner_rx) = tokio::sync::oneshot::channel(); + (side(creator_tx, joiner_rx), side(joiner_tx, creator_rx)) +} + #[cfg(test)] #[cfg_attr(coverage_nightly, coverage(off))] mod tests { use super::*; use clipsync_crypto::{derive_nonce, PairingKeys}; + /// Real-clock budget for a scripted relay that answers immediately. + const SCRIPT_DEADLINE: Duration = Duration::from_secs(8); + + async fn accept(_: SasCheck) -> SasDecision { + SasDecision::Confirmed + } + + fn secret_files(store: &LocalStore) -> Vec { + std::fs::read_dir(&store.paths.data_dir) + .map(|entries| { + entries + .map(|entry| entry.unwrap().path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "secret")) + .collect() + }) + .unwrap_or_default() + } + + /// Scripted relay plus honest joiner (role B). It reports the SAS it + /// derived, then either sends its binding at once like a pre-SAS peer, or + /// waits for ours. Returns the frame the client sent after key confirmation. + async fn honest_joiner( + local: DeviceId, + sid: PairingSessionId, + room: clipsync_protocol::RoomId, + bind_first: bool, + script_deadline: Duration, + ) -> ( + crate::test_relay::Server, + tokio::sync::oneshot::Receiver, + tokio::sync::oneshot::Receiver, + tokio::sync::oneshot::Sender<()>, + ) { + use crate::test_relay::{receive, send, Server}; + let (sas_tx, sas_rx) = tokio::sync::oneshot::channel(); + let (frame_tx, frame_rx) = tokio::sync::oneshot::channel(); + let (release_tx, release) = tokio::sync::oneshot::channel::<()>(); + let peer = DeviceId::from("sas-peer-remote"); + let server = Server::websocket_with_deadline( + axum::Router::new(), + script_deadline, + move |mut socket| async move { + send( + &mut socket, + ControlMessage::PeerJoined { + device: clipsync_protocol::PeerInfo { + device_id: peer.clone(), + device_name: "Pixel of the joiner".into(), + os: "android".into(), + role: DeviceRole::Member, + online: true, + }, + }, + ) + .await; + let ControlMessage::Spake2Msg { message, .. } = receive(&mut socket).await else { + panic!("client did not initiate SPAKE2") + }; + let state = start_pairing_b("123456", sid.clone(), local, peer.clone()).unwrap(); + let outbound = state.outbound.clone(); + let keys = finish_pairing(state, &b64_decode(&message).unwrap()).unwrap(); + let _ = sas_tx.send(short_authentication_string(&keys)); + send( + &mut socket, + ControlMessage::Spake2Msg { + pairing_session_id: sid.clone(), + message: b64_encode(&outbound), + }, + ) + .await; + let ControlMessage::KeyConfirm { mac, .. } = receive(&mut socket).await else { + panic!("client did not confirm key") + }; + verify_confirm_mac(&keys, PairingRole::A, &b64_decode(&mac).unwrap()).unwrap(); + send( + &mut socket, + ControlMessage::KeyConfirm { + pairing_session_id: sid.clone(), + mac: b64_encode(&confirm_mac(&keys, PairingRole::B)), + }, + ) + .await; + let bind = { + let plain = BindPlain { + device_id: peer.clone(), + static_public: hex::encode([7; 32]), + device_name: "Pixel of the joiner".into(), + os: "android".into(), + fingerprint: "fixture fingerprint".into(), + epoch: 1, + epoch_key: hex::encode(initial_epoch_key(&keys.room_root_key).unwrap()), + role: DeviceRole::Member, + }; + let nonce = device_bind_nonce(&keys.pairing_wrap_key, PairingRole::B).unwrap(); + ControlMessage::DeviceBind { + pairing_session_id: sid.clone(), + nonce: hex::encode(nonce), + ciphertext: hex::encode( + seal( + &keys.pairing_wrap_key, + &nonce, + sid.as_str().as_bytes(), + &serde_json::to_vec(&plain).unwrap(), + ) + .unwrap(), + ), + } + }; + let complete = ControlMessage::PairingComplete { + room_id: room, + epoch: 1, + device_token: "synthetic-device-token".into(), + role: DeviceRole::Owner, + }; + if bind_first { + // A pre-SAS peer binds immediately; a hostile relay may also + // announce completion early. Neither may commit the pairing. + send(&mut socket, bind.clone()).await; + send(&mut socket, complete.clone()).await; + } + // No receive deadline here: the timeout test pauses the clock + // while the client waits for an answer that never comes. + let after_confirm = loop { + match socket.recv().await { + Some(Ok(axum::extract::ws::Message::Text(text))) => { + match ControlMessage::decode(&text).unwrap() { + ControlMessage::Ping { ts } => { + send(&mut socket, ControlMessage::Pong { ts }).await; + } + message => break Some(message), + } + } + Some(Ok(_)) => {} + _ => break None, + } + }; + if let Some(after_confirm) = after_confirm { + let bound = matches!(after_confirm, ControlMessage::DeviceBind { .. }); + let _ = frame_tx.send(after_confirm); + if bound && !bind_first { + send(&mut socket, bind).await; + send(&mut socket, complete).await; + } + } + let _ = release.await; + }, + ) + .await; + (server, sas_rx, frame_rx, release_tx) + } + + #[tokio::test] + async fn pairing_commits_only_after_the_user_confirms_a_matching_sas() { + for bind_first in [false, true] { + let directory = tempfile::TempDir::new().unwrap(); + let store = + LocalStore::open_from(crate::AppPaths::from_root(directory.path().into())).unwrap(); + let identity = DeviceIdentity::from_bytes("sas-confirm-local".into(), [36; 32]); + let sid = PairingSessionId::new(); + let room = clipsync_protocol::RoomId::new(); + let (mut server, peer_sas, mut frame, release) = honest_joiner( + identity.device_id.clone(), + sid.clone(), + room.clone(), + bind_first, + SCRIPT_DEADLINE, + ) + .await; + let connection = RelayConnection::connect(&join_ws(&server.url, "/v1/ws")) + .await + .unwrap(); + let (shown_tx, shown) = tokio::sync::oneshot::channel(); + let (answer, answered) = tokio::sync::oneshot::channel(); + let pairing = run_pairing( + &store, + &identity, + connection, + PairingRole::A, + "123456", + sid, + identity.device_id.clone(), + DeviceId::new(), + None, + room.clone(), + DeviceRole::Owner, + move |check: SasCheck| async move { + shown_tx.send(check).unwrap(); + answered.await.unwrap() + }, + ); + let driver = async { + let check = tokio::time::timeout(Duration::from_secs(5), shown) + .await + .unwrap() + .unwrap(); + assert_eq!(check.sas, peer_sas.await.unwrap(), "honest peers agree"); + assert!(check.matches(&check.display())); + assert_eq!(check.peer_device_id, DeviceId::from("sas-peer-remote")); + assert_eq!(check.peer_device_name, "Pixel of the joiner"); + // While the user is still comparing, nothing is bound or stored. + assert!( + tokio::time::timeout(Duration::from_millis(200), &mut frame) + .await + .is_err(), + "DeviceBind sent before SAS confirmation" + ); + assert!(store.load_state().unwrap().rooms.is_empty()); + assert!(secret_files(&store).is_empty()); + answer.send(SasDecision::Confirmed).unwrap(); + }; + let (result, ()) = tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(pairing, driver) + }) + .await + .unwrap(); + result.unwrap(); + assert!(matches!( + frame.await.unwrap(), + ControlMessage::DeviceBind { .. } + )); + let _ = release.send(()); + server.finish().await; + let stored = store.current_room().unwrap(); + assert_eq!(stored.room_id, room); + assert_eq!(stored.peers[0].device_id, DeviceId::from("sas-peer-remote")); + assert!(store.load_epoch_key(&room).is_ok()); + } + } + + #[tokio::test] + async fn rejected_sas_sends_no_binding_and_stores_no_room_keys_or_credentials() { + for bind_first in [false, true] { + let directory = tempfile::TempDir::new().unwrap(); + let store = + LocalStore::open_from(crate::AppPaths::from_root(directory.path().into())).unwrap(); + let identity = DeviceIdentity::from_bytes("sas-reject-local".into(), [37; 32]); + let sid = PairingSessionId::new(); + let room = clipsync_protocol::RoomId::new(); + let (mut server, _peer_sas, frame, release) = honest_joiner( + identity.device_id.clone(), + sid.clone(), + room.clone(), + bind_first, + SCRIPT_DEADLINE, + ) + .await; + let connection = RelayConnection::connect(&join_ws(&server.url, "/v1/ws")) + .await + .unwrap(); + let error = tokio::time::timeout( + Duration::from_secs(10), + run_pairing( + &store, + &identity, + connection, + PairingRole::A, + "123456", + sid, + identity.device_id.clone(), + DeviceId::new(), + None, + room.clone(), + DeviceRole::Owner, + |_| async { SasDecision::Rejected }, + ), + ) + .await + .unwrap() + .unwrap_err(); + assert!( + error.to_string().contains("verification code rejected"), + "{error}" + ); + let ControlMessage::Error { code, .. } = frame.await.unwrap() else { + panic!("rejection must abort the relay session instead of binding") + }; + assert_eq!(code, SAS_REJECTED_CODE); + let _ = release.send(()); + server.finish().await; + assert!(store.load_state().unwrap().rooms.is_empty()); + assert!( + secret_files(&store).is_empty(), + "{:?}", + secret_files(&store) + ); + } + } + + #[tokio::test] + async fn unanswered_sas_prompt_times_out_without_storing_anything() { + let directory = tempfile::TempDir::new().unwrap(); + let store = + LocalStore::open_from(crate::AppPaths::from_root(directory.path().into())).unwrap(); + let identity = DeviceIdentity::from_bytes("sas-timeout-local".into(), [38; 32]); + let sid = PairingSessionId::new(); + let room = clipsync_protocol::RoomId::new(); + let (mut server, _peer_sas, _frame, release) = honest_joiner( + identity.device_id.clone(), + sid.clone(), + room.clone(), + true, + // Outlive the client's paused-clock pairing deadline. + Duration::from_secs(clipsync_protocol::PAIRING_TTL_SECS * 2), + ) + .await; + let connection = RelayConnection::connect(&join_ws(&server.url, "/v1/ws")) + .await + .unwrap(); + let (shown_tx, shown) = tokio::sync::oneshot::channel(); + let pairing = tokio::spawn({ + let store = store.clone(); + async move { + run_pairing( + &store, + &identity, + connection, + PairingRole::A, + "123456", + sid, + identity.device_id.clone(), + DeviceId::new(), + None, + room, + DeviceRole::Owner, + move |_| async move { + shown_tx.send(()).unwrap(); + std::future::pending::().await + }, + ) + .await + } + }); + tokio::time::timeout(Duration::from_secs(5), shown) + .await + .unwrap() + .unwrap(); + tokio::time::pause(); + let result = tokio::time::timeout(Duration::from_secs(150), pairing) + .await + .unwrap() + .unwrap(); + tokio::time::resume(); + let _ = release.send(()); + server.finish().await; + assert!(matches!(result, Err(CoreError::Timeout)), "{result:?}"); + assert!(store.load_state().unwrap().rooms.is_empty()); + assert!(secret_files(&store).is_empty()); + } + + #[test] + fn sas_check_matching_ignores_grouping_and_rejects_empty_input() { + let check = SasCheck { + sas: "482913".into(), + peer_device_id: DeviceId::from("peer"), + peer_device_name: "peer".into(), + }; + assert_eq!(check.display(), "482 913"); + for same in ["482913", "482 913", "482-913", " 48 29 13 "] { + assert!(check.matches(same), "{same}"); + } + for different in ["", "yes", "482914", "4829130", "48291"] { + assert!(!check.matches(different), "{different}"); + } + assert_eq!(normalize_sas("4a8-2 9"), "4829"); + } + fn paired_keys() -> (PairingSessionId, PairingKeys, PairingKeys) { let session = PairingSessionId::new(); let a = DeviceId::from("dev-a"); @@ -664,7 +1198,7 @@ mod tests { }; let create = begin_create_room(&identity, &cfg, 60).await.err().unwrap(); assert!(create.to_string().contains("create failed: maintenance")); - let join = join_room(&store, &identity, &cfg, "123456") + let join = join_room(&store, &identity, &cfg, "123456", accept) .await .unwrap_err(); if body.starts_with("code_") { @@ -687,7 +1221,7 @@ mod tests { .unwrap() .to_string() .contains("relay create")); - assert!(join_room(&store, &identity, &cfg, "123456") + assert!(join_room(&store, &identity, &cfg, "123456", accept) .await .unwrap_err() .to_string() @@ -718,11 +1252,11 @@ mod tests { }; let identity = DeviceIdentity::from_bytes("malformed-response".into(), [32; 32]); assert!(matches!( - create_room(&store, &identity, &cfg, 60).await, + create_room(&store, &identity, &cfg, 60, accept).await, Err(CoreError::Http(_)) )); assert!(matches!( - join_room(&store, &identity, &cfg, "123456").await, + join_room(&store, &identity, &cfg, "123456", accept).await, Err(CoreError::Http(_)) )); assert!(store.load_state().unwrap().rooms.is_empty()); @@ -768,8 +1302,10 @@ mod tests { PairingSessionId::new(), identity.device_id.clone(), DeviceId::new(), + None, clipsync_protocol::RoomId::new(), DeviceRole::Owner, + accept, ) .await .unwrap_err(); @@ -822,8 +1358,10 @@ mod tests { PairingSessionId::new(), identity.device_id.clone(), DeviceId::new(), + None, clipsync_protocol::RoomId::new(), DeviceRole::Owner, + accept, ), ) .await @@ -919,6 +1457,16 @@ mod tests { let _ = release.await; return; } + // Confirm honestly so the client reaches its SAS prompt and + // then parses the hostile binding. + send( + &mut socket, + ControlMessage::KeyConfirm { + pairing_session_id: session.clone(), + mac: b64_encode(&confirm_mac(&keys, PairingRole::B)), + }, + ) + .await; send( &mut socket, ControlMessage::DeviceBind { @@ -949,8 +1497,10 @@ mod tests { sid, identity.device_id.clone(), peer, + None, clipsync_protocol::RoomId::new(), DeviceRole::Owner, + accept, ), ) .await diff --git a/crates/clipsync-core/tests/support/engine_behavior.rs b/crates/clipsync-core/tests/support/engine_behavior.rs index c447a40..f08edcf 100644 --- a/crates/clipsync-core/tests/support/engine_behavior.rs +++ b/crates/clipsync-core/tests/support/engine_behavior.rs @@ -1731,9 +1731,15 @@ async fn create_failure_retains_the_offer_and_error_for_background_status() { let offer = printed.clone(); let error = peer .app - .room_create(Some(Duration::from_secs(999)), true, false, move |value| { - *offer.lock() = Some(value.pairing_code.clone()); - }) + .room_create( + Some(Duration::from_secs(999)), + true, + false, + move |value| { + *offer.lock() = Some(value.pairing_code.clone()); + }, + |_| async { crate::SasDecision::Confirmed }, + ) .await .err() .unwrap(); @@ -1766,25 +1772,34 @@ fn app_pairing_enables_sync_and_supports_one_shot_pull_without_installing_a_serv let (sent, received) = tokio::sync::oneshot::channel(); let offer_channel = Arc::new(Mutex::new(Some(sent))); let app = pair.a.app.clone(); + let (creator_sas, joiner_sas) = crate::pairing::sas_comparison(); let creator = tokio::spawn(async move { - app.room_create(Some(Duration::from_secs(60)), false, true, move |offer| { - let _ = offer_channel - .lock() - .take() - .unwrap() - .send(offer.pairing_code.clone()); - }) + app.room_create( + Some(Duration::from_secs(60)), + false, + true, + move |offer| { + let _ = offer_channel + .lock() + .take() + .unwrap() + .send(offer.pairing_code.clone()); + }, + creator_sas, + ) .await }); let code = tokio::time::timeout(Duration::from_secs(5), received) .await .unwrap() .unwrap(); - let joined = - tokio::time::timeout(Duration::from_secs(10), pair.b.app.room_join(&code, false)) - .await - .unwrap() - .unwrap(); + let joined = tokio::time::timeout( + Duration::from_secs(10), + pair.b.app.room_join(&code, false, joiner_sas), + ) + .await + .unwrap() + .unwrap(); let created = tokio::time::timeout(Duration::from_secs(10), creator) .await .unwrap() @@ -1905,10 +1920,20 @@ fn command_facade_reports_corrupt_config_and_state_without_replacing_them() { assert!(peer.app.status().await.is_err()); assert!(peer .app - .room_create(None, true, false, |_| {}) + .room_create( + None, + true, + false, + |_| {}, + |_| async { crate::SasDecision::Confirmed } + ) + .await + .is_err()); + assert!(peer + .app + .room_join("123456", true, |_| async { crate::SasDecision::Confirmed }) .await .is_err()); - assert!(peer.app.room_join("123456", true).await.is_err()); assert_eq!(std::fs::read(&config).unwrap(), b"invalid = ["); peer.app.store.save_config(&AppConfig::default()).unwrap(); let state = peer.app.store.paths.state_file(); diff --git a/crates/clipsync-core/tests/support/facade_behavior.rs b/crates/clipsync-core/tests/support/facade_behavior.rs index 9bfcc0a..7d3b617 100644 --- a/crates/clipsync-core/tests/support/facade_behavior.rs +++ b/crates/clipsync-core/tests/support/facade_behavior.rs @@ -229,20 +229,27 @@ fn explicit_pairing_without_auto_sync_returns_matching_rooms_and_installs_no_ser let offer_channel = Arc::new(Mutex::new(Some(sent))); let store = creator.store.clone(); let create_app = creator.clone(); + let (creator_sas, joiner_sas) = crate::pairing::sas_comparison(); let create = tokio::spawn(async move { create_app - .room_create(None, true, false, move |offer| { - let waiting = store.load_pairing_wait().unwrap().unwrap(); - assert_eq!(waiting.status, "waiting"); - assert_eq!(waiting.pairing_code, offer.pairing_code); - offer_channel - .lock() - .unwrap() - .take() - .unwrap() - .send(offer.pairing_code.clone()) - .unwrap(); - }) + .room_create( + None, + true, + false, + move |offer| { + let waiting = store.load_pairing_wait().unwrap().unwrap(); + assert_eq!(waiting.status, "waiting"); + assert_eq!(waiting.pairing_code, offer.pairing_code); + offer_channel + .lock() + .unwrap() + .take() + .unwrap() + .send(offer.pairing_code.clone()) + .unwrap(); + }, + creator_sas, + ) .await }); let code = received.await.unwrap(); @@ -274,7 +281,7 @@ fn explicit_pairing_without_auto_sync_returns_matching_rooms_and_installs_no_ser }) .await .unwrap(); - let joined = joiner.room_join(&code, true).await.unwrap(); + let joined = joiner.room_join(&code, true, joiner_sas).await.unwrap(); let created = create.await.unwrap().unwrap(); assert_eq!(created.room_id, joined.room_id); assert_eq!( diff --git a/crates/clipsync-crypto/Cargo.toml b/crates/clipsync-crypto/Cargo.toml index 8cdfd7f..a67330d 100644 --- a/crates/clipsync-crypto/Cargo.toml +++ b/crates/clipsync-crypto/Cargo.toml @@ -29,6 +29,8 @@ zeroize.workspace = true [dev-dependencies] serde_json.workspace = true +# spake2 0.4 draws scalars through rand_core 0.6; seeded tests pin SAS vectors. +spake2_rand_core = { package = "rand_core", version = "0.6" } [lints] workspace = true diff --git a/crates/clipsync-crypto/src/lib.rs b/crates/clipsync-crypto/src/lib.rs index 1e1b97a..ecfd8aa 100644 --- a/crates/clipsync-crypto/src/lib.rs +++ b/crates/clipsync-crypto/src/lib.rs @@ -21,8 +21,9 @@ pub use kdf::{ }; pub use noise::{NoiseHandshake, NoiseSession, NOISE_PATTERN}; pub use pairing::{ - confirm_mac, finish_pairing, pairing_transcript, start_pairing_a, start_pairing_b, - verify_confirm_mac, PairingKeys, PairingRole, PairingState, + confirm_mac, finish_pairing, pairing_transcript, short_authentication_string, start_pairing_a, + start_pairing_b, verify_confirm_mac, PairingKeys, PairingRole, PairingState, SAS_DIGITS, + SAS_LABEL, }; #[derive(Debug, thiserror::Error)] diff --git a/crates/clipsync-crypto/src/pairing.rs b/crates/clipsync-crypto/src/pairing.rs index c88a030..71fb906 100644 --- a/crates/clipsync-crypto/src/pairing.rs +++ b/crates/clipsync-crypto/src/pairing.rs @@ -12,6 +12,17 @@ use crate::{CryptoError, Result}; type HmacSha256 = Hmac; +/// HKDF info label that separates the short authentication string from every +/// other key derived from the SPAKE2 secret. +pub const SAS_LABEL: &[u8] = b"clipsync/v1/sas"; +/// Decimal digits in the SAS. Six digits match the length users already type +/// for the pairing code; two unrelated sessions collide with probability 10^-6. +pub const SAS_DIGITS: u32 = 6; +/// Leading key bytes reduced to the SAS. A 64-bit sample keeps the modulo +/// bias toward low values below 10^6 / 2^64 (about 2^-44). +const SAS_SAMPLE_BYTES: usize = 8; +const SAS_MODULUS: u64 = 10u64.pow(SAS_DIGITS); + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PairingRole { A, @@ -33,6 +44,8 @@ pub struct PairingKeys { pub confirm_key_b: [u8; KEY_LEN], pub pairing_wrap_key: [u8; KEY_LEN], pub room_root_key: [u8; KEY_LEN], + /// Input to [`short_authentication_string`]; never sent on the wire. + pub sas_key: [u8; KEY_LEN], #[zeroize(skip)] pub transcript_hash: [u8; 32], } @@ -99,6 +112,33 @@ fn start( }) } +/// Seeded variant of [`start`] so tests can pin SPAKE2-derived vectors. +#[cfg(test)] +fn start_with_rng( + role: PairingRole, + password: &str, + session_id: PairingSessionId, + device_a: DeviceId, + device_b: DeviceId, + rng: impl spake2_rand_core::RngCore + spake2_rand_core::CryptoRng, +) -> PairingState { + let pw = Password::new(password.as_bytes()); + let id_a = Identity::new(device_a.as_str().as_bytes()); + let id_b = Identity::new(device_b.as_str().as_bytes()); + let (spake, outbound) = match role { + PairingRole::A => Spake2::::start_a_with_rng(&pw, &id_a, &id_b, rng), + PairingRole::B => Spake2::::start_b_with_rng(&pw, &id_a, &id_b, rng), + }; + PairingState { + role, + session_id, + device_a, + device_b, + outbound, + spake: Some(spake), + } +} + pub fn finish_pairing(state: PairingState, inbound: &[u8]) -> Result { let spake = state.spake.ok_or(CryptoError::Pairing("missing state"))?; let shared = spake @@ -122,16 +162,41 @@ pub fn finish_pairing(state: PairingState, inbound: &[u8]) -> Result Result<[u8; KEY_LEN]> { + derive_labeled(shared, transcript_hash, SAS_LABEL) +} + +fn render_sas(sas_key: &[u8; KEY_LEN]) -> String { + let mut sample = [0u8; SAS_SAMPLE_BYTES]; + sample.copy_from_slice(&sas_key[..SAS_SAMPLE_BYTES]); + let value = u64::from_be_bytes(sample) % SAS_MODULUS; + format!("{value:0width$}", width = SAS_DIGITS as usize) +} + +/// Short authentication string both users compare out of band before a +/// pairing is committed. +/// +/// It is computed locally from the SPAKE2 secret and transcript, so it adds +/// nothing to the wire. Two devices show the same value only when they ran +/// SPAKE2 with each other. A relay that ran one session with each device, or +/// a joiner that guessed the code, makes the values differ. See +/// `docs/security.md` for what the comparison does and does not cover. +pub fn short_authentication_string(keys: &PairingKeys) -> String { + render_sas(&keys.sas_key) +} + pub fn confirm_mac(keys: &PairingKeys, role: PairingRole) -> Vec { let (key, label) = match role { PairingRole::A => (&keys.confirm_key_a, b"clipsync/v1/confirm-a".as_slice()), @@ -252,6 +317,183 @@ mod tests { )); } + /// Recorded from the seeded run below. It pins SPAKE2 group constants, + /// the transcript layout, the HKDF label, and the decimal rendering + /// together, so a change to any of them is visible as a compatibility break. + const SEEDED_VECTOR_SAS: &str = "401515"; + + /// Deterministic `rand_core` 0.6 source for SPAKE2 scalars in tests only. + struct SeededRng(u64); + + impl spake2_rand_core::RngCore for SeededRng { + fn next_u32(&mut self) -> u32 { + self.next_u64() as u32 + } + fn next_u64(&mut self) -> u64 { + let mut bytes = [0u8; 8]; + self.fill_bytes(&mut bytes); + u64::from_be_bytes(bytes) + } + fn fill_bytes(&mut self, dest: &mut [u8]) { + for chunk in dest.chunks_mut(32) { + let block = Sha256::digest(self.0.to_be_bytes()); + self.0 += 1; + chunk.copy_from_slice(&block[..chunk.len()]); + } + } + fn try_fill_bytes( + &mut self, + dest: &mut [u8], + ) -> std::result::Result<(), spake2_rand_core::Error> { + self.fill_bytes(dest); + Ok(()) + } + } + + impl spake2_rand_core::CryptoRng for SeededRng {} + + fn seeded( + role: PairingRole, + seed: u64, + password: &str, + session_id: &PairingSessionId, + device_a: &DeviceId, + device_b: &DeviceId, + ) -> PairingState { + start_with_rng( + role, + password, + session_id.clone(), + device_a.clone(), + device_b.clone(), + SeededRng(seed), + ) + } + + #[test] + fn honest_peers_derive_the_same_sas() { + let session = PairingSessionId::new(); + let a = DeviceId::from("dev-a"); + let b = DeviceId::from("dev-b"); + let sa = start_pairing_a("482913", session.clone(), a.clone(), b.clone()).unwrap(); + let sb = start_pairing_b("482913", session, a, b).unwrap(); + let (msg_a, msg_b) = (sa.outbound.clone(), sb.outbound.clone()); + let ka = finish_pairing(sa, &msg_b).unwrap(); + let kb = finish_pairing(sb, &msg_a).unwrap(); + let sas = short_authentication_string(&ka); + assert_eq!(sas, short_authentication_string(&kb)); + assert_eq!(sas.len(), SAS_DIGITS as usize); + assert!(sas.bytes().all(|byte| byte.is_ascii_digit())); + } + + #[test] + fn relay_mitm_with_the_code_yields_different_sas_on_each_device() { + // The relay issues the code, so it can complete one SPAKE2 session + // with each device. Key confirmation succeeds on both, so only the + // out-of-band SAS comparison can reveal the split. + let session = PairingSessionId::new(); + let a = DeviceId::from("dev-a"); + let b = DeviceId::from("dev-b"); + let code = "482913"; + let honest_a = seeded(PairingRole::A, 1, code, &session, &a, &b); + let relay_as_b = seeded(PairingRole::B, 2, code, &session, &a, &b); + let relay_as_a = seeded(PairingRole::A, 3, code, &session, &a, &b); + let honest_b = seeded(PairingRole::B, 4, code, &session, &a, &b); + let (to_relay_from_a, to_a) = (honest_a.outbound.clone(), relay_as_b.outbound.clone()); + let (to_b, to_relay_from_b) = (relay_as_a.outbound.clone(), honest_b.outbound.clone()); + let keys_a = finish_pairing(honest_a, &to_a).unwrap(); + let relay_keys_a = finish_pairing(relay_as_b, &to_relay_from_a).unwrap(); + let relay_keys_b = finish_pairing(relay_as_a, &to_relay_from_b).unwrap(); + let keys_b = finish_pairing(honest_b, &to_b).unwrap(); + // Both devices accept the relay's key confirmation. + verify_confirm_mac( + &keys_a, + PairingRole::B, + &confirm_mac(&relay_keys_a, PairingRole::B), + ) + .unwrap(); + verify_confirm_mac( + &keys_b, + PairingRole::A, + &confirm_mac(&relay_keys_b, PairingRole::A), + ) + .unwrap(); + assert_ne!( + short_authentication_string(&keys_a), + short_authentication_string(&keys_b), + "a split pairing must not show matching SAS values" + ); + assert_ne!(keys_a.sas_key, keys_b.sas_key); + } + + #[test] + fn wrong_peer_with_a_guessed_code_yields_a_different_sas() { + // A guesser completes SPAKE2 with the creator; the device the user + // intended to pair ran its own session and shows a different value. + let session = PairingSessionId::new(); + let a = DeviceId::from("dev-a"); + let guesser = DeviceId::from("dev-guesser"); + let intended = DeviceId::from("dev-intended"); + let creator = seeded(PairingRole::A, 5, "482913", &session, &a, &guesser); + let joiner = seeded(PairingRole::B, 6, "482913", &session, &a, &guesser); + let (msg_a, msg_b) = (creator.outbound.clone(), joiner.outbound.clone()); + let creator_keys = finish_pairing(creator, &msg_b).unwrap(); + let guesser_keys = finish_pairing(joiner, &msg_a).unwrap(); + assert_eq!( + short_authentication_string(&creator_keys), + short_authentication_string(&guesser_keys) + ); + let other_a = seeded(PairingRole::A, 7, "482913", &session, &a, &intended); + let other_b = seeded(PairingRole::B, 8, "482913", &session, &a, &intended); + let (msg_a, msg_b) = (other_a.outbound.clone(), other_b.outbound.clone()); + let intended_keys = finish_pairing(other_b, &msg_a).unwrap(); + let _ = finish_pairing(other_a, &msg_b).unwrap(); + assert_ne!( + short_authentication_string(&creator_keys), + short_authentication_string(&intended_keys) + ); + } + + #[test] + fn sas_derivation_matches_independent_hkdf_vector() { + // Python: HKDF-SHA256(ikm=[7]*32, salt=[3]*32, info=b"clipsync/v1/sas"), + // then the first 8 bytes big-endian modulo 10**6, zero-padded. + let key = derive_sas_key(&[7; 32], &[3; 32]).unwrap(); + assert_eq!( + hex::encode(key), + "19acaf08b7cfd91531f560b32cc1cb6ec712b3941cb0fb5113662171e092c59d" + ); + assert_eq!(render_sas(&key), "882453"); + assert_eq!(SAS_LABEL, b"clipsync/v1/sas"); + } + + #[test] + fn sas_rendering_zero_pads_and_reduces_the_leading_bytes() { + let mut key = [0u8; KEY_LEN]; + assert_eq!(render_sas(&key), "000000"); + key[7] = 42; + assert_eq!(render_sas(&key), "000042"); + key = [0xff; KEY_LEN]; + // u64::MAX % 10^6 = 551615; bytes past the sample do not matter. + assert_eq!(render_sas(&key), "551615"); + key[SAS_SAMPLE_BYTES] = 0; + assert_eq!(render_sas(&key), "551615"); + } + + #[test] + fn seeded_pairing_pins_the_end_to_end_sas_vector() { + let session = PairingSessionId::from("01JCLIPSYNCSASVECTOR00000"); + let a = DeviceId::from("dev-a"); + let b = DeviceId::from("dev-b"); + let sa = seeded(PairingRole::A, 11, "482913", &session, &a, &b); + let sb = seeded(PairingRole::B, 12, "482913", &session, &a, &b); + let (msg_a, msg_b) = (sa.outbound.clone(), sb.outbound.clone()); + let ka = finish_pairing(sa, &msg_b).unwrap(); + let kb = finish_pairing(sb, &msg_a).unwrap(); + assert_eq!(short_authentication_string(&ka), SEEDED_VECTOR_SAS); + assert_eq!(short_authentication_string(&kb), SEEDED_VECTOR_SAS); + } + #[test] fn transcript_message_lengths_and_device_order_are_bound() { let session = PairingSessionId::new(); diff --git a/crates/clipsync-crypto/tests/wire_contract.rs b/crates/clipsync-crypto/tests/wire_contract.rs index d6f53b6..851ed4f 100644 --- a/crates/clipsync-crypto/tests/wire_contract.rs +++ b/crates/clipsync-crypto/tests/wire_contract.rs @@ -55,6 +55,7 @@ fn pairing_confirmation_matches_python_hmac_fixture() { transcript_hash: [3; 32], pairing_wrap_key: [4; 32], room_root_key: [5; 32], + sas_key: [6; 32], }; for (role, expected) in [ ( diff --git a/crates/clipsync-desktop/src/lib.rs b/crates/clipsync-desktop/src/lib.rs index 3474bf9..498105b 100644 --- a/crates/clipsync-desktop/src/lib.rs +++ b/crates/clipsync-desktop/src/lib.rs @@ -3,10 +3,48 @@ #![cfg_attr(all(coverage_nightly, test), feature(coverage_attribute))] //! Desktop pairing and daemon control shared by the window. -use clipsync_core::{begin_create_room, join_room, App}; +use std::future::Future; +use std::pin::Pin; + +use clipsync_core::{begin_create_room, join_room, App, SasCheck, SasDecision}; use clipsync_daemon::install_and_start; use clipsync_storage::LocalStore; +/// A verification code the window must show next to Confirm and Cancel +/// buttons. Dropping it unanswered rejects the pairing. +#[derive(Debug)] +pub struct SasPrompt { + pub check: SasCheck, + reply: tokio::sync::oneshot::Sender, +} + +impl SasPrompt { + pub fn answer(self, decision: SasDecision) { + let _ = self.reply.send(decision); + } + + /// The pairing behind this prompt already ended (timeout, peer + /// rejection, relay error); the window should stop showing it. + pub fn is_closed(&self) -> bool { + self.reply.is_closed() + } +} + +pub type SasConfirm = + Box Pin + Send>> + Send>; + +/// Forward the SAS check to the window through `show` and wait for the +/// user's answer. A window that drops the prompt rejects the pairing. +pub fn window_confirmer(show: impl FnOnce(SasPrompt) + Send + 'static) -> SasConfirm { + Box::new(move |check: SasCheck| { + Box::pin(async move { + let (reply, answer) = tokio::sync::oneshot::channel(); + show(SasPrompt { check, reply }); + answer.await.unwrap_or(SasDecision::Rejected) + }) + }) +} + #[derive(Clone, Debug, PartialEq, Eq)] pub struct DeskStatus { pub device_id: String, @@ -45,7 +83,9 @@ pub fn normalize_join_code(raw: &str) -> Option { } } -pub async fn create_room(store: LocalStore) -> Result { +/// Create a room and return its code. Pairing continues in the background +/// and commits only after `confirm` accepts the verification code. +pub async fn create_room(store: LocalStore, confirm: SasConfirm) -> Result { let app = App { store: store.clone(), }; @@ -56,18 +96,18 @@ pub async fn create_room(store: LocalStore) -> Result { .map_err(|e| e.to_string())?; let code = pending.offer.pairing_code.clone(); tokio::spawn(async move { - if pending.wait(&store, &identity).await.is_ok() { + if pending.wait(&store, &identity, confirm).await.is_ok() { let _ = install_and_start(&store.paths); } }); Ok(code) } -pub async fn join_room_code(app: &App, code: &str) -> Result { +pub async fn join_room_code(app: &App, code: &str, confirm: SasConfirm) -> Result { let code = normalize_join_code(code).ok_or_else(|| "enter a 6-digit code".to_string())?; let identity = app.identity().map_err(|e| e.to_string())?; let cfg = app.store.load_config().map_err(|e| e.to_string())?; - join_room(&app.store, &identity, &cfg, &code) + join_room(&app.store, &identity, &cfg, &code, confirm) .await .map_err(|e| e.to_string())?; let room = app.store.current_room().map_err(|e| e.to_string())?; @@ -80,6 +120,36 @@ pub async fn join_room_code(app: &App, code: &str) -> Result { mod tests { use super::*; + #[tokio::test] + async fn window_confirmer_forwards_the_check_and_rejects_unanswered_prompts() { + let check = SasCheck { + sas: "482913".into(), + peer_device_id: "peer".into(), + peer_device_name: "Laptop".into(), + }; + for answer in [ + Some(SasDecision::Confirmed), + Some(SasDecision::Rejected), + None, + ] { + let (shown_tx, shown) = std::sync::mpsc::channel(); + let confirm = window_confirmer(move |prompt| shown_tx.send(prompt).unwrap()); + let decision = tokio::spawn(confirm(check.clone())); + let prompt = tokio::task::spawn_blocking(move || shown.recv().unwrap()) + .await + .unwrap(); + assert_eq!(prompt.check, check); + match answer { + Some(decision) => prompt.answer(decision), + None => drop(prompt), + } + assert_eq!( + decision.await.unwrap(), + answer.unwrap_or(SasDecision::Rejected) + ); + } + } + #[test] fn join_code_keeps_six_digits() { assert_eq!(normalize_join_code("48 29-13").as_deref(), Some("482913")); @@ -95,6 +165,31 @@ mod command_tests { use clipsync_crypto::DeviceIdentity; use clipsync_storage::{AppConfig, AppPaths}; + fn accept() -> SasConfirm { + Box::new(|_| Box::pin(async { SasDecision::Confirmed })) + } + + /// Confirmers for two windows whose users compare the codes they see. + fn sas_comparison() -> (SasConfirm, SasConfirm) { + fn side( + mine: tokio::sync::oneshot::Sender, + theirs: tokio::sync::oneshot::Receiver, + ) -> SasConfirm { + Box::new(move |check: SasCheck| { + Box::pin(async move { + let _ = mine.send(check.sas.clone()); + match theirs.await { + Ok(other) if check.matches(&other) => SasDecision::Confirmed, + _ => SasDecision::Rejected, + } + }) + }) + } + let (creator_tx, creator_rx) = tokio::sync::oneshot::channel(); + let (joiner_tx, joiner_rx) = tokio::sync::oneshot::channel(); + (side(creator_tx, joiner_rx), side(joiner_tx, creator_rx)) + } + fn fixture() -> (tempfile::TempDir, App) { let root = tempfile::tempdir().unwrap(); let app = App::open_from(AppPaths::from_root(root.path().to_path_buf())).unwrap(); @@ -138,23 +233,23 @@ mod command_tests { async fn commands_reject_invalid_codes_and_unavailable_relay_without_launching_services() { let (_root, app) = fixture(); assert_eq!( - join_room_code(&app, "123").await.unwrap_err(), + join_room_code(&app, "123", accept()).await.unwrap_err(), "enter a 6-digit code" ); - assert!(join_room_code(&app, "482913") + assert!(join_room_code(&app, "482913", accept()) .await .unwrap_err() .contains("relay join")); - assert!(create_room(app.store.clone()) + assert!(create_room(app.store.clone(), accept()) .await .unwrap_err() .contains("relay create")); std::fs::write(app.store.paths.config_file(), "broken = [").unwrap(); - assert!(create_room(app.store.clone()) + assert!(create_room(app.store.clone(), accept()) .await .unwrap_err() .contains("toml")); - assert!(join_room_code(&app, "482913") + assert!(join_room_code(&app, "482913", accept()) .await .unwrap_err() .contains("toml")); @@ -184,7 +279,7 @@ mod command_tests { let mut cfg = app.store.load_config().unwrap(); cfg.relay_url = format!("http://{address}"); app.store.save_config(&cfg).unwrap(); - let code = create_room(app.store.clone()).await.unwrap(); + let code = create_room(app.store.clone(), accept()).await.unwrap(); assert_eq!(code.len(), 6); assert!(code.bytes().all(|byte| byte.is_ascii_digit())); assert!( @@ -266,11 +361,12 @@ mod command_tests { cfg.relay_url = format!("http://{address}"); app.store.save_config(&cfg).unwrap(); } - let code = create_room(first.store.clone()).await.unwrap(); + let (creator_sas, joiner_sas) = sas_comparison(); + let code = create_room(first.store.clone(), creator_sas).await.unwrap(); let formatted = format!("{} {}-{}", &code[..2], &code[2..4], &code[4..]); let room = tokio::time::timeout( std::time::Duration::from_secs(10), - join_room_code(&second, &formatted), + join_room_code(&second, &formatted, joiner_sas), ) .await .unwrap() diff --git a/crates/clipsync-desktop/src/main.rs b/crates/clipsync-desktop/src/main.rs index a067223..0fa2dc1 100644 --- a/crates/clipsync-desktop/src/main.rs +++ b/crates/clipsync-desktop/src/main.rs @@ -6,9 +6,11 @@ use std::sync::mpsc::{self, Receiver, Sender}; use std::time::Duration; -use clipsync_core::App; +use clipsync_core::{App, SasDecision}; use clipsync_daemon::connect_ipc; -use clipsync_desktop::{create_room, join_room_code, local_status, open_app, DeskStatus}; +use clipsync_desktop::{ + create_room, join_room_code, local_status, open_app, window_confirmer, DeskStatus, SasPrompt, +}; use eframe::egui; const INK: egui::Color32 = egui::Color32::from_rgb(18, 20, 22); @@ -18,8 +20,17 @@ const MINT: egui::Color32 = egui::Color32::from_rgb(79, 227, 194); enum Work { Created(Result), Joined(Result), + /// Pairing reached key confirmation; the user must compare codes. + Verify(SasPrompt), } +const SAS_CONFIRM_LABEL: &str = "Codes match"; +const SAS_CANCEL_LABEL: &str = "Cancel"; +const SAS_REJECTED_MESSAGE: &str = + "Pairing cancelled: the verification codes were not confirmed. Nothing was stored."; +const SAS_EXPIRED_MESSAGE: &str = + "Pairing ended before the verification codes were confirmed. Nothing was stored."; + struct DesktopApp { core: App, rt: tokio::runtime::Runtime, @@ -30,6 +41,7 @@ struct DesktopApp { join_code: String, error: Option, busy: bool, + sas_prompt: Option, } impl DesktopApp { @@ -50,9 +62,27 @@ impl DesktopApp { join_code: String::new(), error: None, busy: false, + sas_prompt: None, }) } + fn confirmer(&self) -> clipsync_desktop::SasConfirm { + let tx = self.tx.clone(); + window_confirmer(move |prompt| { + let _ = tx.send(Work::Verify(prompt)); + }) + } + + fn answer_sas(&mut self, decision: SasDecision) { + if let Some(prompt) = self.sas_prompt.take() { + prompt.answer(decision); + } + if decision == SasDecision::Rejected { + self.pairing_code = None; + self.error = Some(SAS_REJECTED_MESSAGE.into()); + } + } + fn refresh(&mut self) { if let Ok(local) = local_status(&self.core) { self.status.device_id = local.device_id; @@ -84,9 +114,10 @@ impl DesktopApp { self.error = None; let store = self.core.store.clone(); let tx = self.tx.clone(); + let confirm = self.confirmer(); let handle = self.rt.handle().clone(); std::thread::spawn(move || { - let result = handle.block_on(create_room(store)); + let result = handle.block_on(create_room(store, confirm)); let _ = tx.send(Work::Created(result)); }); } @@ -97,29 +128,49 @@ impl DesktopApp { let app = self.core.clone(); let code = self.join_code.clone(); let tx = self.tx.clone(); + let confirm = self.confirmer(); let handle = self.rt.handle().clone(); std::thread::spawn(move || { - let result = handle.block_on(join_room_code(&app, &code)); + let result = handle.block_on(join_room_code(&app, &code, confirm)); let _ = tx.send(Work::Joined(result)); }); } fn drain(&mut self) { while let Ok(msg) = self.rx.try_recv() { + if let Work::Verify(prompt) = msg { + // A join keeps its busy state until the pairing finishes. + self.sas_prompt = Some(prompt); + continue; + } self.busy = false; match msg { + Work::Verify(_) => {} Work::Created(Ok(code)) => { self.pairing_code = Some(code); self.error = None; } - Work::Created(Err(e)) | Work::Joined(Err(e)) => self.error = Some(e), + Work::Created(Err(e)) | Work::Joined(Err(e)) => { + // The pairing behind any open prompt is over. + self.sas_prompt = None; + self.error = Some(e); + } Work::Joined(Ok(room)) => { + self.sas_prompt = None; self.status.room_id = Some(room); self.pairing_code = None; self.error = None; } } } + if self.sas_prompt.as_ref().is_some_and(SasPrompt::is_closed) { + // A background create timed out or the relay aborted it. + self.sas_prompt = None; + self.pairing_code = None; + if self.error.is_none() { + self.error = Some(SAS_EXPIRED_MESSAGE.into()); + } + } } } @@ -161,8 +212,39 @@ impl DesktopApp { ); ui.add_space(16.0); + if let Some(prompt) = &self.sas_prompt { + let peer = if prompt.check.peer_device_name.is_empty() { + "the other device" + } else { + prompt.check.peer_device_name.as_str() + }; + let mut decision = None; + egui::Frame::NONE + .fill(PANEL) + .corner_radius(16.0) + .inner_margin(16.0) + .show(ui, |ui| { + ui.label(egui::RichText::new("VERIFICATION CODE").color(MINT).monospace()); + ui.label(egui::RichText::new(prompt.check.display()).size(40.0).monospace().strong()); + ui.label(format!("Check that {peer} shows the same code.")); + ui.label("Confirm only if both devices show the same code."); + ui.horizontal(|ui| { + if ui.button(SAS_CONFIRM_LABEL).clicked() { + decision = Some(SasDecision::Confirmed); + } + if ui.button(SAS_CANCEL_LABEL).clicked() { + decision = Some(SasDecision::Rejected); + } + }); + }); + if let Some(decision) = decision { + self.answer_sas(decision); + } + ui.add_space(12.0); + } + if let Some(code) = &self.pairing_code { - if self.status.room_id.is_none() { + if self.status.room_id.is_none() && self.sas_prompt.is_none() { egui::Frame::NONE .fill(PANEL) .corner_radius(16.0) @@ -282,6 +364,7 @@ mod tests { join_code: String::new(), error: None, busy: false, + sas_prompt: None, }; (root, app) } @@ -456,6 +539,110 @@ mod tests { assert!(!text.contains("PAIRING CODE") && !text.contains("Create room")); } + fn sas_prompt(app: &DesktopApp) -> tokio::sync::oneshot::Receiver { + let (answer_tx, answer) = tokio::sync::oneshot::channel(); + let confirm = app.confirmer(); + app.rt.spawn(async move { + let decision = confirm(clipsync_core::SasCheck { + sas: "482913".into(), + peer_device_id: "peer".into(), + peer_device_name: "Work laptop".into(), + }) + .await; + let _ = answer_tx.send(decision); + }); + answer + } + + #[test] + fn headless_sas_prompt_shows_code_and_peer_and_reports_the_answer() { + for (label, expected) in [ + (SAS_CONFIRM_LABEL, SasDecision::Confirmed), + (SAS_CANCEL_LABEL, SasDecision::Rejected), + ] { + let (_root, mut app) = fixture(); + let ui = HeadlessUi::default(); + app.pairing_code = Some("135790".into()); + app.busy = true; + let answer = sas_prompt(&app); + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while app.sas_prompt.is_none() { + assert!(std::time::Instant::now() < deadline, "prompt never arrived"); + app.drain(); + std::thread::sleep(Duration::from_millis(5)); + } + assert!( + app.busy, + "a verification prompt must not end a pending join" + ); + let text = ui.text(&mut app); + assert!(text.contains("VERIFICATION CODE") && text.contains("482 913")); + assert!(text.contains("Check that Work laptop shows the same code.")); + assert!( + !text.contains("PAIRING CODE"), + "the SAS replaces the pairing code" + ); + ui.click(&mut app, label); + assert_eq!(app.rt.block_on(answer).unwrap(), expected); + assert!(app.sas_prompt.is_none()); + let text = ui.text(&mut app); + assert!(!text.contains("VERIFICATION CODE")); + if expected == SasDecision::Rejected { + assert!(app.pairing_code.is_none()); + assert!(text.contains("Nothing was stored")); + } else { + assert_eq!(app.pairing_code.as_deref(), Some("135790")); + assert!(app.error.is_none()); + } + } + } + + #[test] + fn prompts_close_when_their_pairing_ends_without_an_answer() { + let (_root, mut app) = fixture(); + // The pairing (here, its decision future) ends before the user answers. + let (reply, answer) = tokio::sync::oneshot::channel::(); + let confirm = app.confirmer(); + let pending = app.rt.spawn(async move { + let _ = reply.send( + confirm(clipsync_core::SasCheck { + sas: "482913".into(), + peer_device_id: "peer".into(), + peer_device_name: "Work laptop".into(), + }) + .await, + ); + }); + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while app.sas_prompt.is_none() { + assert!(std::time::Instant::now() < deadline, "prompt never arrived"); + app.drain(); + std::thread::sleep(Duration::from_millis(5)); + } + app.pairing_code = Some("135790".into()); + pending.abort(); + let _ = app.rt.block_on(pending); + drop(answer); + app.drain(); + assert!(app.sas_prompt.is_none() && app.pairing_code.is_none()); + let text = frame(&mut app); + assert!(!text.contains("VERIFICATION CODE")); + assert!(text.contains("Pairing ended before the verification codes were confirmed")); + + // A join result also retires any prompt still on screen. + let _answer = sas_prompt(&app); + while app.sas_prompt.is_none() { + app.drain(); + std::thread::sleep(Duration::from_millis(5)); + } + app.tx + .send(Work::Joined(Err("pairing failed".into()))) + .unwrap(); + app.drain(); + assert!(app.sas_prompt.is_none()); + assert_eq!(app.error.as_deref(), Some("pairing failed")); + } + #[test] fn headless_window_shows_pairing_and_connection_states() { let (_root, mut app) = fixture(); diff --git a/crates/clipsync-mobile/src/lib.rs b/crates/clipsync-mobile/src/lib.rs index 3348477..ac3b355 100644 --- a/crates/clipsync-mobile/src/lib.rs +++ b/crates/clipsync-mobile/src/lib.rs @@ -12,7 +12,7 @@ use clipsync_clipboard::{ hash_item, AdapterInfo, Capabilities, ClipboardBackend, ClipboardItem, ImageMime, SystemClipboard, }; -use clipsync_core::{begin_create_room, join_room, run_daemon, App}; +use clipsync_core::{begin_create_room, join_room, run_daemon, App, SasCheck, SasDecision}; use clipsync_storage::AppPaths; use tokio::runtime::Runtime; use tracing::warn; @@ -44,6 +44,80 @@ pub trait ClipboardBridge: Send + Sync { fn notify(&self, title: String, body: String); } +/// Native hook that shows the pairing verification code (SAS). +/// +/// ClipSync calls `confirm_sas` once per pairing, on a background thread, +/// after key confirmation and before anything is sent to the peer or stored. +/// Show `sas` (for example grouped as `482 913`) together with +/// `peer_device_name`, ask the user whether the other device shows the same +/// code, block until they answer, and return `true` only if it matches. +/// Returning `false` aborts the pairing and stores nothing. +/// +/// If the pairing ends first (deadline, the other device rejected, relay +/// error), ClipSync calls `sas_cancelled`. Dismiss the dialog then, and let +/// the pending `confirm_sas` return; its answer is ignored. `sas_cancelled` +/// must not block. +#[uniffi::export(callback_interface)] +pub trait SasVerifier: Send + Sync { + fn confirm_sas(&self, sas: String, peer_device_name: String) -> bool; + fn sas_cancelled(&self); +} + +/// Tells the host to dismiss its dialog when the pairing future is dropped +/// before `confirm_sas` returned. +struct CancelUnanswered { + verifier: Arc, + answered: Arc, +} + +impl Drop for CancelUnanswered { + fn drop(&mut self) { + if !self.answered.load(std::sync::atomic::Ordering::SeqCst) { + self.verifier.sas_cancelled(); + } + } +} + +fn verifier_confirmer( + verifier: Box, +) -> impl FnOnce(SasCheck) -> std::pin::Pin + Send>> + + Send + + 'static { + let verifier: Arc = Arc::from(verifier); + move |check: SasCheck| { + Box::pin(async move { + let answered = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let _cancel = CancelUnanswered { + verifier: verifier.clone(), + answered: answered.clone(), + }; + // The native callback blocks on UI; keep it off the runtime workers. + let confirmed = tokio::task::spawn_blocking(move || { + let confirmed = verifier.confirm_sas(check.sas, check.peer_device_name); + answered.store(true, std::sync::atomic::Ordering::SeqCst); + confirmed + }) + .await + .unwrap_or(false); + if confirmed { + SasDecision::Confirmed + } else { + SasDecision::Rejected + } + }) + } +} + +/// Pre-SAS behaviour kept for `create_room()` and `join_room()`: the pairing +/// is accepted without comparing codes. +async fn unverified(check: SasCheck) -> SasDecision { + warn!( + peer = %check.peer_device_name, + "pairing accepted without SAS comparison; use the *_verified API to detect a malicious relay or a guessed code" + ); + SasDecision::Confirmed +} + #[derive(uniffi::Record)] pub struct PairingOffer { pub pairing_code: String, @@ -178,36 +252,38 @@ impl ClipSyncClient { }) } + /// Kept for existing apps. Pairs without comparing verification codes, + /// so it cannot detect a malicious relay or a guessed code. New apps + /// should call `create_room_verified`. pub fn create_room(&self) -> Result { - let app = self.app.clone(); - self.rt.block_on(async move { - let identity = app.identity()?; - let cfg = app.store.load_config()?; - let pending = begin_create_room(&identity, &cfg, 120).await?; - let offer = PairingOffer { - pairing_code: pending.offer.pairing_code.clone(), - room_id: pending.offer.room_id.to_string(), - expires_at: pending.offer.expires_at.to_rfc3339(), - }; - let store = app.store.clone(); - tokio::spawn(async move { - if let Err(e) = pending.wait(&store, &identity).await { - warn!(error = %e, "mobile pairing wait failed"); - } - }); - Ok(offer) - }) + self.create(unverified) } + /// Kept for existing apps. Pairs without comparing verification codes, + /// so it cannot detect a malicious relay or a guessed code. New apps + /// should call `join_room_verified`. pub fn join_room(&self, code: String) -> Result { - let app = self.app.clone(); - self.rt.block_on(async move { - let identity = app.identity()?; - let cfg = app.store.load_config()?; - join_room(&app.store, &identity, &cfg, &code).await?; - let room = app.store.current_room()?; - Ok(room.room_id.to_string()) - }) + self.join(code, unverified) + } + + /// Like `create_room`, but the pairing commits only after `verifier` + /// confirms that both devices show the same verification code. + pub fn create_room_verified( + &self, + verifier: Box, + ) -> Result { + self.create(verifier_confirmer(verifier)) + } + + /// Like `join_room`, but the pairing commits only after `verifier` + /// confirms that both devices show the same verification code. A + /// rejected code returns an error and stores nothing. + pub fn join_room_verified( + &self, + code: String, + verifier: Box, + ) -> Result { + self.join(code, verifier_confirmer(verifier)) } pub fn start_sync(&self, clipboard: Box) -> Result<(), MobileError> { @@ -247,6 +323,52 @@ impl ClipSyncClient { } } +/// Room TTL, in seconds, that the mobile create helpers request. It matches +/// the relay's fixed pairing lifetime, as the earlier literal did. +const MOBILE_PAIRING_TTL_SECS: u64 = clipsync_protocol::PAIRING_TTL_SECS; + +impl ClipSyncClient { + fn create(&self, confirm: C) -> Result + where + C: FnOnce(SasCheck) -> F + Send + 'static, + F: std::future::Future + Send + 'static, + { + let app = self.app.clone(); + self.rt.block_on(async move { + let identity = app.identity()?; + let cfg = app.store.load_config()?; + let pending = begin_create_room(&identity, &cfg, MOBILE_PAIRING_TTL_SECS).await?; + let offer = PairingOffer { + pairing_code: pending.offer.pairing_code.clone(), + room_id: pending.offer.room_id.to_string(), + expires_at: pending.offer.expires_at.to_rfc3339(), + }; + let store = app.store.clone(); + tokio::spawn(async move { + if let Err(e) = pending.wait(&store, &identity, confirm).await { + warn!(error = %e, "mobile pairing wait failed"); + } + }); + Ok(offer) + }) + } + + fn join(&self, code: String, confirm: C) -> Result + where + C: FnOnce(SasCheck) -> F + Send, + F: std::future::Future + Send, + { + let app = self.app.clone(); + self.rt.block_on(async move { + let identity = app.identity()?; + let cfg = app.store.load_config()?; + join_room(&app.store, &identity, &cfg, &code, confirm).await?; + let room = app.store.current_room()?; + Ok(room.room_id.to_string()) + }) + } +} + #[cfg(test)] #[cfg_attr(coverage_nightly, coverage(off))] mod tests { @@ -458,6 +580,149 @@ mod tests { } } + /// Native verifier stand-in: shows its code to the other device's verifier + /// and confirms only when `accept` is set and both codes match. + struct ChannelVerifier { + accept: bool, + mine: Mutex>, + theirs: Mutex>, + seen: Arc>>, + } + + impl SasVerifier for ChannelVerifier { + fn confirm_sas(&self, sas: String, peer_device_name: String) -> bool { + self.seen + .lock() + .unwrap() + .push((sas.clone(), peer_device_name)); + let _ = self.mine.lock().unwrap().send(sas.clone()); + let other = self + .theirs + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)); + self.accept && other.as_deref() == Ok(sas.as_str()) + } + + fn sas_cancelled(&self) { + // Recorded so the `seen.len()` checks catch an unexpected cancel. + self.seen + .lock() + .unwrap() + .push(("cancelled".into(), String::new())); + } + } + + /// Verifier whose user never answers until the test releases it. + struct StalledVerifier { + shown: Mutex>, + release: Mutex>, + cancelled: Arc, + } + + impl SasVerifier for StalledVerifier { + fn confirm_sas(&self, _sas: String, _peer_device_name: String) -> bool { + self.shown.lock().unwrap().send(()).unwrap(); + let _ = self.release.lock().unwrap().recv(); + true + } + + fn sas_cancelled(&self) { + self.cancelled.fetch_add(1, Ordering::SeqCst); + } + } + + #[tokio::test] + async fn ended_pairings_tell_the_host_to_dismiss_an_unanswered_prompt() { + let (shown_tx, shown) = std::sync::mpsc::channel(); + let (release, release_rx) = std::sync::mpsc::channel(); + let cancelled = Arc::new(AtomicUsize::new(0)); + let confirm = verifier_confirmer(Box::new(StalledVerifier { + shown: Mutex::new(shown_tx), + release: Mutex::new(release_rx), + cancelled: cancelled.clone(), + })); + let decision = confirm(SasCheck { + sas: "482913".into(), + peer_device_id: "peer".into(), + peer_device_name: "Phone".into(), + }); + let pairing = tokio::spawn(decision); + tokio::task::spawn_blocking(move || shown.recv_timeout(Duration::from_secs(5)).unwrap()) + .await + .unwrap(); + assert_eq!(cancelled.load(Ordering::SeqCst), 0); + // The pairing deadline or a peer rejection drops the decision future. + pairing.abort(); + let _ = pairing.await; + assert_eq!(cancelled.load(Ordering::SeqCst), 1); + release.send(()).unwrap(); + } + + fn verifier_pair( + creator_accepts: bool, + joiner_accepts: bool, + seen: &Arc>>, + ) -> (Box, Box) { + let (creator_tx, creator_rx) = std::sync::mpsc::channel(); + let (joiner_tx, joiner_rx) = std::sync::mpsc::channel(); + ( + Box::new(ChannelVerifier { + accept: creator_accepts, + mine: Mutex::new(creator_tx), + theirs: Mutex::new(joiner_rx), + seen: seen.clone(), + }), + Box::new(ChannelVerifier { + accept: joiner_accepts, + mine: Mutex::new(joiner_tx), + theirs: Mutex::new(creator_rx), + seen: seen.clone(), + }), + ) + } + + fn client_at( + root: &std::path::Path, + device: &str, + seed: u8, + relay: &str, + ) -> Arc { + seed_home(root); + let identity = DeviceIdentity::from_bytes(device.into(), [seed; 32]); + std::fs::write( + AppPaths::from_root(root.into()).identity_file(), + serde_json::to_vec(&identity.to_stored()).unwrap(), + ) + .unwrap(); + let client = ClipSyncClient::new( + root.display().to_string(), + relay.into(), + String::new(), + String::new(), + ) + .unwrap(); + let mut cfg = client.app.store.load_config().unwrap(); + cfg.sync.enabled = false; + cfg.sync.auto_start = false; + client.app.store.save_config(&cfg).unwrap(); + client + } + + fn secret_files(client: &ClipSyncClient) -> usize { + std::fs::read_dir(&client.app.store.paths.data_dir) + .unwrap() + .filter(|entry| { + entry + .as_ref() + .unwrap() + .path() + .extension() + .is_some_and(|ext| ext == "secret") + }) + .count() + } + fn seed_home(root: &std::path::Path) { let app = App::open_from(AppPaths::from_root(root.to_path_buf())).unwrap(); let identity = DeviceIdentity::from_bytes("mobile-test-device".into(), [11; 32]); @@ -633,6 +898,71 @@ mod tests { .unwrap(), joiner.app.store.load_epoch_key(&joined.into()).unwrap() ); + + // Verified API: a rejected code stores nothing on the joiner, and the + // creator cannot complete a pairing the joiner refused. + let relay = format!("http://{address}"); + let verified_creator_home = tempfile::tempdir().unwrap(); + let verified_joiner_home = tempfile::tempdir().unwrap(); + let verified_creator = client_at( + verified_creator_home.path(), + "mobile-verified-creator", + 13, + &relay, + ); + let verified_joiner = client_at( + verified_joiner_home.path(), + "mobile-verified-joiner", + 14, + &relay, + ); + let seen = Arc::new(Mutex::new(Vec::new())); + let (creator_verifier, joiner_verifier) = verifier_pair(true, false, &seen); + let refused = verified_creator + .create_room_verified(creator_verifier) + .unwrap(); + let error = verified_joiner + .join_room_verified(refused.pairing_code, joiner_verifier) + .unwrap_err(); + assert!( + error.to_string().contains("verification code rejected"), + "{error}" + ); + assert!(verified_joiner.status().unwrap().room_id.is_none()); + assert_eq!(secret_files(&verified_joiner), 0); + { + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 2, "both devices were asked to compare"); + assert_eq!(seen[0].0, seen[1].0, "honest devices show one code"); + assert!(seen.iter().all(|(_, name)| !name.is_empty())); + } + seen.lock().unwrap().clear(); + + // Both users confirm matching codes: the pairing commits on both. + let (creator_verifier, joiner_verifier) = verifier_pair(true, true, &seen); + let offer = verified_creator + .create_room_verified(creator_verifier) + .unwrap(); + let joined = verified_joiner + .join_room_verified(offer.pairing_code, joiner_verifier) + .unwrap(); + assert_eq!(joined, offer.room_id); + let until = std::time::Instant::now() + Duration::from_secs(5); + while verified_creator.status().unwrap().room_id.as_deref() != Some(joined.as_str()) { + assert!( + std::time::Instant::now() < until, + "verified creator did not commit completed pairing" + ); + std::thread::sleep(Duration::from_millis(5)); + } + assert_ne!( + verified_creator.status().unwrap().room_id.as_deref(), + Some(refused.room_id.as_str()), + "the refused room must never be committed" + ); + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 2); + assert_eq!(seen[0].0, seen[1].0); std::env::set_var( "CLIPSYNC_HOME", client.app.store.paths.data_dir.parent().unwrap(), diff --git a/crates/clipsync-relay/src/ws_tests.rs b/crates/clipsync-relay/src/ws_tests.rs index d2d9f21..a1f3592 100644 --- a/crates/clipsync-relay/src/ws_tests.rs +++ b/crates/clipsync-relay/src/ws_tests.rs @@ -1217,6 +1217,10 @@ fn regression_f98_late_creator_completes_real_core_pairing_and_persists_matching clipsync_crypto::DeviceIdentity::from_bytes("late-creator".into(), [81; 32]); let member = clipsync_crypto::DeviceIdentity::from_bytes("early-joiner".into(), [82; 32]); + // Each side shows its verification code to the other and + // confirms only on a match, as two users comparing screens would. + let (owner_sas_tx, owner_sas_rx) = tokio::sync::oneshot::channel::(); + let (member_sas_tx, member_sas_rx) = tokio::sync::oneshot::channel::(); let owner_task = { let store = owner_store.clone(); tokio::spawn(async move { @@ -1225,6 +1229,15 @@ fn regression_f98_late_creator_completes_real_core_pairing_and_persists_matching &owner, &store.load_config().unwrap(), 60, + move |check: clipsync_core::SasCheck| async move { + let _ = owner_sas_tx.send(check.sas.clone()); + match member_sas_rx.await { + Ok(other) if check.matches(&other) => { + clipsync_core::SasDecision::Confirmed + } + _ => clipsync_core::SasDecision::Rejected, + } + }, ) .await }) @@ -1239,6 +1252,15 @@ fn regression_f98_late_creator_completes_real_core_pairing_and_persists_matching &member, &store.load_config().unwrap(), &code, + move |check: clipsync_core::SasCheck| async move { + let _ = member_sas_tx.send(check.sas.clone()); + match owner_sas_rx.await { + Ok(other) if check.matches(&other) => { + clipsync_core::SasDecision::Confirmed + } + _ => clipsync_core::SasDecision::Rejected, + } + }, ) .await }) diff --git a/crates/clipsync-relay/tests/e2e.rs b/crates/clipsync-relay/tests/e2e.rs index 10da54b..87011f2 100644 --- a/crates/clipsync-relay/tests/e2e.rs +++ b/crates/clipsync-relay/tests/e2e.rs @@ -4,7 +4,7 @@ use std::net::SocketAddr; use std::time::Duration; use clipsync_clipboard::{ClipboardItem, FileRef, ImageMime, MockClipboard, SystemClipboard}; -use clipsync_core::{begin_create_room, join_room, App}; +use clipsync_core::{begin_create_room, join_room, App, SasCheck, SasDecision}; use clipsync_crypto::blake3_hex; use clipsync_protocol::{FILE_MAX_COUNT, FRAME_HARD_CAP, IMAGE_MAX_BYTES, TEXT_MAX_BYTES}; use clipsync_relay::{router, RelayConfig}; @@ -80,6 +80,42 @@ fn store_in(dir: &TempDir) -> clipsync_storage::LocalStore { .store } +type SasConfirm = Box< + dyn FnOnce(SasCheck) -> std::pin::Pin + Send>> + + Send, +>; + +/// Two confirmers that compare SAS values the way two users would: each +/// device shows its value to the other and confirms only on a match. +fn sas_comparison() -> (SasConfirm, SasConfirm) { + fn side( + mine: tokio::sync::oneshot::Sender, + theirs: tokio::sync::oneshot::Receiver, + ) -> SasConfirm { + Box::new(move |check: SasCheck| { + Box::pin(async move { + let _ = mine.send(check.sas.clone()); + match theirs.await { + Ok(other) if check.matches(&other) => SasDecision::Confirmed, + _ => SasDecision::Rejected, + } + }) + }) + } + let (creator_tx, creator_rx) = tokio::sync::oneshot::channel(); + let (joiner_tx, joiner_rx) = tokio::sync::oneshot::channel(); + (side(creator_tx, joiner_rx), side(joiner_tx, creator_rx)) +} + +fn stored_secrets(dir: &TempDir) -> Vec { + let store = store_in(dir); + std::fs::read_dir(&store.paths.data_dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|name| name.ends_with(".secret")) + .collect() +} + // Two peers share this runtime; keep workers free for I/O during OS keychain calls. async fn pair_homes(relay: &str) -> (TempDir, TempDir) { let a_dir = TempDir::new().unwrap(); @@ -96,7 +132,8 @@ async fn pair_homes(relay: &str) -> (TempDir, TempDir) { assert_eq!(code.len(), 6); let store_a = store_in(&a_dir); - let wait_a = tokio::spawn(async move { pending.wait(&store_a, &id_a).await }); + let (creator_sas, joiner_sas) = sas_comparison(); + let wait_a = tokio::spawn(async move { pending.wait(&store_a, &id_a, creator_sas).await }); wait_for_connection_count(relay, 1).await; let creator = async { wait_a @@ -105,7 +142,7 @@ async fn pair_homes(relay: &str) -> (TempDir, TempDir) { .map_err(|error| format!("creator pairing failed: {error}")) }; let joiner = async { - join_room(&app_b.store, &id_b, &cfg_b, &code) + join_room(&app_b.store, &id_b, &cfg_b, &code, joiner_sas) .await .map(|_| ()) .map_err(|error| format!("joiner pairing failed: {error}")) @@ -616,6 +653,140 @@ async fn format_matrix_files_roundtrip() { } } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn real_relay_pairing_shows_both_devices_the_same_sas_and_names() { + let (relay, _h) = start_relay().await; + let a_dir = TempDir::new().unwrap(); + let b_dir = TempDir::new().unwrap(); + let app_a = app_in(&a_dir, &relay); + let app_b = app_in(&b_dir, &relay); + let (id_a, id_b) = (app_a.identity().unwrap(), app_b.identity().unwrap()); + let cfg_a = app_a.store.load_config().unwrap(); + let cfg_b = app_b.store.load_config().unwrap(); + let pending = begin_create_room(&id_a, &cfg_a, 60).await.unwrap(); + let code = pending.offer.pairing_code.clone(); + let (seen_a_tx, seen_a) = tokio::sync::oneshot::channel(); + let (seen_b_tx, seen_b) = tokio::sync::oneshot::channel(); + let (creator_sas, joiner_sas) = sas_comparison(); + let store_a = store_in(&a_dir); + let creator_id = id_a.clone(); + let creator = tokio::spawn(async move { + pending + .wait(&store_a, &creator_id, move |check: SasCheck| { + let _ = seen_a_tx.send(check.clone()); + creator_sas(check) + }) + .await + }); + wait_for_connection_count(&relay, 1).await; + tokio::time::timeout( + Duration::from_secs(20), + join_room( + &app_b.store, + &id_b, + &cfg_b, + &code, + move |check: SasCheck| { + let _ = seen_b_tx.send(check.clone()); + joiner_sas(check) + }, + ), + ) + .await + .unwrap() + .unwrap(); + creator.await.unwrap().unwrap(); + let (seen_a, seen_b) = (seen_a.await.unwrap(), seen_b.await.unwrap()); + assert_eq!(seen_a.sas, seen_b.sas); + assert_eq!(seen_a.peer_device_id, id_b.device_id); + assert_eq!(seen_b.peer_device_id, id_a.device_id); + assert!(!seen_a.peer_device_name.is_empty() && !seen_b.peer_device_name.is_empty()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn rejected_sas_leaves_both_devices_without_room_keys_or_credentials() { + let (relay, _h) = start_relay().await; + let a_dir = TempDir::new().unwrap(); + let b_dir = TempDir::new().unwrap(); + let app_a = app_in(&a_dir, &relay); + let app_b = app_in(&b_dir, &relay); + let (id_a, id_b) = (app_a.identity().unwrap(), app_b.identity().unwrap()); + let cfg_a = app_a.store.load_config().unwrap(); + let cfg_b = app_b.store.load_config().unwrap(); + let pending = begin_create_room(&id_a, &cfg_a, 60).await.unwrap(); + let code = pending.offer.pairing_code.clone(); + let (release_tx, release) = tokio::sync::oneshot::channel::<()>(); + let store_a = store_in(&a_dir); + let creator_id = id_a.clone(); + // The creator's user is slow and confirms only after the joiner refused. + let creator = tokio::spawn(async move { + pending + .wait(&store_a, &creator_id, move |_| async move { + let _ = release.await; + SasDecision::Confirmed + }) + .await + }); + wait_for_connection_count(&relay, 1).await; + let joined = tokio::time::timeout( + Duration::from_secs(20), + join_room(&app_b.store, &id_b, &cfg_b, &code, |_| async { + SasDecision::Rejected + }), + ) + .await + .unwrap(); + assert!(joined + .unwrap_err() + .to_string() + .contains("verification code rejected")); + // Fence on the relay dropping the aborted session before the creator binds. + let client = loopback_http_client(); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let body = client + .post(format!("{relay}/v1/pairing/join")) + .json(&clipsync_protocol::JoinPairingRequest { + pairing_code: code.clone(), + device_id: clipsync_protocol::DeviceId::new(), + device_name: "fence".into(), + os: "test".into(), + protocol_version: clipsync_protocol::PROTOCOL_VERSION, + }) + .send() + .await + .unwrap() + .text() + .await + .unwrap(); + if body.contains("code_invalid") { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("relay kept the rejected pairing session"); + release_tx.send(()).unwrap(); + let created = tokio::time::timeout(Duration::from_secs(20), creator) + .await + .unwrap() + .unwrap(); + let refused = created.expect_err("creator must not complete a rejected pairing"); + assert!( + refused + .to_string() + .contains("the other device rejected the verification code"), + "{refused}" + ); + for dir in [&a_dir, &b_dir] { + let store = store_in(dir); + assert!(store.load_state().unwrap().rooms.is_empty()); + assert!(store.current_room().is_err()); + assert!(stored_secrets(dir).is_empty(), "{:?}", stored_secrets(dir)); + } +} + #[tokio::test] async fn wrong_pairing_code_rejected() { let (relay, _h) = start_relay().await; @@ -623,9 +794,11 @@ async fn wrong_pairing_code_rejected() { let app = app_in(&dir, &relay); let id = app.identity().unwrap(); let cfg = app.store.load_config().unwrap(); - let err = join_room(&app.store, &id, &cfg, "000000") - .await - .unwrap_err(); + let err = join_room(&app.store, &id, &cfg, "000000", |_| async { + SasDecision::Confirmed + }) + .await + .unwrap_err(); let msg = err.to_string(); assert!( msg.contains("join failed") || msg.contains("code"), diff --git a/crates/clipsync-storage/src/store.rs b/crates/clipsync-storage/src/store.rs index 91a7fef..33b7bf1 100644 --- a/crates/clipsync-storage/src/store.rs +++ b/crates/clipsync-storage/src/store.rs @@ -49,6 +49,15 @@ pub struct PairingWait { pub pid: u32, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option, + /// SAS the background worker asks the user to compare (status `confirm_sas`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sas: Option, + /// Relay-reported name of the joining device, shown next to the SAS. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub peer_device_name: Option, + /// The user's answer, written by `clipsync room confirm` or `room reject`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sas_decision: Option, } #[derive(Clone)] @@ -145,7 +154,9 @@ impl LocalStore { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } - let tmp = path.with_extension("json.tmp"); + // The background worker and `room confirm`/`room reject` both write + // this file; a per-process temporary name keeps their renames whole. + let tmp = path.with_extension(format!("json.{}.tmp", std::process::id())); std::fs::write(&tmp, serde_json::to_vec_pretty(wait)?)?; set_private_file(&tmp)?; std::fs::rename(tmp, path)?; @@ -298,6 +309,9 @@ mod failure_tests { expires_at: "2026-11-15T00:00:00Z".into(), pid: 1, error: None, + sas: None, + peer_device_name: None, + sas_decision: None, } } @@ -351,8 +365,12 @@ mod failure_tests { assert!(store.save_pairing_wait(&waiting()).is_err()); assert!(store.paths.pairing_file().is_dir()); std::fs::remove_dir(store.paths.pairing_file()).unwrap(); - std::fs::remove_file(store.paths.pairing_file().with_extension("json.tmp")).unwrap(); - std::fs::create_dir(store.paths.pairing_file().with_extension("json.tmp")).unwrap(); + let tmp = store + .paths + .pairing_file() + .with_extension(format!("json.{}.tmp", std::process::id())); + std::fs::remove_file(&tmp).unwrap(); + std::fs::create_dir(&tmp).unwrap(); assert!(store.save_pairing_wait(&waiting()).is_err()); } diff --git a/docs/assurance-case.md b/docs/assurance-case.md index 71300f7..366e8cd 100644 --- a/docs/assurance-case.md +++ b/docs/assurance-case.md @@ -22,9 +22,10 @@ a correctly authenticated out-of-band pairing-code exchange, private local data directories and correctly configured HTTPS/WSS for public transport. Attackers may control the network, malformed protocol/file inputs or a webhook destination. The relay generates the pairing password, so a malicious relay -operator during pairing is outside the confidentiality guarantee: knowing the -password can enable impersonation of a pairing participant. Use a trusted relay -for pairing. TLS authenticates the selected service; it does not make a malicious +operator can run one SPAKE2 session with each device. Users compare a +verification code (SAS) before anything is stored, which detects this unless +the relay searches offline for colliding codes; see +[security](security.md#verification-code-sas). Use a trusted relay for pairing. TLS authenticates the selected service; it does not make a malicious service operator trustworthy. This is the honest-but-curious relay model already stated in the security requirements. An authorized malicious peer can intentionally send content; the receiver still treats its filenames, manifests and sizes as untrusted. Relay diff --git a/docs/interfaces.md b/docs/interfaces.md index 2b17621..8cb7779 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -28,7 +28,7 @@ required. All commands accept `-h`/`--help` and `-V`/`--version`. | --- | --- | | `--json` | Print command result objects/arrays as compact JSON, one value per line. Streaming pairing can emit multiple values. | | `--yes` | Confirm room removal without an interactive confirmation. | -| `--non-interactive` | Never prompt; the current `room leave` handler also treats this as confirmation. | +| `--non-interactive` | Never prompt; the current `room leave` handler also treats this as confirmation. A verification-code prompt fails instead (pass the code to `room confirm`, or `--insecure-skip-sas`). | Successful commands exit with `0`. Ordinary runtime errors print `error: ` to **stderr**, including with `--json`; they do not have a @@ -45,8 +45,10 @@ output is empty; errors follow the convention above. | Command and inputs | Effect and normal-mode output | JSON result | | --- | --- | --- | | `init [--relay-url URL]` | Create/reuse the local identity; optionally save a relay URL. Print device ID and fingerprint. | `{device_id: string, fingerprint: string}` | -| `room create [--ttl DURATION] [--no-auto-sync] [--foreground]` | Print a six-digit pairing code, room, and expiry. Default: detach the pairing wait and return after the offer is available. `--foreground` (alias `--wait`) waits for pairing and prints `paired` on success. | First `{event: "pairing_code", pairing_code: string, room_id: string, expires_at: time}`. Background mode adds `{background: true, pid: integer}`; foreground mode later emits `{ok: true, pairing_code: string, room_id: string}`. | -| `room join CODE [--no-auto-sync]` | Join using the code string, preserving any leading zero. Wait for pairing and print the room ID. | `{room_id: string, role: "member"}` | +| `room create [--ttl DURATION] [--no-auto-sync] [--foreground] [--insecure-skip-sas]` | Print a six-digit pairing code, room, and expiry. Default: detach the pairing wait and return after the offer is available; answer the verification code later with `room confirm` or `room reject`. `--foreground` (alias `--wait`) waits in this terminal, asks for the verification code like `room join`, and prints `paired` on success. | First `{event: "pairing_code", pairing_code: string, room_id: string, expires_at: time}`. Background mode adds `{background: true, pid: integer}`; foreground mode later emits the SAS event below, then `{ok: true, pairing_code: string, room_id: string}`. | +| `room join CODE [--no-auto-sync] [--insecure-skip-sas]` | Join using the code string, preserving any leading zero. After key confirmation, print the verification code and the other device's name and read one answer line from stdin: `y`/`yes`, or the code shown on the other device, confirms; anything else or end of input rejects and stores nothing. Then wait for pairing and print the room ID. | `{event: "sas_confirmation", sas: string, peer_device_name: string}`, then `{room_id: string, role: "member"}` | +| `room confirm [CODE]` | Answer a background `room create`. Waits for the joiner if needed, then compares `CODE` (the code shown on the other device) or prompts like `room join`. A mismatch aborts the pairing. On a match, waits for the worker and prints `paired`. | Without `CODE`, the SAS event above; then `{ok: true, room_id: string}`. | +| `room reject` | Abort a background `room create`. At the verification step, waits until the worker has stopped, then reports that nothing was stored; fails if the code was already confirmed. Before a device joins, records the rejection (the worker stops when one joins) and lets a new `room create` start at once. | `{ok: true, rejected: true}`; before a join also `joined: false` | | `room leave [--yes]` | Stop/uninstall the login daemon, remove the current local room, and clear pending pairing state. Requires local/global `--yes` or global `--non-interactive`; otherwise fails rather than prompting. | `{ok: true}` | | `room list` | Print locally stored rooms with epoch and role. | Array of `RoomRecord` values below. | | `push [--type auto\|text\|image\|files] [--file PATH]...` | Read files, stdin, or the clipboard using the precedence below; print a summary. | `{ok: true, summary: string}` | @@ -95,7 +97,7 @@ not printed. Clipboard write failures in `pull --copy` are currently best effort | --- | --- | | `PeerRecord` | `device_id`, `device_name`, `os`, `public_key_hex`, `fingerprint`: strings; `role`: `owner` or `member`. | | `RoomRecord` | `room_id`: string; `epoch`: unsigned integer; `role`: `owner` or `member`; `created_at`: time; `device_token`: secret string; `peers`: array of `PeerRecord`. | -| Status without daemon | `daemon: false`, `paused`, `connected: false`, `peer_online: false`: booleans; `room_id`, `device_id`: nullable strings; `relay_url`: string. Optional `pairing` contains `status` (`waiting`, `paired`, `failed`), `pairing_code`, `room_id`, `expires_at`: strings; `pid`: integer; optional `error`: string. | +| Status without daemon | `daemon: false`, `paused`, `connected: false`, `peer_online: false`: booleans; `room_id`, `device_id`: nullable strings; `relay_url`: string. Optional `pairing` contains `status` (`waiting`, `confirm_sas`, `paired`, `failed`), `pairing_code`, `room_id`, `expires_at`: strings; `pid`: integer; optional `error`, `sas`, `peer_device_name`, `sas_decision` (`confirmed`/`rejected`): strings. | | Status with daemon | `daemon: true`, `paused`, `connected`, `peer_online`: booleans; `room_id`, `device_id`, `device_name`, `relay_url`: nullable strings; `last_item_kind`: nullable `text`/`image`/`files`; `last_sync_at`: nullable string (currently always `null`). | | Doctor | `identity`, `daemon_socket`, `login_service`: booleans; `device_id`, `fingerprint`, `room`: nullable strings; `relay_url`: string; `clipboard`: nullable `{name, source: string, text, image, files: boolean, fallback: string\|null}`; `tools`: array of `[tool_name, found_boolean]`; `relay`: `{ok: boolean, status: integer}` or `{ok: false, error: string}`; `tls`: `{verifier: "platform", ca_file: string\|null}`; `paths`: `{config_dir, data_dir, log_file: string}`. | @@ -328,8 +330,10 @@ runtime, or thread-start failures and are not stable machine error codes. | --- | --- | --- | | `ClipSyncClient::new` | `data_dir`, `relay_url`, `os`, `device_name`: strings. | Shared client object. Creates app directories and a runtime; attempts identity/config initialization with the supplied relay. `data_dir` is the root layout described under `CLIPSYNC_HOME`. Empty OS/name leave existing overrides alone. The initialization attempt's error is currently not propagated; use `status()` to confirm the stored identity/config. | | `status()` | None. | `MobileStatus {device_id, fingerprint, relay_url, os: string, room_id: string?}`. Creates/reuses identity; an unpaired client has a null room ID. | -| `create_room()` | None. | `PairingOffer {pairing_code, room_id, expires_at: string}`; expiry is RFC 3339. Returns after the offer is available and waits for the joiner in a background task. The offer alone does not mean pairing completed; poll until `status().room_id` equals the offered room ID. Later pairing failures are logged rather than returned from this completed call. | -| `join_room(code)` | Six-digit code string, preserving leading zeros. | Room ID string after the pairing handshake completes and state is saved. | +| `create_room_verified(verifier)` | Host implementation of `SasVerifier`. | `PairingOffer {pairing_code, room_id, expires_at: string}`; expiry is RFC 3339. Returns after the offer is available and waits for the joiner in a background task, which calls `verifier.confirm_sas` before anything is sent or stored. The offer alone does not mean pairing completed; poll until `status().room_id` equals the offered room ID. Later pairing failures, including a rejected code, are logged rather than returned from this completed call. | +| `join_room_verified(code, verifier)` | Six-digit code string, preserving leading zeros; `SasVerifier`. | Room ID string after the handshake completes, `verifier` confirmed, and state is saved. A rejected code returns an error and stores nothing. | +| `create_room()` | None. | Same as `create_room_verified` but accepts without comparing verification codes. Kept so existing apps keep working; it cannot detect a malicious relay or a guessed code. | +| `join_room(code)` | Six-digit code string, preserving leading zeros. | Same as `join_room_verified` but accepts without comparing verification codes. Kept for existing apps; same limitation. | | `start_sync(clipboard)` | Host implementation of `ClipboardBridge`. | Returns unit after starting a background thread; repeated calls on the same client return success without starting another loop. Requires paired state for useful sync. Subsequent loop failures are logged, not delivered to the caller. No stop/pause/dispose-sync method is exported. | These are synchronous FFI methods: network operations in create/join block the @@ -340,6 +344,20 @@ is cached; use one active identity/client configuration per process rather than assuming independent instances. Neither pairing method installs an OS login service; native apps call `start_sync` and manage platform lifecycle. +`SasVerifier.confirm_sas(sas, peer_device_name) -> bool` is called once per +pairing on a background thread, after key confirmation. Show the six-digit +`sas` (for example as `482 913`) and the relay-reported `peer_device_name`, ask +whether the other device shows the same code, block until the user answers, +and return `true` only for a match. Returning `false` aborts the pairing and +stores nothing. The pairing deadline is 120 seconds from the offer, not from +the prompt. If the pairing ends before the user answers (deadline, the other +device rejected, relay error), `SasVerifier.sas_cancelled()` is called: dismiss +the dialog and let the pending `confirm_sas` return; its answer is ignored. +`sas_cancelled` must not block. Marshal the dialog to the UI thread; do not +block the UI thread waiting for it. Keep the client alive until the dialog is +dismissed, because dropping it waits for a blocked `confirm_sas`. See +[security](security.md#verification-code-sas). + Implement every callback in `ClipboardBridge`; it is a thread-safe (`Send + Sync`) interface called by the background sync runtime. Marshal any UI- or OS-main-thread-only work in the host app: diff --git a/docs/mobile.md b/docs/mobile.md index 52d3de4..888e3ed 100644 --- a/docs/mobile.md +++ b/docs/mobile.md @@ -47,3 +47,7 @@ See [dependency migration](dependency-migration.md) for validation details. `CLIPSYNC_CORE` can point at a non-sibling checkout of this repository. Pair with the desktop CLI as usual (`clipsync room create` / `room join`). +Use `create_room_verified` / `join_room_verified` with a `SasVerifier` that shows +the verification code and asks the user to compare it with the other device; +see [interfaces](interfaces.md) and [security](security.md#verification-code-sas). +The older `create_room()` / `join_room()` still work but skip the comparison. diff --git a/docs/protocol.md b/docs/protocol.md index 5e19e25..19051ea 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -54,10 +54,32 @@ HKDF-SHA-256 labels: - `clipsync/v1/confirm-b` - `clipsync/v1/pairing-wrap` - `clipsync/v1/room-root` +- `clipsync/v1/sas` - `clipsync/v1/epoch/1` - `clipsync/v1/content/{transferId}` - `clipsync/v1/nonce/{chunkIndex}` +## Pairing verification code (SAS) + +Computed locally on each device from its SPAKE2 secret; nothing is added to +the wire: + +``` +sas_key = HKDF-SHA-256(ikm = spake2_secret, salt = SHA-256(transcript), + info = "clipsync/v1/sas") +sas = decimal(u64be(sas_key[0..8]) mod 10^6), zero-padded to 6 digits +``` + +After verifying the peer's `key_confirm`, a client shows the SAS and waits for +the local user. It sends its `device_bind` only after the user confirms. It +stores room keys, the room record, and the device token only after its own +`device_bind` went out and the peer's `device_bind` and `pairing_complete` +arrived. On rejection it sends `error` with code `sas_rejected`; the relay +aborts the pairing session on any client `error`. Pre-SAS clients send +`device_bind` right after key confirmation; a SAS client buffers it until its +user confirms. See [security](security.md#verification-code-sas) for what the +comparison covers. + ## Reconnect Noise pattern `Noise_KK_25519_AESGCM_SHA256` using long-term X25519 device diff --git a/docs/security.md b/docs/security.md index d56afc2..30a0ed3 100644 --- a/docs/security.md +++ b/docs/security.md @@ -6,6 +6,8 @@ To disclose a vulnerability privately, follow the [security policy](../SECURITY. - Honest-but-curious relay operator - Pairing-code guessing +- A relay that runs one SPAKE2 session with each device during pairing, within + the limit described under [Verification code](#verification-code-sas) - Replay, truncation, and chunk reordering - Path traversal on received files - Oversized payloads and connection floods @@ -17,11 +19,68 @@ SPAKE2 transcript to the protocol version, pairing session ID, and device IDs, then exchange HMAC confirmations. Wrong code, mutated transcript, or failed confirmation aborts without storing credentials. -The relay generates this password. Pair through a trusted relay: an actively -malicious operator who knows the password is outside the honest-but-curious -model and may impersonate a pairing participant. HTTPS/WSS authenticates the -chosen relay and protects traffic in transit; it does not establish that the -operator is honest. +The relay generates this password and sees it in the create response and the +join request. HTTPS/WSS authenticates the chosen relay and protects traffic in +transit; it does not establish that the operator is honest. A relay that knows +the password can run one SPAKE2 session with each device. Key confirmation +then succeeds on both devices, because each device really did agree a key with +the relay. The verification code below is the check that catches this. + +### Verification code (SAS) + +After key confirmation, each device derives a 6-digit short authentication +string from its own SPAKE2 result: + +``` +HKDF-SHA-256(ikm = SPAKE2 secret, salt = transcript hash, + info = "clipsync/v1/sas")[0..8] as u64be mod 10^6 +``` + +Both devices show the code and the other device's relay-reported name. The +user confirms only if the two screens show the same code. Two devices show the +same code only when they ran SPAKE2 with each other: + +- **Relay in the middle.** Each device ran SPAKE2 with the relay, so each + derived a different secret and transcript, and the codes differ. +- **Guessed code.** A joiner who guessed the pairing code completed SPAKE2 + with the creator. The device the user meant to pair never joined, so it + shows no matching code, and the creator's user rejects. + +Until the user confirms, the device sends no `device_bind` and stores no room +keys, room record, or device token. A rejection, an unanswered prompt, or the +pairing deadline aborts with nothing stored. The deadline runs from when the +code was created, not from when the prompt appears: the relay keeps a pairing +session for 120 seconds after `room create`, so joining and comparing must both +fit in that window. On rejection the device sends an `error` frame (`sas_rejected`), and +the relay drops the pairing session. If the other device has not answered yet, +its later `device_bind` is refused. If it already confirmed, it stores nothing +and fails at its pairing deadline. The peer name comes from the relay and is +not authenticated; only the code is. + +Users must actually compare the codes. Typing the code shown on the other +device is the most reliable comparison; answering "yes" relies on the user +having looked. + +**Limit: offline search by a relay.** There is no commitment step: a device +sends its SPAKE2 message before it sees the peer's. A relay in the middle sees +both honest messages before it picks its own message toward each device. It can +therefore search offline for a pair of its own messages that make the two +devices derive the same 6-digit code. This is a birthday search of roughly +2^10 cheap trials per side, so a relay that is built to do this can defeat the +comparison. The code fully stops a guessed-code joiner and any relay that does +not run this search, and it makes an attack an explicit, targeted change to +the relay. Closing the gap needs a commitment to the SPAKE2 messages, which is +a protocol change and is not part of this version. Until then, pair through a +relay you trust. + +**Older peers.** The code is computed locally, so the wire format is unchanged +and an updated device still pairs with an older one. The older device shows no +code, so the comparison cannot be made. Treat such a pairing as unverified, or +update both devices first. + +**Skipping the comparison.** `clipsync room create|join --insecure-skip-sas` +and the mobile `create_room()` / `join_room()` calls, kept for existing apps, +accept without comparing. They provide none of the protection above. Device-binding messages share a session wrapping key but use sender-specific nonce domains (A: index 2, B: index 3). Index 1 is reserved for legacy senders; @@ -102,7 +161,7 @@ to implementations and tests and records unresolved limits. A compromised or unlocked authorized endpoint can read clipboard contents and keys. Same-user local malware and administrators are outside the confidentiality guarantee. Pairing codes must be shared through an authenticated separate -channel. Use HTTPS/WSS with trusted certificates for public deployments; the +channel, and users must compare the verification code on both devices. Use HTTPS/WSS with trusted certificates for public deployments; the relay requires a TLS certificate/key pair by default and permits only TLS 1.2/1.3. Its explicit HTTP opt-in requires TLS termination and network restrictions for public deployments; see [self-hosting](self-hosting.md). diff --git a/scripts/e2e-brew.py b/scripts/e2e-brew.py index c35ad6f..46c4fcb 100755 --- a/scripts/e2e-brew.py +++ b/scripts/e2e-brew.py @@ -68,6 +68,62 @@ def spawn_create(home: Path) -> tuple[int, int]: return pid, fd +def env_for(home: Path) -> dict: + env = os.environ.copy() + env["CLIPSYNC_HOME"] = str(home) + env["CLIPSYNC_NO_DAEMON"] = "1" + env["CLIPSYNC_RELAY_URL"] = RELAY + return env + + +def join_comparing_sas(a: Path, b: Path, code: str) -> str: + """Join from B and compare verification codes the way two users would. + + B prints its code and reads an answer on stdin; A's background worker + publishes its code in `status`. Each side is given the other's code. + """ + join = subprocess.Popen( + [CS, "room", "join", code, "--no-auto-sync"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=env_for(b), + text=True, + ) + try: + joiner_sas = None + deadline = time.time() + TIMEOUT + assert join.stdout is not None and join.stdin is not None + while time.time() < deadline and joiner_sas is None: + line = join.stdout.readline() + if not line: + break + if line.startswith("verification code: "): + joiner_sas = "".join(ch for ch in line if ch.isdigit()) + if not joiner_sas: + raise Fail(f"joiner printed no verification code: {join.stderr.read() if join.stderr else ''}") + creator_sas = None + while time.time() < deadline: + pairing = run_json(a, "status", timeout=5).get("pairing") or {} + if pairing.get("status") == "confirm_sas" and pairing.get("sas"): + creator_sas = pairing["sas"] + break + time.sleep(0.2) + if creator_sas != joiner_sas: + raise Fail(f"verification codes differ: creator={creator_sas} joiner={joiner_sas}") + log(f"verification codes match ({creator_sas})") + join.stdin.write(creator_sas + "\n") + join.stdin.flush() + log(run(a, "room", "confirm", joiner_sas, timeout=TIMEOUT).strip()) + out, err = join.communicate(timeout=TIMEOUT) + if join.returncode != 0: + raise Fail(f"join rc={join.returncode}\nstdout:\n{out}\nstderr:\n{err}") + return out + finally: + if join.poll() is None: + join.kill() + + def read_until_code(fd: int, deadline: float) -> str: buf = "" while time.time() < deadline: @@ -164,7 +220,11 @@ def main() -> int: if not code: raise Fail(f"no pairing code: {offer}") log(f"pairing code={code} background={offer.get('background')}") - join_out = run(b, "room", "join", code, "--no-auto-sync", timeout=TIMEOUT) + room_help = subprocess.check_output([CS, "room", "--help"], text=True) + if "confirm" in room_help: + join_out = join_comparing_sas(a, b, code) + else: + join_out = run(b, "room", "join", code, "--no-auto-sync", timeout=TIMEOUT) log(join_out.strip()) deadline = time.time() + TIMEOUT while time.time() < deadline: diff --git a/scripts/local-two-homes.sh b/scripts/local-two-homes.sh index c4cfd83..da52300 100755 --- a/scripts/local-two-homes.sh +++ b/scripts/local-two-homes.sh @@ -11,4 +11,5 @@ echo "Home A: CLIPSYNC_HOME=$A" echo "Home B: CLIPSYNC_HOME=$B" echo "Start the relay, then:" echo " CLIPSYNC_HOME=$A cargo run -p clipsync-cli -- room create --no-auto-sync # inits, prints code, waits in background" -echo " CLIPSYNC_HOME=$B cargo run -p clipsync-cli -- room join --no-auto-sync" +echo " CLIPSYNC_HOME=$B cargo run -p clipsync-cli -- room join --no-auto-sync # shows a verification code" +echo " CLIPSYNC_HOME=$A cargo run -p clipsync-cli -- room confirm # compare codes; confirm on both homes"