Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions projects/start-tunnel/web/src/app/i18n/dictionaries/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ export const ENGLISH: Record<string, number> = {
'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
1 change: 1 addition & 0 deletions projects/start-tunnel/web/src/app/i18n/dictionaries/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ const es: Record<number, string> = {
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
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions projects/start-wrt/web/src/app/i18n/dictionaries/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions projects/start-wrt/web/src/app/i18n/dictionaries/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -610,4 +610,5 @@ export const ENGLISH: Record<string, number> = {
"{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,
}
1 change: 1 addition & 0 deletions projects/start-wrt/web/src/app/i18n/dictionaries/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 7 additions & 0 deletions shared-libs/crates/start-core/locales/i18n.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
27 changes: 20 additions & 7 deletions shared-libs/crates/start-core/signed-session.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down
34 changes: 25 additions & 9 deletions shared-libs/crates/start-core/src/middleware/auth/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<C: SignatureAuthContext>(
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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
30 changes: 25 additions & 5 deletions shared-libs/crates/start-core/src/sign/commitment/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down Expand Up @@ -119,7 +129,17 @@ impl RequestProof {
body: &[u8],
context: &str,
) -> Result<Self, Error> {
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<Self, Error> {
let commitment = RequestCommitment::for_bytes_at(body, timestamp);
let signature = signer
.sign_message(&crate::sign::signing_message(
crate::sign::COMMITMENT_SIG_TAG,
Expand Down
71 changes: 66 additions & 5 deletions shared-libs/crates/start-core/src/sign/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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<i64>,
},
}

rpc_toolkit::reflect_ts!(Hello);
Expand All @@ -80,7 +85,7 @@ fn ephemeral() -> StaticSecret {
StaticSecret::from(rand::random::<[u8; 32]>())
}

async fn encode(signer: &Signer, context: &str, hello: Hello) -> Result<Vec<u8>, Error> {
fn encode_body(hello: Hello) -> Result<Vec<u8>, Error> {
let mut wire = Vec::new();
serde_cbor::ser::into_writer(
&Message {
Expand All @@ -91,7 +96,17 @@ async fn encode(signer: &Signer, context: &str, hello: Hello) -> Result<Vec<u8>,
&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<Vec<u8>, 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 {
Expand Down Expand Up @@ -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<i64> {
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<Vec<u8>, 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<u8>,
Expand All @@ -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, Error> {
Self::at(signer, context, target, unix_timestamp()).await
}

async fn at(
signer: &Signer,
context: &str,
target: Target,
timestamp: i64,
) -> Result<Self, Error> {
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, Error> {
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
Expand Down Expand Up @@ -274,6 +334,7 @@ where
client_hello: ByteString(Sha256::digest(request).into()),
temporary: identity.temporary,
},
unix_timestamp(),
)
.await?;
let cipher = SessionCipher::derive(
Expand Down
Loading