From 989defcc8825f849728172bbaafcd43ecccde049 Mon Sep 17 00:00:00 2001 From: mnovak Date: Fri, 4 Dec 2026 12:30:30 +0100 Subject: [PATCH] [domistream] Host pairing: the host's state machine (pending-PIN slot, proof and signature checks, deadlines from the caller, trusted clients without a PIN) --- crates/domistream/src/host/pairing.rs | 210 +++++++++++++++++++++--- crates/domistream/tests/host_pairing.rs | 5 +- 2 files changed, 189 insertions(+), 26 deletions(-) diff --git a/crates/domistream/src/host/pairing.rs b/crates/domistream/src/host/pairing.rs index 1cf4633..078ce32 100644 --- a/crates/domistream/src/host/pairing.rs +++ b/crates/domistream/src/host/pairing.rs @@ -26,10 +26,15 @@ use core::fmt; use core::time::Duration; -use crate::http::Scheme; -use crate::pairing::{CHALLENGE_LEN, HASH_LEN, Pin, SALT_LEN, SECRET_LEN}; +use crate::http::{Scheme, check_unique_id}; +use crate::pairing::identity::MAX_CERT_DER_BYTES; +use crate::pairing::{CHALLENGE_LEN, ClientIdentity, HASH_LEN, Pin, SALT_LEN, SECRET_LEN, ServerCert, crypto}; +use crate::util::{array, cap, ct_eq, malformed}; use crate::{Error, Instant, RandomSource, Result}; +/// A failed step: why, and the error to return. +type StepError = (HostPairingFailure, Error); + /// Default time the owner has to type the PIN after the first phase arrives (the client waits as long, see /// [`crate::pairing::STEP1_TIMEOUT`]). pub const DEFAULT_PIN_TIMEOUT: Duration = Duration::from_secs(120); @@ -48,7 +53,7 @@ pub const HOST_SECRET_LEN: usize = SECRET_LEN; /// certificate is sent as `plaincert` while pairing and presented by the HTTPS server. `Debug` never prints the key. #[derive(Clone)] pub struct HostIdentity { - inner: crate::pairing::ClientIdentity, + inner: ClientIdentity, } impl HostIdentity { @@ -58,8 +63,7 @@ impl HostIdentity { /// # Errors /// [`Error::Malformed`] for a bad `common_name` or time, [`Error::Crypto`] if key generation fails. pub fn generate(rng: &mut dyn RandomSource, common_name: &str, not_before_unix: i64) -> Result { - let _ = (rng, common_name, not_before_unix); - Err(Error::Unimplemented) + ClientIdentity::generate(rng, common_name, not_before_unix).map(|inner| Self { inner }) } /// Loads a stored identity and checks that the key matches the certificate. @@ -67,8 +71,7 @@ impl HostIdentity { /// # Errors /// As [`crate::pairing::ClientIdentity::from_der`]. pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result { - let _ = (cert_der, key_pkcs8_der); - Err(Error::Unimplemented) + ClientIdentity::from_der(cert_der, key_pkcs8_der).map(|inner| Self { inner }) } /// The certificate, DER (what the HTTPS server presents). @@ -220,8 +223,8 @@ impl PairedClient { /// # Errors /// [`Error::TooLarge`] over [`crate::pairing::identity::MAX_CERT_DER_BYTES`], [`Error::Malformed`] otherwise. pub fn trusted(cert_der: &[u8]) -> Result { - let _ = cert_der; - Err(Error::Unimplemented) + ServerCert::from_der(cert_der)?; + Ok(Self { cert_der: cert_der.to_vec(), unique_id: None, device_name: None }) } /// TLS authorization: whether the certificate a client presents over HTTPS (DER) is exactly this one, compared @@ -230,8 +233,8 @@ impl PairedClient { /// # Errors /// [`Error::TooLarge`] over [`crate::pairing::identity::MAX_CERT_DER_BYTES`]. pub fn matches(&self, presented_der: &[u8]) -> Result { - let _ = presented_der; - Err(Error::Unimplemented) + cap("presented certificate", MAX_CERT_DER_BYTES, presented_der.len())?; + Ok(ct_eq(&self.cert_der, presented_der)) } } @@ -322,6 +325,7 @@ pub struct HostPairingSession { deadline: Instant, host_cert_der: Vec, pending: Option, + client_cert: Option, salt: [u8; SALT_LEN], key: zeroize::Zeroizing<[u8; 16]>, server_challenge: [u8; CHALLENGE_LEN], @@ -341,6 +345,7 @@ impl HostPairingSession { deadline: now.saturating_add(config.phase_timeout), host_cert_der: identity.cert_der().to_vec(), pending: None, + client_cert: None, salt: [0; SALT_LEN], key: zeroize::Zeroizing::new([0; 16]), server_challenge: [0; CHALLENGE_LEN], @@ -350,7 +355,19 @@ impl HostPairingSession { } } - /// Handles one `/pair` request. Draws randomness in phase 2 (host challenge and host secret). + const fn is_over(&self) -> bool { + matches!(self.state, HostPairingState::Paired | HostPairingState::Failed(_)) + } + + fn fail(&mut self, why: HostPairingFailure, error: Error) -> Result { + self.state = HostPairingState::Failed(why); + Err(error) + } + + /// Handles one `/pair` request. Draws randomness in phase 2 (host challenge and host secret, 16 bytes each). + /// + /// Phases 1-4 are accepted over either transport; phase 5 only over HTTPS with exactly the certificate of + /// phase 1. Every phase must carry the `uniqueid` of phase 1. /// /// # Errors /// [`Error::PairingRefused`] for a wrong phase, client, signature or PIN; [`Error::Malformed`] / @@ -365,35 +382,178 @@ impl HostPairingSession { now: Instant, rng: &mut dyn RandomSource, ) -> Result { - let _ = (identity, request, transport, now, rng); - Err(Error::Unimplemented) + if self.is_over() { + return Err(Error::State { expected: "a pairing in progress" }); + } + if identity.cert_der() != self.host_cert_der.as_slice() { + return Err(malformed("host pairing: a different identity than at the start")); + } + if now > self.deadline { + return self.fail(HostPairingFailure::TimedOut, Error::TimedOut); + } + match self.step(identity, request, transport, now, rng) { + Ok(step) => Ok(step), + Err((why, e)) => self.fail(why, e), + } } - /// The owner typed the PIN: derives the key and returns the held answer to phase 1. + /// Every phase after the first must come from the client of phase 1. + fn same_client(&self, request: &PairRequest) -> core::result::Result<(), StepError> { + match &self.pending { + Some(p) if p.unique_id == request.unique_id => Ok(()), + _ => Err((HostPairingFailure::WrongClient, Error::PairingRefused)), + } + } + + fn next_phase(&mut self, state: HostPairingState, now: Instant, timeout: Duration) { + self.state = state; + self.deadline = now.saturating_add(timeout); + } + + fn step( + &mut self, + identity: &HostIdentity, + request: &PairRequest, + transport: Transport<'_>, + now: Instant, + rng: &mut dyn RandomSource, + ) -> core::result::Result { + let bad = |e: Error| (HostPairingFailure::Malformed, e); + match (self.state, &request.phase) { + (HostPairingState::AwaitGetServerCert, PairPhase::GetServerCert { salt, client_cert_pem }) => { + check_unique_id(&request.unique_id).map_err(bad)?; + if let Some(name) = &request.device_name { + cap("devicename", MAX_PAIR_DEVICE_NAME_BYTES, name.len()).map_err(bad)?; + if name.chars().any(char::is_control) { + return Err(bad(malformed("devicename"))); + } + } + let cert = ServerCert::from_pem(client_cert_pem).map_err(bad)?; + self.salt = *salt; + self.pending = Some(PendingClient { + unique_id: request.unique_id.clone(), + device_name: request.device_name.clone(), + cert_der: cert.der().to_vec(), + }); + self.client_cert = Some(cert); + self.next_phase(HostPairingState::AwaitPin, now, self.config.pin_timeout); + Ok(HostPairingStep::HoldForPin) + } + (HostPairingState::AwaitClientChallenge, PairPhase::ClientChallenge(encrypted)) => { + self.same_client(request)?; + if encrypted.len() != CLIENT_CHALLENGE_LEN { + return Err(bad(malformed("clientchallenge is not 16 bytes"))); + } + let challenge = array::( + "clientchallenge", + &crypto::ecb_decrypt(&self.key, encrypted).map_err(bad)?, + 0, + ) + .map_err(bad)?; + rng.fill(&mut self.server_challenge); + rng.fill(&mut *self.host_secret); + let host_sig = identity.inner.cert_signature().map_err(bad)?; + let host_proof = crypto::proof_hash(&challenge, &host_sig, &self.host_secret).map_err(bad)?; + let plain = [&host_proof[..], &self.server_challenge[..]].concat(); + let answer = crypto::ecb_encrypt(&self.key, &plain).map_err(bad)?; + self.next_phase(HostPairingState::AwaitServerChallengeResp, now, self.config.phase_timeout); + Ok(HostPairingStep::Answer(PairAnswer::ChallengeResponse(answer))) + } + (HostPairingState::AwaitServerChallengeResp, PairPhase::ServerChallengeResp(encrypted)) => { + self.same_client(request)?; + if encrypted.len() != SERVER_CHALLENGE_RESP_LEN { + return Err(bad(malformed("serverchallengeresp is not 32 bytes"))); + } + let proof = crypto::ecb_decrypt(&self.key, encrypted).map_err(bad)?; + self.client_proof = array::("serverchallengeresp", &proof, 0).map_err(bad)?; + let signature = identity.inner.sign(&*self.host_secret).map_err(bad)?; + let answer = [&self.host_secret[..], &signature].concat(); + self.next_phase(HostPairingState::AwaitClientPairingSecret, now, self.config.phase_timeout); + Ok(HostPairingStep::Answer(PairAnswer::PairingSecret(answer))) + } + (HostPairingState::AwaitClientPairingSecret, PairPhase::ClientPairingSecret(value)) => { + self.same_client(request)?; + let (secret, signature) = crypto::split_pairing_secret(value).map_err(bad)?; + let cert = self.client_cert.as_ref().ok_or_else(|| bad(malformed("host pairing: no client cert")))?; + cert.verify(&secret, signature) + .map_err(|_| (HostPairingFailure::BadSignature, Error::PairingRefused))?; + let client_sig = cert.signature().map_err(bad)?; + let expected = crypto::proof_hash(&self.server_challenge, &client_sig, &secret).map_err(bad)?; + if !ct_eq(&expected, &self.client_proof) { + return Err((HostPairingFailure::WrongPin, Error::PairingRefused)); + } + self.next_phase(HostPairingState::AwaitPairChallenge, now, self.config.phase_timeout); + Ok(HostPairingStep::Answer(PairAnswer::Paired)) + } + (HostPairingState::AwaitPairChallenge, PairPhase::PairChallenge) => { + self.same_client(request)?; + let pending = self.pending.as_ref().ok_or((HostPairingFailure::WrongClient, Error::PairingRefused))?; + let Transport::Https { client_cert_der } = transport else { + return Err((HostPairingFailure::WrongClient, Error::PairingRefused)); + }; + if !ct_eq(client_cert_der, &pending.cert_der) { + return Err((HostPairingFailure::WrongClient, Error::PairingRefused)); + } + let client = PairedClient { + cert_der: pending.cert_der.clone(), + unique_id: Some(pending.unique_id.clone()), + device_name: pending.device_name.clone(), + }; + self.paired = Some(client.clone()); + self.state = HostPairingState::Paired; + Ok(HostPairingStep::Paired(client)) + } + _ => Err((HostPairingFailure::WrongOrder, Error::PairingRefused)), + } + } + + /// The owner typed the PIN: derives the key `SHA-256(salt ‖ PIN)[0..16]` and returns the held answer to phase 1 + /// (the host certificate). Whether the PIN matches the client's shows only in phase 4. /// /// # Errors - /// [`Error::State`] unless the state is [`HostPairingState::AwaitPin`] (state unchanged); [`Error::TimedOut`] - /// past the PIN deadline (state becomes Failed); [`Error::Malformed`] for a different identity. + /// [`Error::State`] unless the state is [`HostPairingState::AwaitPin`] (state unchanged); [`Error::Malformed`] + /// for a different identity (state unchanged); [`Error::TimedOut`] past the PIN deadline (state becomes Failed). pub fn supply_pin(&mut self, identity: &HostIdentity, pin: Pin, now: Instant) -> Result { - let _ = (identity, pin, now); - Err(Error::Unimplemented) + if self.state != HostPairingState::AwaitPin { + return Err(Error::State { expected: "a phase-1 request held for the PIN" }); + } + if identity.cert_der() != self.host_cert_der.as_slice() { + return Err(malformed("host pairing: a different identity than at the start")); + } + if now > self.deadline { + return self.fail(HostPairingFailure::TimedOut, Error::TimedOut); + } + let pem = match identity.cert_pem() { + Ok(pem) => pem, + Err(e) => return self.fail(HostPairingFailure::Malformed, e), + }; + *self.key = crypto::derive_key(&self.salt, &pin)?; + self.next_phase(HostPairingState::AwaitClientChallenge, now, self.config.phase_timeout); + Ok(PairAnswer::ServerCert { pem }) } /// The owner closed the code box (or the caller gives up): the state becomes `Failed(Cancelled)` unless it is /// already terminal. Answer a held request with [`PairAnswer::Refused`]. - pub fn cancel(&mut self) {} + pub fn cancel(&mut self) { + if !self.is_over() { + self.state = HostPairingState::Failed(HostPairingFailure::Cancelled); + } + } - /// When the session times out, if it is still in progress. + /// When the session times out, if it is still in progress. The session is late only after this instant. #[must_use] - pub fn poll_timeout(&self) -> Option { - None + pub const fn poll_timeout(&self) -> Option { + if self.is_over() { None } else { Some(self.deadline) } } /// Wakes the session at its deadline: returns `true` when this call moved it to `Failed(TimedOut)` (answer a /// held request with [`PairAnswer::Refused`]). pub fn handle_timeout(&mut self, now: Instant) -> bool { - let _ = now; - false + if self.is_over() || now <= self.deadline { + return false; + } + self.state = HostPairingState::Failed(HostPairingFailure::TimedOut); + true } /// Where the handshake is. diff --git a/crates/domistream/tests/host_pairing.rs b/crates/domistream/tests/host_pairing.rs index 9e710c3..7307177 100644 --- a/crates/domistream/tests/host_pairing.rs +++ b/crates/domistream/tests/host_pairing.rs @@ -308,10 +308,13 @@ fn genuine_phase4(d: &mut Duo) -> (Vec, Vec) { } } +/// Builds a phase-4 value from the genuine secret and signature. +type Forge = dyn Fn(&[u8], &[u8]) -> Vec; + #[test] fn bad_client_signatures() { let rogue = rogue_id(); - let cases: Vec<(&str, Box Vec>)> = vec![ + let cases: Vec<(&str, Box)> = vec![ ("signed by another key", Box::new(move |s, _| [s.to_vec(), rogue.sign(s).unwrap()].concat())), ( "one bit flipped",