[domistream] Host pairing: the host's state machine (pending-PIN slot, proof and signature checks, deadlines from the caller, trusted clients without a PIN)

This commit is contained in:
2026-12-04 12:30:30 +01:00
parent 2ba0926cd6
commit 632561ef16
2 changed files with 189 additions and 26 deletions
+185 -25
View File
@@ -26,10 +26,15 @@
use core::fmt; use core::fmt;
use core::time::Duration; use core::time::Duration;
use crate::http::Scheme; use crate::http::{Scheme, check_unique_id};
use crate::pairing::{CHALLENGE_LEN, HASH_LEN, Pin, SALT_LEN, SECRET_LEN}; 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}; 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 /// Default time the owner has to type the PIN after the first phase arrives (the client waits as long, see
/// [`crate::pairing::STEP1_TIMEOUT`]). /// [`crate::pairing::STEP1_TIMEOUT`]).
pub const DEFAULT_PIN_TIMEOUT: Duration = Duration::from_secs(120); 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. /// certificate is sent as `plaincert` while pairing and presented by the HTTPS server. `Debug` never prints the key.
#[derive(Clone)] #[derive(Clone)]
pub struct HostIdentity { pub struct HostIdentity {
inner: crate::pairing::ClientIdentity, inner: ClientIdentity,
} }
impl HostIdentity { impl HostIdentity {
@@ -58,8 +63,7 @@ impl HostIdentity {
/// # Errors /// # Errors
/// [`Error::Malformed`] for a bad `common_name` or time, [`Error::Crypto`] if key generation fails. /// [`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<Self> { pub fn generate(rng: &mut dyn RandomSource, common_name: &str, not_before_unix: i64) -> Result<Self> {
let _ = (rng, common_name, not_before_unix); ClientIdentity::generate(rng, common_name, not_before_unix).map(|inner| Self { inner })
Err(Error::Unimplemented)
} }
/// Loads a stored identity and checks that the key matches the certificate. /// Loads a stored identity and checks that the key matches the certificate.
@@ -67,8 +71,7 @@ impl HostIdentity {
/// # Errors /// # Errors
/// As [`crate::pairing::ClientIdentity::from_der`]. /// As [`crate::pairing::ClientIdentity::from_der`].
pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result<Self> { pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result<Self> {
let _ = (cert_der, key_pkcs8_der); ClientIdentity::from_der(cert_der, key_pkcs8_der).map(|inner| Self { inner })
Err(Error::Unimplemented)
} }
/// The certificate, DER (what the HTTPS server presents). /// The certificate, DER (what the HTTPS server presents).
@@ -220,8 +223,8 @@ impl PairedClient {
/// # Errors /// # Errors
/// [`Error::TooLarge`] over [`crate::pairing::identity::MAX_CERT_DER_BYTES`], [`Error::Malformed`] otherwise. /// [`Error::TooLarge`] over [`crate::pairing::identity::MAX_CERT_DER_BYTES`], [`Error::Malformed`] otherwise.
pub fn trusted(cert_der: &[u8]) -> Result<Self> { pub fn trusted(cert_der: &[u8]) -> Result<Self> {
let _ = cert_der; ServerCert::from_der(cert_der)?;
Err(Error::Unimplemented) 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 /// TLS authorization: whether the certificate a client presents over HTTPS (DER) is exactly this one, compared
@@ -230,8 +233,8 @@ impl PairedClient {
/// # Errors /// # Errors
/// [`Error::TooLarge`] over [`crate::pairing::identity::MAX_CERT_DER_BYTES`]. /// [`Error::TooLarge`] over [`crate::pairing::identity::MAX_CERT_DER_BYTES`].
pub fn matches(&self, presented_der: &[u8]) -> Result<bool> { pub fn matches(&self, presented_der: &[u8]) -> Result<bool> {
let _ = presented_der; cap("presented certificate", MAX_CERT_DER_BYTES, presented_der.len())?;
Err(Error::Unimplemented) Ok(ct_eq(&self.cert_der, presented_der))
} }
} }
@@ -322,6 +325,7 @@ pub struct HostPairingSession {
deadline: Instant, deadline: Instant,
host_cert_der: Vec<u8>, host_cert_der: Vec<u8>,
pending: Option<PendingClient>, pending: Option<PendingClient>,
client_cert: Option<ServerCert>,
salt: [u8; SALT_LEN], salt: [u8; SALT_LEN],
key: zeroize::Zeroizing<[u8; 16]>, key: zeroize::Zeroizing<[u8; 16]>,
server_challenge: [u8; CHALLENGE_LEN], server_challenge: [u8; CHALLENGE_LEN],
@@ -341,6 +345,7 @@ impl HostPairingSession {
deadline: now.saturating_add(config.phase_timeout), deadline: now.saturating_add(config.phase_timeout),
host_cert_der: identity.cert_der().to_vec(), host_cert_der: identity.cert_der().to_vec(),
pending: None, pending: None,
client_cert: None,
salt: [0; SALT_LEN], salt: [0; SALT_LEN],
key: zeroize::Zeroizing::new([0; 16]), key: zeroize::Zeroizing::new([0; 16]),
server_challenge: [0; CHALLENGE_LEN], 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<T>(&mut self, why: HostPairingFailure, error: Error) -> Result<T> {
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 /// # Errors
/// [`Error::PairingRefused`] for a wrong phase, client, signature or PIN; [`Error::Malformed`] / /// [`Error::PairingRefused`] for a wrong phase, client, signature or PIN; [`Error::Malformed`] /
@@ -365,35 +382,178 @@ impl HostPairingSession {
now: Instant, now: Instant,
rng: &mut dyn RandomSource, rng: &mut dyn RandomSource,
) -> Result<HostPairingStep> { ) -> Result<HostPairingStep> {
let _ = (identity, request, transport, now, rng); if self.is_over() {
Err(Error::Unimplemented) 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<HostPairingStep, StepError> {
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::<CHALLENGE_LEN>(
"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::<HASH_LEN>("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 /// # Errors
/// [`Error::State`] unless the state is [`HostPairingState::AwaitPin`] (state unchanged); [`Error::TimedOut`] /// [`Error::State`] unless the state is [`HostPairingState::AwaitPin`] (state unchanged); [`Error::Malformed`]
/// past the PIN deadline (state becomes Failed); [`Error::Malformed`] for a different identity. /// 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<PairAnswer> { pub fn supply_pin(&mut self, identity: &HostIdentity, pin: Pin, now: Instant) -> Result<PairAnswer> {
let _ = (identity, pin, now); if self.state != HostPairingState::AwaitPin {
Err(Error::Unimplemented) 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 /// 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`]. /// 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] #[must_use]
pub fn poll_timeout(&self) -> Option<Instant> { pub const fn poll_timeout(&self) -> Option<Instant> {
None 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 /// Wakes the session at its deadline: returns `true` when this call moved it to `Failed(TimedOut)` (answer a
/// held request with [`PairAnswer::Refused`]). /// held request with [`PairAnswer::Refused`]).
pub fn handle_timeout(&mut self, now: Instant) -> bool { pub fn handle_timeout(&mut self, now: Instant) -> bool {
let _ = now; if self.is_over() || now <= self.deadline {
false return false;
}
self.state = HostPairingState::Failed(HostPairingFailure::TimedOut);
true
} }
/// Where the handshake is. /// Where the handshake is.
+4 -1
View File
@@ -308,10 +308,13 @@ fn genuine_phase4(d: &mut Duo) -> (Vec<u8>, Vec<u8>) {
} }
} }
/// Builds a phase-4 value from the genuine secret and signature.
type Forge = dyn Fn(&[u8], &[u8]) -> Vec<u8>;
#[test] #[test]
fn bad_client_signatures() { fn bad_client_signatures() {
let rogue = rogue_id(); let rogue = rogue_id();
let cases: Vec<(&str, Box<dyn Fn(&[u8], &[u8]) -> Vec<u8>>)> = vec![ let cases: Vec<(&str, Box<Forge>)> = vec![
("signed by another key", Box::new(move |s, _| [s.to_vec(), rogue.sign(s).unwrap()].concat())), ("signed by another key", Box::new(move |s, _| [s.to_vec(), rogue.sign(s).unwrap()].concat())),
( (
"one bit flipped", "one bit flipped",