diff --git a/projects/start-cli/changelog/patch-changed-registry-transport.md b/projects/start-cli/changelog/patch-changed-registry-transport.md index de84c76bc9..3bb33f7b1c 100644 --- a/projects/start-cli/changelog/patch-changed-registry-transport.md +++ b/projects/start-cli/changelog/patch-changed-registry-transport.md @@ -12,3 +12,4 @@ release-notes: false - Preserve deployment URL prefixes ending in a slash for RPC and continuation calls. - Preserve logical HTTP hostnames and ports when `.local` resolution pins an encrypted RPC or continuation's dial address. - Warn on registry CLI server-identity changes without interrupting commands; remember the new verified key while preserving JSON output and exit status. +- When this computer's clock is wrong, sign encrypted connections to StartOS, StartTunnel and registries again with the server's clock, and say the clock is wrong if the server still rejects it. diff --git a/projects/start-os/changelog/patch-changed-rpc-authentication.md b/projects/start-os/changelog/patch-changed-rpc-authentication.md index 381c9aaf7e..13b7ae54cb 100644 --- a/projects/start-os/changelog/patch-changed-rpc-authentication.md +++ b/projects/start-os/changelog/patch-changed-rpc-authentication.md @@ -20,3 +20,4 @@ release-notes: false - Keep encrypted browser RPC available over HTTP/2 connections. - Cancel timed-out or disposed WebSocket requests without interrupting sibling calls, and release pending handlers when the socket closes. - Log decrypted browser RPC requests and replies to the developer console for 30 minutes after `rpcLog.enable()`, or a chosen number of minutes, until it expires or `rpcLog.disable()`. +- Sign the browser's encrypted RPC connection with the server's clock when this device's clock is wrong, so signing in, setup and RPC still work. diff --git a/projects/start-registry/changelog/patch-changed-session-clock.md b/projects/start-registry/changelog/patch-changed-session-clock.md new file mode 100644 index 0000000000..e9c3db68bd --- /dev/null +++ b/projects/start-registry/changelog/patch-changed-session-clock.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Answer an encrypted connection signed with a wrong clock with the registry's time, so clients whose clock is wrong can still connect. diff --git a/projects/start-tunnel/changelog/patch-changed-rpc-authentication.md b/projects/start-tunnel/changelog/patch-changed-rpc-authentication.md index 36f3273ffb..9bfd07daa6 100644 --- a/projects/start-tunnel/changelog/patch-changed-rpc-authentication.md +++ b/projects/start-tunnel/changelog/patch-changed-rpc-authentication.md @@ -14,3 +14,4 @@ release-notes: false - Keep encrypted browser RPC available over HTTP/2 connections. - Cancel timed-out or disposed WebSocket requests without interrupting sibling calls, and release pending handlers when the socket closes. - Log decrypted browser RPC requests and replies to the developer console for 30 minutes after `rpcLog.enable()`, or a chosen number of minutes, until it expires or `rpcLog.disable()`. +- Sign the browser's encrypted RPC connection with the server's clock when this device's clock is wrong, so the web interface still works. diff --git a/projects/start-tunnel/web/src/app/i18n/dictionaries/en.ts b/projects/start-tunnel/web/src/app/i18n/dictionaries/en.ts index 813d95a48d..a8d55b1b07 100644 --- a/projects/start-tunnel/web/src/app/i18n/dictionaries/en.ts +++ b/projects/start-tunnel/web/src/app/i18n/dictionaries/en.ts @@ -147,6 +147,7 @@ export const ENGLISH: Record = { 'This browser is not enrolled yet': 133, 'Cancel': 134, 'Continue': 135, + "The server rejected this device's clock; check this device's date, time and time zone": 136, } export default ENGLISH diff --git a/projects/start-tunnel/web/src/app/i18n/dictionaries/es.ts b/projects/start-tunnel/web/src/app/i18n/dictionaries/es.ts index ffe0433a9d..810c1c13f5 100644 --- a/projects/start-tunnel/web/src/app/i18n/dictionaries/es.ts +++ b/projects/start-tunnel/web/src/app/i18n/dictionaries/es.ts @@ -138,6 +138,7 @@ const es: Record = { 133: 'Este navegador aún no está registrado', 134: 'Cancelar', 135: 'Continuar', + 136: 'El servidor rechazó el reloj de este dispositivo; compruebe la fecha, la hora y la zona horaria de este dispositivo', } export default es diff --git a/projects/start-wrt/changelog/patch-changed-rpc-authentication.md b/projects/start-wrt/changelog/patch-changed-rpc-authentication.md index 8de8d9d563..4ac8e7dbcd 100644 --- a/projects/start-wrt/changelog/patch-changed-rpc-authentication.md +++ b/projects/start-wrt/changelog/patch-changed-rpc-authentication.md @@ -19,3 +19,4 @@ release-notes: false - Cancel timed-out or disposed WebSocket requests without interrupting sibling calls, and release pending handlers when the socket closes. - Log decrypted browser RPC requests and replies to the developer console for 30 minutes after `rpcLog.enable()`, or a chosen number of minutes, until it expires or `rpcLog.disable()`. - Stream update progress and live logs over the encrypted RPC session instead of separate continuation sockets, ending log follow and update observation when the requesting key is revoked; the CLI and older clients keep the GUID WebSocket. +- Sign the browser's encrypted RPC connection with the router's clock when this device's clock is wrong, so the web interface and first-time setup still work. diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts index 6e50c583c5..0c8364f86b 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts @@ -605,4 +605,5 @@ export default { 653: '{port} sendet jedes Sicherheitsprofil mit seiner VLAN-ID getaggt an den Switch. Richten Sie die VLANs des Switches mit diesen IDs ein.', 654: '{profile} überschneidet sich mit dem vorgelagerten Netzwerk {network}', 655: 'Der Router kann den Zugang zum vorgelagerten Netzwerk oder zum Internet verlieren. Ein spezifischeres WAN-Netzwerk kann auch Geräten den Zugriff auf dieses Dashboard verwehren. Ändern Sie sein Subnetz in eines außerhalb dieses Netzwerks.', + 656: 'Der Server hat die Uhr dieses Geräts abgelehnt; prüfen Sie Datum, Uhrzeit und Zeitzone dieses Geräts', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts index 1482344004..081bf48b5b 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts @@ -610,4 +610,5 @@ export const ENGLISH: Record = { "{port} sends each security profile to the switch tagged with its VLAN ID. Set up the switch's VLANs with these IDs.": 653, '{profile} overlaps the upstream network {network}': 654, 'The router may lose upstream or Internet access. A more-specific WAN network can also block devices from this dashboard. Change its subnet to one outside that network.': 655, + "The server rejected this device's clock; check this device's date, time and time zone": 656, } diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts index 22262eb81d..464b9c5703 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts @@ -605,4 +605,5 @@ export default { 653: '{port} envía cada perfil de seguridad al switch etiquetado con su ID de VLAN. Configura las VLAN del switch con estos IDs.', 654: '{profile} se superpone con la red superior {network}', 655: 'El router puede perder el acceso a la red superior o a Internet. Una red WAN más específica también puede impedir que los dispositivos accedan a este panel. Cambie su subred a una fuera de esa red.', + 656: 'El servidor rechazó el reloj de este dispositivo; compruebe la fecha, la hora y la zona horaria de este dispositivo', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts index 0c78581aa1..ad97003447 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts @@ -605,4 +605,5 @@ export default { 653: '{port} envoie chaque profil de sécurité au switch, étiqueté avec son ID de VLAN. Configurez les VLAN du switch avec ces ID.', 654: '{profile} chevauche le réseau amont {network}', 655: 'Le routeur peut perdre l’accès au réseau amont ou à Internet. Un réseau WAN plus spécifique peut aussi empêcher les appareils d’accéder à ce tableau de bord. Changez son sous-réseau pour un sous-réseau hors de ce réseau.', + 656: "Le serveur a rejeté l'horloge de cet appareil ; vérifiez la date, l'heure et le fuseau horaire de cet appareil", } satisfies i18n diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts index 1a76547ed0..05652f0617 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts @@ -605,4 +605,5 @@ export default { 653: '{port} wysyła każdy profil bezpieczeństwa do przełącznika oznaczony jego identyfikatorem VLAN. Skonfiguruj sieci VLAN przełącznika z użyciem tych identyfikatorów.', 654: '{profile} nakłada się na sieć nadrzędną {network}', 655: 'Router może stracić dostęp do sieci nadrzędnej lub Internetu. Bardziej szczegółowa sieć WAN może też uniemożliwić urządzeniom dostęp do tego panelu. Zmień jego podsieć na leżącą poza tą siecią.', + 656: 'Serwer odrzucił zegar tego urządzenia; sprawdź datę, godzinę i strefę czasową tego urządzenia', } satisfies i18n diff --git a/shared-libs/crates/start-core/locales/i18n.yaml b/shared-libs/crates/start-core/locales/i18n.yaml index 7e36c9715e..6ec6678086 100644 --- a/shared-libs/crates/start-core/locales/i18n.yaml +++ b/shared-libs/crates/start-core/locales/i18n.yaml @@ -5417,6 +5417,13 @@ util.rpc.unknown-scheme: pl_PL: "nieznany schemat: %{scheme}" # util/net.rs +util.net.secure.clock-rejected: + en_US: "The server rejected this device's clock; check this device's date, time and time zone" + de_DE: "Der Server hat die Uhr dieses Geräts abgelehnt; prüfen Sie Datum, Uhrzeit und Zeitzone dieses Geräts" + es_ES: "El servidor rechazó el reloj de este dispositivo; compruebe la fecha, la hora y la zona horaria de este dispositivo" + fr_FR: "Le serveur a rejeté l'horloge de cet appareil ; vérifiez la date, l'heure et le fuseau horaire de cet appareil" + pl_PL: "Serwer odrzucił zegar tego urządzenia; sprawdź datę, godzinę i strefę czasową tego urządzenia" + util.net.secure.invalid-message: en_US: "Invalid encrypted WebSocket message" de_DE: "Ungültige verschlüsselte WebSocket-Nachricht" diff --git a/shared-libs/crates/start-core/signed-session.md b/shared-libs/crates/start-core/signed-session.md index e76c6a5f74..b190af9522 100644 --- a/shared-libs/crates/start-core/signed-session.md +++ b/shared-libs/crates/start-core/signed-session.md @@ -21,9 +21,10 @@ ingress policy. The request authority ranks an allowed candidate first; the veri proof determines the matched name. Dial-IP and proxy aliases do not change the client's selected signing identity. No query parameter selects a trusted context. -There are two binary handshake records. Each record has a two-byte big-endian length -and exactly two consecutive CBOR objects: a body followed by a structured proof. -The record has at most 1,024 bytes, with CBOR nesting bounded at 16 levels. Extra +There are two binary handshake records, or four after a retry answer. Each record has a +two-byte big-endian length and exactly two consecutive CBOR objects: a body followed by a +structured proof. A retry answer is the one exception: a single unsigned body. A record has +at most 1,024 bytes, with CBOR nesting bounded at 16 levels. Extra objects, trailing data, duplicate/unknown fields and invalid binary lengths are rejected. Maps use text keys; admission values are untagged. Binary fields are definite CBOR byte strings, not Base64 or integer arrays. CBOR integers preserve the full @@ -41,6 +42,9 @@ Each body has `protocol: "Start-RPC-Session"`, `version: 1` and a `hello` map: SHA-256 of the exact captured client record contents, excluding the length prefix. Provisional setup and diagnostic recovery without an account identity include signed `temporary: true`; committed account identities omit it. Missing `temporary` means false for existing-server compatibility. +3. Server → client, unsigned and in place of the server hello: `role: "retry"` and + `timestamp`, the server's clock in Unix seconds as a CBOR integer. See the freshness + rules below. Temporary identities must not enter fingerprint history. Normal browser encrypted RPC and continuations reject them before sending application payloads; only explicit setup/init/diagnostic @@ -79,10 +83,19 @@ authorization. Enrollment and revocation affect subsequent calls on the same ope connection. No callback receives unauthenticated plaintext as an admitted request. Each physical connection gets fresh DH keys, commitment and nonce. Client signing -finishes before the 30-second network/admission deadline; provider handles may be -reused, prepared hellos may not. The existing signed-timestamp freshness policy still -applies while signing and connecting. There is no relaxed clock policy or hidden -signing retry. The server signs only after validating the initiation. +finishes before the 30-second network/admission deadline, except for the hello answering +a retry, which signs within it; provider handles may be reused, prepared hellos may not. The existing signed-timestamp freshness policy still +applies while signing and connecting, and the server never relaxes it. Clients sign with +the local clock. A synchronized server that finds a hello valid except for its timestamp +(`ClockSkew` from `accept_nonce`) answers with an unsigned retry record and accepts one more +hello on the same socket within the handshake deadline; every other rejection, and a second +timestamp rejection, drops the connection without a reply. A client that receives a retry +answer signs one fresh hello, with a new ephemeral key and nonce, stamped with the server's +`timestamp`, and reports a wrong device clock when that hello is rejected. The retry stays on +the upgraded socket, so a GUID continuation survives it. An unsynchronized server never sends +one. A forged retry time can only make the client sign a hello bound to its own ephemeral +key; a rejected timestamp never reaches the nonce cache. HTTP request proofs sign with the +local clock. The server signs only after validating the initiation. The first message exposes the client's public identity on `ws://`; `wss://` protects it. Private signing keys never travel. Identity proof is separate from enrollment, diff --git a/shared-libs/crates/start-core/src/middleware/auth/signature.rs b/shared-libs/crates/start-core/src/middleware/auth/signature.rs index dec31736ae..933b0a01f9 100644 --- a/shared-libs/crates/start-core/src/middleware/auth/signature.rs +++ b/shared-libs/crates/start-core/src/middleware/auth/signature.rs @@ -2,7 +2,6 @@ use std::collections::{BTreeSet, HashSet}; use std::future::Future; use std::net::IpAddr; use std::sync::Arc; -use std::time::{SystemTime, UNIX_EPOCH}; use axum::body::Body; use axum::extract::Request; @@ -588,20 +587,37 @@ impl RequestReplayCheck { #[path = "signature/replay_tests.rs"] mod replay_tests; +/// The source of an `accept_nonce` rejection for a timestamp outside the synchronized window. +/// The rejected nonce stays unrecorded. +#[derive(Debug)] +pub struct ClockSkew { + /// This server's clock in Unix seconds when it rejected the timestamp. + pub now: i64, +} + +impl std::fmt::Display for ClockSkew { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&t!("middleware.auth.timestamp-not-within-30s")) + } +} + +impl std::error::Error for ClockSkew {} + +impl ClockSkew { + /// The skew behind an admission rejection, distinct from replay or a bad proof. + pub fn of(error: &Error) -> Option<&Self> { + error.source.downcast_ref() + } +} + async fn accept_nonce( context: &C, commitment: &RequestCommitment, ) -> Result<(), Error> { let now = if context.clock_synced().await { - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_secs() as i64) - .unwrap_or_else(|e| e.duration().as_secs() as i64 * -1); + let now = crate::sign::commitment::request::unix_timestamp(); if now.abs_diff(commitment.timestamp) > SIG_TIME_GRACE_PERIOD_SECS / 2 { - return Err(Error::new( - eyre!("{}", t!("middleware.auth.timestamp-not-within-30s")), - ErrorKind::InvalidSignature, - )); + return Err(Error::new(ClockSkew { now }, ErrorKind::InvalidSignature)); } Some(now) } else { diff --git a/shared-libs/crates/start-core/src/middleware/auth/signature/replay_tests.rs b/shared-libs/crates/start-core/src/middleware/auth/signature/replay_tests.rs index fe1b3eb585..91a2a4e742 100644 --- a/shared-libs/crates/start-core/src/middleware/auth/signature/replay_tests.rs +++ b/shared-libs/crates/start-core/src/middleware/auth/signature/replay_tests.rs @@ -63,14 +63,15 @@ async fn an_unpolled_check_does_not_retain_or_revive_the_authentication_owner() } #[tokio::test] -async fn validator_uses_the_existing_clock_policy_without_consuming_rejected_nonces() { +async fn validator_reports_clock_skew_without_consuming_rejected_nonces() { let (_directory, context) = context().await; let check = context.replay_check(); let mut commitment = RequestCommitment::for_bytes(b"hello"); let now = commitment.timestamp; commitment.timestamp = 0; let expired = verified(commitment.clone()).await; - assert!(check.check(expired).await.is_err()); + let error = check.check(expired).await.unwrap_err(); + assert!(ClockSkew::of(&error).unwrap().now.abs_diff(now) <= 2); commitment.timestamp = now; check.check(verified(commitment).await).await.unwrap(); } diff --git a/shared-libs/crates/start-core/src/sign/commitment/request.rs b/shared-libs/crates/start-core/src/sign/commitment/request.rs index 3f4e59ec11..564a001ed7 100644 --- a/shared-libs/crates/start-core/src/sign/commitment/request.rs +++ b/shared-libs/crates/start-core/src/sign/commitment/request.rs @@ -32,14 +32,24 @@ pub struct RequestCommitment { rpc_toolkit::reflect_ts!(RequestCommitment); rpc_toolkit::ts_export!(RequestCommitment, namespaces = [""]); +/// Seconds since the Unix epoch on this host's clock, negative before it. +pub fn unix_timestamp() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or_else(|e| e.duration().as_secs() as i64 * -1) +} + impl RequestCommitment { /// Commits the complete byte slice with a fresh timestamp and nonce. pub fn for_bytes(body: &[u8]) -> Self { + Self::for_bytes_at(body, unix_timestamp()) + } + + /// Commits the complete byte slice with a fresh nonce, stamped with the given Unix seconds. + pub fn for_bytes_at(body: &[u8], timestamp: i64) -> Self { Self { - timestamp: SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_secs() as i64) - .unwrap_or_else(|e| e.duration().as_secs() as i64 * -1), + timestamp, nonce: rand::random(), size: body.len() as u64, blake3: Base64(*blake3::hash(body).as_bytes()), @@ -119,7 +129,17 @@ impl RequestProof { body: &[u8], context: &str, ) -> Result { - let commitment = RequestCommitment::for_bytes(body); + Self::sign_commitment_at(signer, body, context, unix_timestamp()).await + } + + /// Signs as [`Self::sign_commitment`], stamped with the given Unix seconds. + pub async fn sign_commitment_at( + signer: &Signer, + body: &[u8], + context: &str, + timestamp: i64, + ) -> Result { + let commitment = RequestCommitment::for_bytes_at(body, timestamp); let signature = signer .sign_message(&crate::sign::signing_message( crate::sign::COMMITMENT_SIG_TAG, diff --git a/shared-libs/crates/start-core/src/sign/session.rs b/shared-libs/crates/start-core/src/sign/session.rs index 3e5b5f3236..73e0697fcb 100644 --- a/shared-libs/crates/start-core/src/sign/session.rs +++ b/shared-libs/crates/start-core/src/sign/session.rs @@ -10,11 +10,11 @@ use x25519_dalek::{PublicKey, StaticSecret}; use zeroize::Zeroizing; use super::commitment::request::binary::BinaryRequestProof; -use super::commitment::request::{RequestCommitment, RequestProof}; +use super::commitment::request::{RequestCommitment, RequestProof, unix_timestamp}; use super::{AnyVerifyingKey, Signer}; use crate::prelude::*; use crate::rpc_continuations::Guid; -use crate::util::serde::binary::ByteString; +use crate::util::serde::binary::{ByteString, Integer}; mod cbor; @@ -65,6 +65,11 @@ enum Hello { #[serde(default, skip_serializing_if = "std::ops::Not::not")] temporary: bool, }, + /// Unsigned server answer to a client hello rejected only for its timestamp. + Retry { + /// The server's clock in Unix seconds. + timestamp: Integer, + }, } rpc_toolkit::reflect_ts!(Hello); @@ -80,7 +85,7 @@ fn ephemeral() -> StaticSecret { StaticSecret::from(rand::random::<[u8; 32]>()) } -async fn encode(signer: &Signer, context: &str, hello: Hello) -> Result, Error> { +fn encode_body(hello: Hello) -> Result, Error> { let mut wire = Vec::new(); serde_cbor::ser::into_writer( &Message { @@ -91,7 +96,17 @@ async fn encode(signer: &Signer, context: &str, hello: Hello) -> Result, &mut wire, ) .with_kind(ErrorKind::Serialization)?; - let proof = RequestProof::sign_commitment(signer, &wire, context).await?; + Ok(wire) +} + +async fn encode( + signer: &Signer, + context: &str, + hello: Hello, + timestamp: i64, +) -> Result, Error> { + let mut wire = encode_body(hello)?; + let proof = RequestProof::sign_commitment_at(signer, &wire, context, timestamp).await?; serde_cbor::ser::into_writer(&BinaryRequestProof::from(&proof), &mut wire) .with_kind(ErrorKind::Serialization)?; if wire.len() > MAX_HANDSHAKE_BYTES { @@ -163,8 +178,36 @@ pub struct PeerIdentity { pub temporary: bool, } +/// The server's clock from an unsigned retry answer, else `None`. +pub fn retry_timestamp(response: &[u8]) -> Option { + if response.len() > MAX_HANDSHAKE_BYTES { + return None; + } + let mut reader = std::io::Cursor::new(response); + let message: Message = cbor::read(&mut reader).ok()?; + match message { + Message { + protocol, + version: VERSION, + hello: Hello::Retry { timestamp }, + } if protocol == PROTOCOL && reader.position() as usize == response.len() => { + Some(timestamp.0) + } + _ => None, + } +} + +/// The unsigned answer inviting one hello signed at the server's clock. +pub(crate) fn retry(timestamp: i64) -> Result, Error> { + encode_body(Hello::Retry { + timestamp: Integer(timestamp), + }) +} + /// A single connection's signed initiation, prepared before network deadlines. pub struct PreparedClient { + signer: Signer, + target: Target, secret: StaticSecret, context: InternedString, message: Vec, @@ -173,23 +216,40 @@ pub struct PreparedClient { impl PreparedClient { /// Uses a fresh DH key and request commitment for every connection. pub async fn new(signer: &Signer, context: &str, target: Target) -> Result { + Self::at(signer, context, target, unix_timestamp()).await + } + + async fn at( + signer: &Signer, + context: &str, + target: Target, + timestamp: i64, + ) -> Result { let secret = ephemeral(); let message = encode( signer, context, Hello::Client { ephemeral: ByteString(PublicKey::from(&secret).to_bytes()), - target, + target: target.clone(), }, + timestamp, ) .await?; Ok(Self { + signer: signer.clone(), + target, secret, context: context.into(), message, }) } + /// A fresh initiation for the same signer and target, stamped with the server's clock. + pub async fn retry(&self, timestamp: i64) -> Result { + Self::at(&self.signer, &self.context, self.target.clone(), timestamp).await + } + /// The signed client envelope, without the transport's length prefix. pub fn message(&self) -> &[u8] { &self.message @@ -274,6 +334,7 @@ where client_hello: ByteString(Sha256::digest(request).into()), temporary: identity.temporary, }, + unix_timestamp(), ) .await?; let cipher = SessionCipher::derive( diff --git a/shared-libs/crates/start-core/src/sign/session/tests.rs b/shared-libs/crates/start-core/src/sign/session/tests.rs index 88747dd5d1..9acd5c1074 100644 --- a/shared-libs/crates/start-core/src/sign/session/tests.rs +++ b/shared-libs/crates/start-core/src/sign/session/tests.rs @@ -600,6 +600,8 @@ struct WebCryptoRecord { fn fixture_client(fixture: &WebCryptoFixture) -> PreparedClient { PreparedClient { + signer: signer(1), + target: Target::Rpc, secret: StaticSecret::from( <[u8; 32]>::try_from(hex::decode(&fixture.client_private).unwrap()).unwrap(), ), @@ -740,3 +742,44 @@ async fn malformed_and_oversized_envelopes_do_not_reach_replay_policy() { } assert_eq!(wire_profile()["version"], VERSION); } + +#[tokio::test] +async fn a_retry_answer_carries_the_server_clock_and_nothing_else() { + let timestamp = i64::MAX - 7; + let answer = retry(timestamp).unwrap(); + assert_eq!(retry_timestamp(&answer), Some(timestamp)); + assert_eq!(retry_timestamp(&[answer.as_slice(), &[0]].concat()), None); + let prepared = client(&signer(1)).await; + assert_eq!(retry_timestamp(prepared.message()), None); + let (_, response, _) = accept_rpc(&signer(2), prepared.message()).await; + assert_eq!(retry_timestamp(&response), None); + assert!(client(&signer(1)).await.finish(&answer).await.is_err()); +} + +#[tokio::test] +async fn a_retried_initiation_is_fresh_and_signed_at_the_given_time() { + let prepared = client(&signer(1)).await; + let timestamp = unix_timestamp() + 3600; + let retried = prepared.retry(timestamp).await.unwrap(); + let (_, proof) = split_proof(retried.message()); + assert_eq!(proof.commitment.timestamp, timestamp); + let (first, _) = split_proof(prepared.message()); + let (second, _) = split_proof(retried.message()); + assert_ne!(first, second); + let (peer, response, _) = accept_rpc(&signer(2), retried.message()).await; + assert_eq!(peer, signer(1).verifying_key().await.unwrap()); + retried.finish(&response).await.unwrap(); +} + +#[test] +fn a_retry_answer_matches_the_browser_golden() { + assert_eq!( + retry(1_900_000_000).unwrap(), + hex::decode(concat!( + "a36870726f746f636f6c7153746172742d5250432d53657373696f6e", + "6776657273696f6e016568656c6c6fa264726f6c6565726574727969", + "74696d657374616d701a713fb300", + )) + .unwrap() + ); +} diff --git a/shared-libs/crates/start-core/src/util/net/secure.rs b/shared-libs/crates/start-core/src/util/net/secure.rs index 8923579da1..0dac6718f3 100644 --- a/shared-libs/crates/start-core/src/util/net/secure.rs +++ b/shared-libs/crates/start-core/src/util/net/secure.rs @@ -12,6 +12,7 @@ use tokio_util::codec::length_delimited::Builder; use tokio_util::codec::{Decoder, Encoder, LengthDelimitedCodec}; use super::{MAX_CLOSE_PAYLOAD_BYTES, MAX_CLOSE_REASON_BYTES}; +use crate::middleware::auth::signature::ClockSkew; use crate::prelude::*; use crate::sign::AnyVerifyingKey; use crate::sign::commitment::request::RequestCommitment; @@ -120,6 +121,13 @@ fn retaining_decoder(header: usize, maximum: usize) -> LengthDelimitedCodec { .new_codec() } +fn clock_rejected() -> Error { + Error::new( + eyre!("{}", t!("util.net.secure.clock-rejected")), + ErrorKind::InvalidSignature, + ) +} + fn invalid_message() -> Error { Error::new( eyre!("{}", t!("util.net.secure.invalid-message")), @@ -348,7 +356,8 @@ impl EncryptedSocket { } /// Completes the initiator exchange before returning the verified remote identity. - /// Preparing the identity separately keeps interactive signing outside the handshake deadline. + /// Preparing the identity separately keeps interactive signing outside the handshake deadline, + /// except for the one re-signing a server's retry answer asks for. pub async fn initiate( mut socket: BoxWebSocket, prepared: PreparedClient, @@ -357,7 +366,19 @@ impl EncryptedSocket { tokio::time::timeout(HANDSHAKE_TIMEOUT, async move { let mut records = HandshakeRecords::new(); send_handshake(&mut socket, prepared.message()).await?; - let response = records.receive(&mut socket).await?; + let mut response = records.receive(&mut socket).await?; + let prepared = match crate::sign::session::retry_timestamp(&response) { + Some(timestamp) => { + let retried = prepared.retry(timestamp).await?; + send_handshake(&mut socket, retried.message()).await?; + response = records + .receive(&mut socket) + .await + .map_err(|_| clock_rejected())?; + retried + } + None => prepared, + }; let (peer, state) = prepared.finish(&response).await?; Ok((peer, Self::new(socket, state, records, incoming))) }) @@ -366,6 +387,7 @@ impl EncryptedSocket { } /// Completes the responder exchange, optionally restricting the admitted peer identity. + /// A hello rejected only as [`ClockSkew`] gets an unsigned retry answer and one more hello. pub async fn accept( mut socket: BoxWebSocket, identity: &ServerIdentity, @@ -376,21 +398,36 @@ impl EncryptedSocket { accept_nonce: F, ) -> Result<(AnyVerifyingKey, InternedString, Self), Error> where - F: FnOnce(RequestCommitment) -> Fut, + F: Fn(RequestCommitment) -> Fut, Fut: Future>, { tokio::time::timeout(HANDSHAKE_TIMEOUT, async move { let mut records = HandshakeRecords::new(); - let request = records.receive(&mut socket).await?; - let (peer, context, response, state) = crate::sign::session::accept( - identity, - contexts, - &request, - target, - expected, - accept_nonce, - ) - .await?; + let mut retried = false; + let (peer, context, response, state) = loop { + let request = records.receive(&mut socket).await?; + let error = match crate::sign::session::accept( + identity, + contexts, + &request, + target, + expected, + &accept_nonce, + ) + .await + { + Ok(accepted) => break accepted, + Err(error) => error, + }; + match ClockSkew::of(&error) { + Some(skew) if !retried => { + retried = true; + send_handshake(&mut socket, &crate::sign::session::retry(skew.now)?) + .await?; + } + _ => return Err(error), + } + }; send_handshake(&mut socket, &response).await?; Ok((peer, context, Self::new(socket, state, records, incoming))) }) diff --git a/shared-libs/crates/start-core/src/util/net/secure/tests.rs b/shared-libs/crates/start-core/src/util/net/secure/tests.rs index 10f99a08ea..f3112d065a 100644 --- a/shared-libs/crates/start-core/src/util/net/secure/tests.rs +++ b/shared-libs/crates/start-core/src/util/net/secure/tests.rs @@ -820,3 +820,129 @@ async fn expected_peer_restriction_rejects_different_authenticated_identity() { ); assert_eq!(context.calls.load(Ordering::SeqCst), 0); } + +type NonceCheck = Arc Result<(), Error> + Send + Sync>; + +async fn admission_server( + check: NonceCheck, +) -> ( + String, + tokio::sync::oneshot::Receiver>, + ServerGuard, +) { + let (done, completion) = tokio::sync::oneshot::channel(); + let done = Arc::new(std::sync::Mutex::new(Some(done))); + let route = get(move |upgrade: axum::extract::ws::WebSocketUpgrade| { + let done = done.clone(); + let check = check.clone(); + async move { + upgrade.on_upgrade(move |socket| async move { + let result = EncryptedSocket::accept( + Box::new(socket), + &signer(42).into(), + &[CONTEXT.into()], + NonZeroUsize::new(1024).unwrap(), + &Target::Rpc, + None, + |commitment| futures::future::ready(check(&commitment)), + ) + .await + .map(|_| ()); + done.lock().unwrap().take().unwrap().send(result).unwrap(); + }) + } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}/admit", listener.local_addr().unwrap()); + let guard = ServerGuard(tokio::spawn(async move { + axum::serve(listener, Router::new().route("/admit", route)) + .await + .unwrap(); + })); + (url, completion, guard) +} + +fn server_clock(skew: i64, seen: Arc>>) -> NonceCheck { + Arc::new(move |commitment| { + seen.lock().unwrap().push(commitment.timestamp); + let now = crate::sign::commitment::request::unix_timestamp() + skew; + if now.abs_diff(commitment.timestamp) > 30 { + return Err(Error::new(ClockSkew { now }, ErrorKind::InvalidSignature)); + } + Ok(()) + }) +} + +async fn initiate(url: &str) -> Result<(PeerIdentity, EncryptedSocket), Error> { + tokio::time::timeout( + Duration::from_secs(3), + EncryptedSocket::initiate( + raw_socket(url).await, + PreparedClient::new(&signer(41), CONTEXT, Target::Rpc) + .await + .unwrap(), + NonZeroUsize::new(1024).unwrap(), + ), + ) + .await + .unwrap() +} + +#[tokio::test] +async fn a_hello_rejected_for_its_timestamp_is_signed_again_with_the_server_clock() { + let seen = Arc::new(std::sync::Mutex::new(Vec::new())); + let (url, completion, _server) = admission_server(server_clock(120, seen.clone())).await; + let (peer, _socket) = initiate(&url).await.unwrap(); + assert_eq!(peer.key, signer(42).verifying_key().await.unwrap()); + completion.await.unwrap().unwrap(); + let seen = seen.lock().unwrap(); + let now = crate::sign::commitment::request::unix_timestamp(); + assert_eq!(seen.len(), 2); + assert!(seen[0].abs_diff(now) <= 2); + assert!(seen[1].abs_diff(now + 120) <= 2); +} + +#[tokio::test] +async fn a_second_timestamp_rejection_reports_the_device_clock_without_another_retry() { + let seen = Arc::new(std::sync::Mutex::new(Vec::new())); + let (url, completion, _server) = admission_server(Arc::new({ + let seen = seen.clone(); + move |commitment: &RequestCommitment| { + seen.lock().unwrap().push(commitment.timestamp); + Err(Error::new( + ClockSkew { + now: commitment.timestamp + 120, + }, + ErrorKind::InvalidSignature, + )) + } + })) + .await; + let error = initiate(&url).await.err().unwrap(); + assert_eq!( + error.source.to_string(), + t!("util.net.secure.clock-rejected") + ); + assert!(ClockSkew::of(&completion.await.unwrap().err().unwrap()).is_some()); + assert_eq!(seen.lock().unwrap().len(), 2); +} + +#[tokio::test] +async fn other_admission_rejections_get_no_retry_answer() { + let calls = Arc::new(AtomicUsize::new(0)); + let (url, completion, _server) = admission_server(Arc::new({ + let calls = calls.clone(); + move |_: &RequestCommitment| { + calls.fetch_add(1, Ordering::SeqCst); + Err(Error::new(eyre!("replayed"), ErrorKind::InvalidSignature)) + } + })) + .await; + let error = initiate(&url).await.err().unwrap(); + assert_ne!( + error.source.to_string(), + t!("util.net.secure.clock-rejected") + ); + assert!(ClockSkew::of(&completion.await.unwrap().err().unwrap()).is_none()); + assert_eq!(calls.load(Ordering::SeqCst), 1); +} diff --git a/shared-libs/ts-modules/ARCHITECTURE.md b/shared-libs/ts-modules/ARCHITECTURE.md index 3a2dcaf52c..f8656a79fc 100644 --- a/shared-libs/ts-modules/ARCHITECTURE.md +++ b/shared-libs/ts-modules/ARCHITECTURE.md @@ -36,7 +36,7 @@ to its transport and must cancel only that operation, without replaying it or re - **`HttpService`** (`shared/src/services/http.service.ts`) — HTTP transport. `rpcRequest()` prepares an unsigned request; `rpcMessage()` sends an already serialized message unchanged. Both use the shared JSON headers and response-compatibility adapter. - **`AuthKeyService`** (`shared/src/services/auth-key.service.ts`) — Owns the browser's enrolled, nonextractable device key and its cancellation lifetime. `admissionLease` reuses possession of that key or an opaque, unpersisted Ed25519 signer when none is stored, without enrollment or a WebCrypto dependency for startup. Acquisition and enrollment started under a replaced, rolled-back or logged-out lifetime cannot adopt the next identity; fresh requests receive a fresh lifetime. StartOS and Tunnel use leases for encrypted RPC. StartWRT composes the same encrypted transport through its own RPC/reconnect owners; anonymous bootstrap uses unpersisted encrypted possession and omits normal-product peer-history observation. Resource requests keep header signing. -- **`RpcSocketService`** (`shared/src/services/rpc-socket.service.ts`) — StartOS/Tunnel/WRT's authenticated RPC and continuation transport. Its per-session abort primitive lets an existing recovery owner discard a wedged multiplexed socket without invalidating the enrolled key; DOM-style continuation sockets retain caller event ownership. Active RPC calls share an RxJS WebSocket subject; its last unsubscribe closes the socket. A two-message signed-DH exchange authenticates the selected hostname and logical RPC/GUID target before application traffic; each connection prepares a fresh hello before network deadlines, without per-message proofs or plaintext fallback. StartOS startup/bootstrap uses possession admission without requiring a stored key. WRT anonymous RPC uses the same encrypted owner without enrollment; its legacy HTTP endpoints remain for compatibility. Request serialization precedes asynchronous identity lookup; JSON response metadata remains authoritative. The bounded `ReadableStream` adapter retains physical framing/backpressure/closure ownership; Maintained Noble libraries supply X25519, HKDF-SHA256 and AES-256-GCM in one implementation shared by HTTP and HTTPS; browser randomness uses `getRandomValues`. Persisted enrollment keys remain nonextractable WebCrypto keys. The existing UUID library keeps request correlation available without secure-context `randomUUID`. The SDK auth module owns opaque signing providers and generic proof/key verification. Its asynchronous CBOR admission decoder validates wire kinds through the existing library's public decoder events before schema interpretation; it retains exact captured byte boundaries, rejects normalized tag/array/indefinite-byte alternatives, and destroys its bounded decoder after the first object or failure. Rust generates the hello schemas and transport/signature profiles. `rpc-stream.ts` owns each typed response stream's serialized UTF-8 byte-bounded queue and reserved terminal result; `RpcSocketService.stream` composes it with the existing correlation source. AbortSignals cancel pending initialization and iteration, including queued items after a terminal; iterator disposal also cancels before its first `next`. Application terminals drain accepted items, while transport loss discards them. Database subscriptions use the generated `RpcStreamClient`, deliver their initial dump without awaiting its own cache fence, and retain the source's existing batching/recovery lifetime. +- **`RpcSocketService`** (`shared/src/services/rpc-socket.service.ts`) — StartOS/Tunnel/WRT's authenticated RPC and continuation transport. Its per-session abort primitive lets an existing recovery owner discard a wedged multiplexed socket without invalidating the enrolled key; DOM-style continuation sockets retain caller event ownership. Active RPC calls share an RxJS WebSocket subject; its last unsubscribe closes the socket. A two-message signed-DH exchange authenticates the selected hostname and logical RPC/GUID target before application traffic; each connection prepares a fresh hello before network deadlines, without per-message proofs or plaintext fallback, and signs one more at the server's clock when the server answers with a [retry](../crates/start-core/signed-session.md#admission). StartOS startup/bootstrap uses possession admission without requiring a stored key. WRT anonymous RPC uses the same encrypted owner without enrollment; its legacy HTTP endpoints remain for compatibility. Request serialization precedes asynchronous identity lookup; JSON response metadata remains authoritative. The bounded `ReadableStream` adapter retains physical framing/backpressure/closure ownership; Maintained Noble libraries supply X25519, HKDF-SHA256 and AES-256-GCM in one implementation shared by HTTP and HTTPS; browser randomness uses `getRandomValues`. Persisted enrollment keys remain nonextractable WebCrypto keys. The existing UUID library keeps request correlation available without secure-context `randomUUID`. The SDK auth module owns opaque signing providers and generic proof/key verification. Its asynchronous CBOR admission decoder validates wire kinds through the existing library's public decoder events before schema interpretation; it retains exact captured byte boundaries, rejects normalized tag/array/indefinite-byte alternatives, and destroys its bounded decoder after the first object or failure. Rust generates the hello schemas and transport/signature profiles. `rpc-stream.ts` owns each typed response stream's serialized UTF-8 byte-bounded queue and reserved terminal result; `RpcSocketService.stream` composes it with the existing correlation source. AbortSignals cancel pending initialization and iteration, including queued items after a terminal; iterator disposal also cancels before its first `next`. Application terminals drain accepted items, while transport loss discards them. Database subscriptions use the generated `RpcStreamClient`, deliver their initial dump without awaiting its own cache fence, and retain the source's existing batching/recovery lifetime. - **`local-rpc.ts`** — `localRpcRequest` owns OS/Tunnel local capture, nullable-key encrypted-or-public-HTTP dispatch, error metadata and PatchDB fences. `authenticatedRpcTransport` owns device-key typed-stream admission and the combined device/operation signal; it rejects missing keys without HTTP fallback. Server authorization remains live. StartOS's normal generated stream facade waits for initial fences, shares its code-34 logout owner and preserves the socket iterator's early disposal. `watchDb$` composes the raw transport separately: its initial dump establishes the fence. Fence cancellation releases cache subscriptions and prevents late adoption after logout/disposal. Explicit foreign echo remains unsigned HTTP and unfenced; its rejection never invalidates local authentication. - **`ServerIdentityService`** (`shared/src/services/server-identity.service.ts`) — Normal product API callers attach its open observer to RPC/stream/GUID operations. The transport caches one verified open event; reuse observes it only while its physical socket remains open. Observation precedes application replies, including authorization rejection, without introducing another connection owner. Same-origin API targets remember one fingerprint per app/API namespace, atomically in the existing identity IndexedDB store through `identity-store.ts`. This record is separate from the device-key record and survives logout. First contact is silent; rotation remembers the new key and lazily opens a nonblocking Taiga notice/details view. Storage failure never changes the RPC result. RPC, DOM and RxJS continuation open observers retain their owners. The signed handshake marks provisional setup and temporary recovery identities. Normal operations reject them before sending payloads, including when reusing a startup probe's socket; explicit setup/init/diagnostic operations opt in. Continuations enforce the same admission policy. Temporary identities, foreign API overrides and OS registry listings do not populate this history. The backend [identity lifecycle](../crates/start-core/encrypted-rpc.md#identity-and-trust) owns persistence and recovery policy. - **`StartupApiService`** (`ui/src/app/services/api/startup-api.service.ts`) — Explicit encrypted-possession boundary for StartOS initialization, diagnostics and the existing state/DNS probe. Setup-wizard calls and GUIDs use the same admission lease and socket owner. These callers neither enroll keys nor attach normal-product identity-history observers. Normal callers retain `ApiService` and its enrolled-key policy. An unauthenticated mode response never selects plaintext for a normal call. Diagnostic update observation uses the generated typed stream; the component-scoped `DiagnosticUpdate` service reports success after the actual terminal, not a progress counter or close code. Disposal cancels observation without canceling accepted backend work. Mock mode aliases the same concrete API fixture for both interfaces rather than duplicating its state; its initiating update and progress producers are shared with ordinary mock calls. Shared `pauseFor` accepts cancellation for mock progress waits. The setup wizard's component-scoped `SetupObservation` consumes typed `setup.status` through the same lease/socket owner; only successful termination permits navigation to its separate finalization step. Transport loss retries the read-only observation, never the accepted setup operation. Shared `isNetworkError` owns numeric code-zero classification for formatting and reconnect callers; StartWRT retains its existing exported binding and reconnect policy. Both transports share `rpcWebSocketUrl` and the native-generated endpoint. diff --git a/shared-libs/ts-modules/shared/scripts/rpc-socket.test.mjs b/shared-libs/ts-modules/shared/scripts/rpc-socket.test.mjs index a514464377..b2ee6f575d 100644 --- a/shared-libs/ts-modules/shared/scripts/rpc-socket.test.mjs +++ b/shared-libs/ts-modules/shared/scripts/rpc-socket.test.mjs @@ -17,6 +17,8 @@ const { RPC_CONSOLE_LOG_GLOBAL, RpcConsoleLog } = await import('../src/services/rpc-console-log.ts') const { ServerIdentityService } = await import('../src/services/server-identity.service.ts') +const { DeviceClockError } = + await import('../src/services/session-websocket.ts') for (const name of ['CloseEvent', 'ErrorEvent']) globalThis[name] ??= class extends Event { @@ -159,8 +161,8 @@ class LogicalSocket { this.readyState = 3 this.onclose?.({ wasClean: true }) } - fail() { - this.onerror?.(new ErrorEvent('error', { error: Error('transport') })) + fail(error = Error('transport')) { + this.onerror?.(new ErrorEvent('error', { error })) } } @@ -582,6 +584,18 @@ test('transport loss cancels two established streams, pending initialization and assert.equal((await fresh).name, 'AbortError') }) +test('a rejected device clock names the clock instead of the transport', async context => { + const { service, lease } = await streamFixture(context) + const call = service.message(body, {}, lease).catch(error => error) + const other = service.message(body, {}, lease).catch(error => error) + await tick() + LogicalSocket.instances[0].fail(new DeviceClockError()) + const clock = await call + network(clock) + assert.equal(clock.message, new DeviceClockError().message) + network(await other) +}) + test('an unread burst survives while its sibling completes', async context => { const { service, lease } = await streamFixture(context) const pending = service.stream(body, lease) diff --git a/shared-libs/ts-modules/shared/scripts/session-identity.test.mjs b/shared-libs/ts-modules/shared/scripts/session-identity.test.mjs index fd41a0a692..fddba06802 100644 --- a/shared-libs/ts-modules/shared/scripts/session-identity.test.mjs +++ b/shared-libs/ts-modules/shared/scripts/session-identity.test.mjs @@ -6,7 +6,8 @@ import { x25519 } from '@noble/curves/ed25519' import { decodeFirst, encode } from '@start9labs/start-core/auth/cbor' import './typescript-loader.mjs' -const { prepareSession } = await import('../src/services/session-identity.ts') +const { prepareSession, retryTime } = + await import('../src/services/session-identity.ts') const fixture = JSON.parse( readFileSync( new URL( @@ -87,6 +88,58 @@ test('opaque fresh initiation signs once per connection and binds exact GUID int assert.equal(b.hello.target, 'rpc') }) +test('a hello proof carries the requested signing time', async () => { + const key = await auth.generateAuthKey() + const time = Date.UTC(2030, 0, 1, 0, 0, 30, 999) + const prepared = await prepareSession( + auth.requestSigner(key), + fixture.context, + 'rpc', + time, + ) + const body = await decodeFirst(prepared.message) + const proof = prepared.message.subarray(body.length) + assert.equal( + BigInt((await decodeFirst(proof)).value.commitment.timestamp), + BigInt(Math.floor(time / 1000)), + ) + assert.equal( + await auth.verifyRequestProof( + proof, + fixture.context, + prepared.message.subarray(0, body.length), + ), + auth.normalizeDer64(key.pubkeyPem), + ) +}) + +test('a native retry answer yields the server clock and nothing else does', async () => { + const retry = Uint8Array.from( + Buffer.from( + 'a36870726f746f636f6c7153746172742d5250432d53657373696f6e' + + '6776657273696f6e016568656c6c6fa264726f6c6565726574727969' + + '74696d657374616d701a713fb300', + 'hex', + ), + ) + assert.equal(await retryTime(retry), 1_900_000_000_000) + assert.equal( + await retryTime(concatenate(retry, new Uint8Array([0]))), + undefined, + ) + assert.equal(await retryTime(server), undefined) + assert.equal(await retryTime(client), undefined) + const body = { ...(await decodeFirst(retry)).value } + assert.equal( + await retryTime(encode({ ...body, hello: { ...body.hello, extra: 1 } })), + undefined, + ) + assert.equal( + await retryTime(encode({ ...body, protocol: 'Other' })), + undefined, + ) +}) + test('independent WebCrypto golden matches both directional records and full captured hellos', async context => { const prepared = await frozenClient(context) assert.deepEqual(prepared.message, client) diff --git a/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs b/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs index 7141535c83..7d06946bc2 100644 --- a/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs +++ b/shared-libs/ts-modules/shared/scripts/session-transport.test.mjs @@ -13,7 +13,11 @@ registerHooks({ format: 'module', shortCircuit: true, source: ` - export async function prepareSession() { + export async function retryTime(response) { + return response[0] === 3 ? globalThis.serverTime : undefined + } + export async function prepareSession(...args) { + globalThis.preparedSessions?.push(args) return { message: new Uint8Array([1]), async finish(response) { return { temporary: response[0] === 2, peer: ${JSON.stringify(auth.ed25519PublicKeyDer64(new Uint8Array(32).fill(7)))}, cipher: { async write(bytes) { return bytes.slice() }, async read(bytes) { await globalThis.sessionRecordGate?.(); return bytes.slice() } @@ -26,7 +30,7 @@ registerHooks({ }) const { SessionWebSocketStream } = await import('../src/services/session-stream.ts') -const { sessionWebSocketConstructor } = +const { DeviceClockError, sessionWebSocketConstructor } = await import('../src/services/session-websocket.ts') const profile = SESSION_PROFILE.transport for (const name of ['CloseEvent', 'ErrorEvent']) @@ -354,3 +358,90 @@ test('raw writes wait for bufferedAmount and abort without a retained drain task await assert.rejects(write) raw.abort(Error('test complete')) }) + +function retryingServer(answers) { + return class extends Socket { + constructor(url) { + super(url) + queueMicrotask(() => this.dispatchEvent(new Event('open'))) + } + send(data) { + super.send(data) + const answer = answers[this.writes.length - 1] + if (this.writes.length > answers.length) return + queueMicrotask(() => + answer === undefined ? this.close() : this.receive(record(answer)), + ) + } + } +} +async function admitted(target, url, Server) { + globalThis.preparedSessions = [] + globalThis.serverTime = Date.UTC(2031, 0, 1) + Socket.instances = [] + try { + const Constructor = sessionWebSocketConstructor( + async () => identity(), + 'server.test', + target, + Server, + ) + const socket = new Constructor(url) + let error + socket.addEventListener('error', event => (error = event.error)) + const opened = await new Promise(resolve => { + socket.addEventListener('open', () => resolve(true), { once: true }) + socket.addEventListener('close', () => resolve(false), { once: true }) + }) + socket.close() + return { + opened, + error, + signedAt: globalThis.preparedSessions.map(args => args[3]), + sockets: Socket.instances.length, + writes: Socket.instances[0]?.writes.length, + } + } finally { + delete globalThis.preparedSessions + delete globalThis.serverTime + } +} + +for (const [name, target, url] of [ + ['RPC', 'rpc', 'wss://server.test/rpc/v2'], + [ + 'a GUID continuation', + { continuation: 'A'.repeat(32) }, + `wss://server.test/rpc/v2/${'A'.repeat(32)}`, + ], +]) + test(`a retry answer re-signs ${name} once at the server clock on the same socket`, async () => { + const result = await admitted(target, url, retryingServer([[3], [1]])) + assert.equal(result.opened, true) + assert.deepEqual(result.signedAt, [undefined, Date.UTC(2031, 0, 1)]) + assert.equal(result.sockets, 1) + assert.equal(result.writes, 2) + }) + +test('a rejected retried hello reports the device clock without a third hello', async () => { + const result = await admitted( + 'rpc', + 'wss://server.test/rpc/v2', + retryingServer([[3], undefined]), + ) + assert.equal(result.opened, false) + assert.ok(result.error instanceof DeviceClockError) + assert.equal(result.signedAt.length, 2) + assert.equal(result.writes, 2) +}) + +test('a dropped first hello is not re-signed', async () => { + const result = await admitted( + 'rpc', + 'wss://server.test/rpc/v2', + retryingServer([undefined]), + ) + assert.equal(result.opened, false) + assert.ok(!(result.error instanceof DeviceClockError)) + assert.equal(result.signedAt.length, 1) +}) diff --git a/shared-libs/ts-modules/shared/src/i18n/dictionaries/de.ts b/shared-libs/ts-modules/shared/src/i18n/dictionaries/de.ts index e44ea28e1b..5cec8a6f83 100644 --- a/shared-libs/ts-modules/shared/src/i18n/dictionaries/de.ts +++ b/shared-libs/ts-modules/shared/src/i18n/dictionaries/de.ts @@ -1113,4 +1113,5 @@ export default { 1319: 'Chipsatz', 1320: 'Sensor', 1321: 'Keine Temperatursensoren gefunden', + 1322: 'Der Server hat die Uhr dieses Geräts abgelehnt; prüfen Sie Datum, Uhrzeit und Zeitzone dieses Geräts', } satisfies i18n diff --git a/shared-libs/ts-modules/shared/src/i18n/dictionaries/en.ts b/shared-libs/ts-modules/shared/src/i18n/dictionaries/en.ts index 51122ef876..a2e39e56f5 100644 --- a/shared-libs/ts-modules/shared/src/i18n/dictionaries/en.ts +++ b/shared-libs/ts-modules/shared/src/i18n/dictionaries/en.ts @@ -1114,4 +1114,5 @@ export const ENGLISH: Record = { 'Chipset': 1319, 'Sensor': 1320, // as in, a temperature sensor 'No temperature sensors found': 1321, + "The server rejected this device's clock; check this device's date, time and time zone": 1322, } diff --git a/shared-libs/ts-modules/shared/src/i18n/dictionaries/es.ts b/shared-libs/ts-modules/shared/src/i18n/dictionaries/es.ts index 57b86b9c62..57efa93c09 100644 --- a/shared-libs/ts-modules/shared/src/i18n/dictionaries/es.ts +++ b/shared-libs/ts-modules/shared/src/i18n/dictionaries/es.ts @@ -1113,4 +1113,5 @@ export default { 1319: 'Chipset', 1320: 'Sensor', 1321: 'No se encontraron sensores de temperatura', + 1322: 'El servidor rechazó el reloj de este dispositivo; compruebe la fecha, la hora y la zona horaria de este dispositivo', } satisfies i18n diff --git a/shared-libs/ts-modules/shared/src/i18n/dictionaries/fr.ts b/shared-libs/ts-modules/shared/src/i18n/dictionaries/fr.ts index 9a4ce98eff..304ddf27f4 100644 --- a/shared-libs/ts-modules/shared/src/i18n/dictionaries/fr.ts +++ b/shared-libs/ts-modules/shared/src/i18n/dictionaries/fr.ts @@ -1113,4 +1113,5 @@ export default { 1319: 'Chipset', 1320: 'Capteur', 1321: 'Aucun capteur de température trouvé', + 1322: "Le serveur a rejeté l'horloge de cet appareil ; vérifiez la date, l'heure et le fuseau horaire de cet appareil", } satisfies i18n diff --git a/shared-libs/ts-modules/shared/src/i18n/dictionaries/pl.ts b/shared-libs/ts-modules/shared/src/i18n/dictionaries/pl.ts index 9c2403b7ab..7ed448ed4f 100644 --- a/shared-libs/ts-modules/shared/src/i18n/dictionaries/pl.ts +++ b/shared-libs/ts-modules/shared/src/i18n/dictionaries/pl.ts @@ -1113,4 +1113,5 @@ export default { 1319: 'Chipset', 1320: 'Czujnik', 1321: 'Nie znaleziono czujników temperatury', + 1322: 'Serwer odrzucił zegar tego urządzenia; sprawdź datę, godzinę i strefę czasową tego urządzenia', } satisfies i18n diff --git a/shared-libs/ts-modules/shared/src/services/rpc-socket.service.ts b/shared-libs/ts-modules/shared/src/services/rpc-socket.service.ts index 435b76062f..a302052319 100644 --- a/shared-libs/ts-modules/shared/src/services/rpc-socket.service.ts +++ b/shared-libs/ts-modules/shared/src/services/rpc-socket.service.ts @@ -24,6 +24,7 @@ import { AUTH_SIGNING_HOST, AuthKeyService } from './auth-key.service' import type { SessionSocketIdentity } from './session-websocket' import { withTimeout } from './http.service' import { + DeviceClockError, SessionOpenEvent, assertServerIdentity, sessionWebSocketConstructor, @@ -236,8 +237,24 @@ export class RpcSocketService { } } +function deviceClockError(cause: unknown): DeviceClockError | undefined { + let value = cause + while (value !== undefined) { + if (value instanceof DeviceClockError) return value + value = + value instanceof Event + ? (value as ErrorEvent).error + : value instanceof Error + ? value.cause + : undefined + } + return undefined +} + function transportError(cause: unknown) { - return Object.assign(new Error('Encrypted RPC transport failed', { cause }), { - code: 0, - }) + const clock = deviceClockError(cause) + return Object.assign( + new Error(clock?.message ?? 'Encrypted RPC transport failed', { cause }), + { code: 0 }, + ) } diff --git a/shared-libs/ts-modules/shared/src/services/session-identity.ts b/shared-libs/ts-modules/shared/src/services/session-identity.ts index 5d041b036f..200883e6e3 100644 --- a/shared-libs/ts-modules/shared/src/services/session-identity.ts +++ b/shared-libs/ts-modules/shared/src/services/session-identity.ts @@ -84,11 +84,33 @@ export interface SessionCipher { read(bytes: Uint8Array): Promise> } +/** The server's clock in epoch milliseconds from an unsigned retry answer, else undefined. */ +export async function retryTime( + response: Uint8Array, +): Promise { + if (response.length > maximum) return undefined + try { + const captured = await decodeFirst(response) + if (captured.length !== response.length) return undefined + const message = parseHandshake(MessageSchema, captured.value) + if ( + message.protocol !== profile.protocol || + message.version !== profile.version || + message.hello.role !== 'retry' + ) + return undefined + return Number(message.hello.timestamp) * 1000 + } catch { + return undefined + } +} + /** Single-use initiation supports LAN HTTP without crypto.subtle; signing precedes network deadlines. */ export async function prepareSession( signer: auth.RequestSigner, context: string, target: Target, + time?: number, ) { const dh = x25519.utils.randomPrivateKey() const ephemeral = new Uint8Array(x25519.getPublicKey(dh)) @@ -98,7 +120,7 @@ export async function prepareSession( hello: { role: 'client', ephemeral, target }, } const payload = encode(body) - const proof = await signer.sign(context, payload) + const proof = await signer.sign(context, payload, time) const wire = new Uint8Array(payload.length + proof.length) wire.set(payload) wire.set(proof, payload.length) diff --git a/shared-libs/ts-modules/shared/src/services/session-websocket.ts b/shared-libs/ts-modules/shared/src/services/session-websocket.ts index 03a741a71e..6625f912a8 100644 --- a/shared-libs/ts-modules/shared/src/services/session-websocket.ts +++ b/shared-libs/ts-modules/shared/src/services/session-websocket.ts @@ -10,6 +10,16 @@ const profile = SESSION_PROFILE.transport const encoder = new TextEncoder() const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) +/** A server rejected a hello signed at its own clock. */ +export class DeviceClockError extends Error { + constructor(options?: ErrorOptions) { + super( + "The server rejected this device's clock; check this device's date, time and time zone", + options, + ) + } +} + export interface SessionSocketIdentity { readonly signer: auth.RequestSigner readonly signal: AbortSignal @@ -134,8 +144,8 @@ export function sessionWebSocketConstructor( () => this.fail(identity.signal.reason), { once: true, signal: this.lifetime.signal }, ) - const { prepareSession } = await import('./session-identity') - const prepared = await prepareSession(identity.signer, context, target) + const { prepareSession, retryTime } = await import('./session-identity') + let prepared = await prepareSession(identity.signer, context, target) if (this.readyState !== this.CONNECTING) return identity.signal.throwIfAborted() const signal = AbortSignal.any([ @@ -154,10 +164,27 @@ export function sessionWebSocketConstructor( rejectionEvents: ['error', 'close'], }) await raw.writeRecord(prepared.message, signal) - const response = await raw.readRecord( + let response = await raw.readRecord( profile.maxHandshakeRecordBytes, signal, ) + const time = await retryTime(response) + if (time !== undefined) { + prepared = await prepareSession( + identity.signer, + context, + target, + time, + ) + signal.throwIfAborted() + await raw.writeRecord(prepared.message, signal) + response = await raw + .readRecord(profile.maxHandshakeRecordBytes, signal) + .catch((cause: unknown) => { + signal.throwIfAborted() + throw new DeviceClockError({ cause }) + }) + } const secured = await prepared.finish(response) signal.throwIfAborted() assertServerIdentity(secured, allowTemporaryIdentity) diff --git a/shared-libs/ts-modules/start-core/lib/auth/signature.ts b/shared-libs/ts-modules/start-core/lib/auth/signature.ts index d19eb68770..5739cf08fe 100644 --- a/shared-libs/ts-modules/start-core/lib/auth/signature.ts +++ b/shared-libs/ts-modules/start-core/lib/auth/signature.ts @@ -23,7 +23,12 @@ export interface AuthKey { /** Signs captured body bytes and returns a binary CBOR request proof without exporting private keys. */ export interface RequestSigner { - sign(context: string, body: Uint8Array): Promise> + /** Stamps the proof with the given epoch-millisecond time, else the local clock. */ + sign( + context: string, + body: Uint8Array, + time?: number, + ): Promise> } interface SigningIdentity { @@ -43,10 +48,10 @@ function webCryptoIdentity(key: AuthKey): SigningIdentity { function commitmentSigner(identity: SigningIdentity): RequestSigner { return { - sign: async (context, body) => { + sign: async (context, body, time) => { const { encode } = await import('./cbor') return encode( - await signTaggedRequest(identity, context, body, COMMITMENT_TAG), + await signTaggedRequest(identity, context, body, COMMITMENT_TAG, time), ) }, } @@ -129,8 +134,9 @@ async function signTaggedRequest( context: string, body: Uint8Array, tag: Uint8Array, + time = Date.now(), ): Promise { - const timestamp = BigInt(Math.floor(Date.now() / 1000)) + const timestamp = BigInt(Math.floor(time / 1000)) const nonce = crypto.getRandomValues(new BigUint64Array(1))[0] const size = BigInt(body.length) const hash = blake3(body) diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/session.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/session.schemas.ts index 914579c759..2e286aa766 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/session.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/session.schemas.ts @@ -101,6 +101,20 @@ export const Hello: z.ZodUnion< temporary: z.ZodOptional }> >, + z.ZodIntersection< + z.ZodObject<{ + /** + * Unsigned server answer to a client hello rejected only for its timestamp. + */ + role: z.ZodLiteral<'retry'> + }>, + z.ZodObject<{ + /** + * The server's clock in Unix seconds. + */ + timestamp: typeof literal_0 + }> + >, ] > = /* @__PURE__ */ z .union([ @@ -128,6 +142,30 @@ export const Hello: z.ZodUnion< temporary: z.boolean().optional(), }), ), + z.intersection( + object({ + /** + * Unsigned server answer to a client hello rejected only for its timestamp. + */ + role: z.literal('retry').meta({ + description: + 'Unsigned server answer to a client hello rejected only for its timestamp.', + }), + }), + object({ + /** + * The server's clock in Unix seconds. + */ + timestamp: literal_0 + .meta({ + description: + 'A CBOR integer whose JavaScript decoder may return a bigint.', + }) + .meta({ + description: "The server's clock in Unix seconds.", + }), + }), + ), ]) .meta({ id: 'Hello', diff --git a/shared-libs/ts-modules/start-core/lib/test/signature.test.ts b/shared-libs/ts-modules/start-core/lib/test/signature.test.ts index 90b4486dd9..48e58eaa44 100644 --- a/shared-libs/ts-modules/start-core/lib/test/signature.test.ts +++ b/shared-libs/ts-modules/start-core/lib/test/signature.test.ts @@ -62,6 +62,20 @@ test('request proof verification rejects a normalized typed-byte tag', async () ).rejects.toThrow() }) +test('request proofs commit the requested signing time and still verify', async () => { + const signer = await generateEphemeralRequestSigner() + const body = new TextEncoder().encode('captured body') + const time = Date.UTC(2030, 0, 1, 0, 0, 30, 999) + const proof = await signer.sign('server.test', body, time) + const parsed = (await decodeFirst(proof)).value as BinaryRequestProof + expect(BigInt(parsed.commitment.timestamp)).toBe( + BigInt(Math.floor(time / 1000)), + ) + await expect( + verifyRequestProof(proof, 'server.test', body), + ).resolves.toBeTruthy() +}) + test('DER64 normalization preserves standard Base64 and padding', () => { expect(normalizeDer64(pem)).toBe(der64) expect(normalizeDer64(pem.replace(/\n/g, '\r\n'))).toBe(der64)