586 lines
25 KiB
Rust
586 lines
25 KiB
Rust
//! The host's half of the PIN pairing handshake (`docs/PROTOCOL.md` 1.5), as a sans-I/O state machine: the
|
|
//! mirror of the client's [`crate::pairing::PairingSession`].
|
|
//!
|
|
//! ```text
|
|
//! new ─▶ AwaitGetServerCert ─(getservercert)─▶ AwaitPin ─(supply_pin)─▶ AwaitClientChallenge
|
|
//! │ (clientchallenge)
|
|
//! AwaitClientPairingSecret ◀─(serverchallengeresp)─ AwaitServerChallengeResp ◀┘
|
|
//! │ (clientpairingsecret: signature and proof checked)
|
|
//! ▼
|
|
//! AwaitPairChallenge ─(pairchallenge over HTTPS, same client certificate)─▶ Paired
|
|
//! any step: wrong phase / bad input / bad signature / wrong PIN / deadline passed / cancel ─▶ Failed
|
|
//! ```
|
|
//!
|
|
//! The PIN is not known when the first phase arrives: the machine answers it with [`HostPairingStep::HoldForPin`]
|
|
//! and the caller keeps that HTTP request open until the owner types the code from the phone into Arena Domi's
|
|
//! "Enter the code from your phone" box; [`HostPairingSession::supply_pin`] then returns the held answer.
|
|
//!
|
|
//! **Trusted clients (Tessera grants).** The handshake's AES key is `SHA-256(salt ‖ PIN)`, so the wire handshake
|
|
//! cannot complete unless both sides know the same PIN. A client the owner already trusts (a Tessera grant) does
|
|
//! not run it at all: [`PairedClient::trusted`] records its certificate directly, with no PIN anywhere
|
|
//! (`docs/LUMEN-HOST-PLAN.md` 1.9).
|
|
//!
|
|
//! When a call fails, the state becomes [`HostPairingState::Failed`] and the caller answers the request (and a
|
|
//! held phase-1 request, if any) with [`PairAnswer::Refused`]. Failed and Paired are terminal.
|
|
|
|
use core::fmt;
|
|
use core::time::Duration;
|
|
|
|
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);
|
|
/// Default time the client has for each later phase after the host's previous answer.
|
|
pub const DEFAULT_PHASE_TIMEOUT: Duration = Duration::from_secs(30);
|
|
/// Maximum length of the device name kept from the first phase, in bytes.
|
|
pub const MAX_PAIR_DEVICE_NAME_BYTES: usize = 256;
|
|
/// Length of the encrypted client challenge (phase 2), in bytes.
|
|
pub const CLIENT_CHALLENGE_LEN: usize = CHALLENGE_LEN;
|
|
/// Length of the encrypted client proof (phase 3), in bytes.
|
|
pub const SERVER_CHALLENGE_RESP_LEN: usize = HASH_LEN;
|
|
/// Length of the host secret (phase 3 answer), in bytes.
|
|
pub const HOST_SECRET_LEN: usize = SECRET_LEN;
|
|
|
|
/// The host's long-lived GameStream identity: a self-signed RSA-2048 / SHA-256 certificate and its key. The same
|
|
/// certificate is sent as `plaincert` while pairing and presented by the HTTPS server. `Debug` never prints the key.
|
|
#[derive(Clone)]
|
|
pub struct HostIdentity {
|
|
inner: ClientIdentity,
|
|
}
|
|
|
|
impl HostIdentity {
|
|
/// Generates a new key and self-signed certificate (same rules as
|
|
/// [`crate::pairing::ClientIdentity::generate`]); `not_before_unix` is passed in, never read from a clock.
|
|
///
|
|
/// # 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<Self> {
|
|
ClientIdentity::generate(rng, common_name, not_before_unix).map(|inner| Self { inner })
|
|
}
|
|
|
|
/// Loads a stored identity and checks that the key matches the certificate.
|
|
///
|
|
/// # Errors
|
|
/// As [`crate::pairing::ClientIdentity::from_der`].
|
|
pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result<Self> {
|
|
ClientIdentity::from_der(cert_der, key_pkcs8_der).map(|inner| Self { inner })
|
|
}
|
|
|
|
/// The certificate, DER (what the HTTPS server presents).
|
|
#[must_use]
|
|
pub fn cert_der(&self) -> &[u8] {
|
|
self.inner.cert_der()
|
|
}
|
|
|
|
/// The private key, PKCS#8 DER, for the secret store and the TLS stack.
|
|
#[must_use]
|
|
pub fn key_pkcs8_der(&self) -> &[u8] {
|
|
self.inner.key_pkcs8_der()
|
|
}
|
|
|
|
/// The certificate as PEM text (what `plaincert` carries, hex-encoded).
|
|
///
|
|
/// # Errors
|
|
/// None today.
|
|
pub fn cert_pem(&self) -> Result<String> {
|
|
self.inner.cert_pem()
|
|
}
|
|
}
|
|
|
|
impl fmt::Debug for HostIdentity {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.debug_struct("HostIdentity")
|
|
.field("cert_der_len", &self.inner.cert_der().len())
|
|
.field("key", &"<redacted>")
|
|
.finish()
|
|
}
|
|
}
|
|
|
|
/// One pairing phase as the client sent it (`docs/PROTOCOL.md` 1.5), hex already decoded by
|
|
/// [`crate::host::http`]. Lengths are checked by the state machine, not here.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub enum PairPhase {
|
|
/// Phase 1 (`phrase=getservercert`): the 16-byte salt and the client certificate as PEM text.
|
|
GetServerCert {
|
|
/// `salt`.
|
|
salt: [u8; SALT_LEN],
|
|
/// `clientcert`, hex-decoded: the client certificate PEM.
|
|
client_cert_pem: Vec<u8>,
|
|
},
|
|
/// Phase 2 (`clientchallenge`): `E_K(C)`.
|
|
ClientChallenge(Vec<u8>),
|
|
/// Phase 3 (`serverchallengeresp`): `E_K(H_c)`.
|
|
ServerChallengeResp(Vec<u8>),
|
|
/// Phase 4 (`clientpairingsecret`): `secret_c ‖ Sign_client(secret_c)`.
|
|
ClientPairingSecret(Vec<u8>),
|
|
/// Phase 5 (`phrase=pairchallenge`), over HTTPS with the client certificate.
|
|
PairChallenge,
|
|
}
|
|
|
|
impl PairPhase {
|
|
/// The phase number, 1..=5 (for logs).
|
|
#[must_use]
|
|
pub const fn number(&self) -> u8 {
|
|
match self {
|
|
Self::GetServerCert { .. } => 1,
|
|
Self::ClientChallenge(_) => 2,
|
|
Self::ServerChallengeResp(_) => 3,
|
|
Self::ClientPairingSecret(_) => 4,
|
|
Self::PairChallenge => 5,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A `/pair` request: who sends it and which phase.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct PairRequest {
|
|
/// `uniqueid`: the client's id; every phase of one pairing must carry the same one.
|
|
pub unique_id: String,
|
|
/// `devicename`, if sent (kept from phase 1, shown to the owner).
|
|
pub device_name: Option<String>,
|
|
/// The phase.
|
|
pub phase: PairPhase,
|
|
}
|
|
|
|
/// How a request reached the host.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum Transport<'a> {
|
|
/// Plain HTTP.
|
|
Http,
|
|
/// HTTPS; `client_cert_der` is the certificate the client presented in the TLS handshake.
|
|
Https {
|
|
/// The client's TLS certificate, DER.
|
|
client_cert_der: &'a [u8],
|
|
},
|
|
}
|
|
|
|
impl Transport<'_> {
|
|
/// [`Scheme::Http`] or [`Scheme::Https`].
|
|
#[must_use]
|
|
pub const fn scheme(&self) -> Scheme {
|
|
match self {
|
|
Self::Http => Scheme::Http,
|
|
Self::Https { .. } => Scheme::Https,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// What the host answers to one phase (`<root status_code="200"><paired>…</paired>…</root>`); serialize it with
|
|
/// [`crate::host::http::pair_answer_xml`].
|
|
#[derive(Clone, PartialEq, Eq)]
|
|
pub enum PairAnswer {
|
|
/// `paired=0`: pairing refused or failed.
|
|
Refused,
|
|
/// Phase 1: `paired=1`, `plaincert` = the host certificate PEM.
|
|
ServerCert {
|
|
/// The host certificate PEM text.
|
|
pem: String,
|
|
},
|
|
/// Phase 2: `paired=1`, `challengeresponse` = `E_K(H_s ‖ S_c)`, 48 bytes.
|
|
ChallengeResponse(Vec<u8>),
|
|
/// Phase 3: `paired=1`, `pairingsecret` = `secret_s ‖ Sign_host(secret_s)`.
|
|
PairingSecret(Vec<u8>),
|
|
/// Phases 4 and 5: `paired=1` alone.
|
|
Paired,
|
|
}
|
|
|
|
impl fmt::Debug for PairAnswer {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::Refused => f.write_str("Refused"),
|
|
Self::ServerCert { pem } => f.debug_struct("ServerCert").field("pem_len", &pem.len()).finish(),
|
|
Self::ChallengeResponse(v) => f.debug_tuple("ChallengeResponse").field(&v.len()).finish(),
|
|
Self::PairingSecret(v) => f.debug_tuple("PairingSecret").field(&v.len()).finish(),
|
|
Self::Paired => f.write_str("Paired"),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A client whose certificate the host accepts on HTTPS from now on. Store it (signed by the host key, per
|
|
/// `docs/LUMEN-HOST-PLAN.md` 1.9).
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct PairedClient {
|
|
/// The client certificate, DER: exactly what its TLS handshake must present.
|
|
pub cert_der: Vec<u8>,
|
|
/// `uniqueid` from the pairing, `None` for a trusted client recorded without a handshake.
|
|
pub unique_id: Option<String>,
|
|
/// `devicename` from the pairing, if sent.
|
|
pub device_name: Option<String>,
|
|
}
|
|
|
|
impl PairedClient {
|
|
/// The Tessera grant path: records a client certificate the owner already trusts, with no PIN and no wire
|
|
/// handshake. Checks that it is one well-formed X.509 certificate with an RSA key.
|
|
///
|
|
/// # Errors
|
|
/// [`Error::TooLarge`] over [`crate::pairing::identity::MAX_CERT_DER_BYTES`], [`Error::Malformed`] otherwise.
|
|
pub fn trusted(cert_der: &[u8]) -> Result<Self> {
|
|
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
|
|
/// in constant time.
|
|
///
|
|
/// # Errors
|
|
/// [`Error::TooLarge`] over [`crate::pairing::identity::MAX_CERT_DER_BYTES`].
|
|
pub fn matches(&self, presented_der: &[u8]) -> Result<bool> {
|
|
cap("presented certificate", MAX_CERT_DER_BYTES, presented_der.len())?;
|
|
Ok(ct_eq(&self.cert_der, presented_der))
|
|
}
|
|
}
|
|
|
|
/// The client that started a pairing, as phase 1 described it: what the owner's prompt shows.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct PendingClient {
|
|
/// `uniqueid`.
|
|
pub unique_id: String,
|
|
/// `devicename`, if sent.
|
|
pub device_name: Option<String>,
|
|
/// The client certificate, DER.
|
|
pub cert_der: Vec<u8>,
|
|
}
|
|
|
|
/// Where the host's handshake is.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
pub enum HostPairingState {
|
|
/// Nothing received yet; waiting for phase 1 (`getservercert`).
|
|
AwaitGetServerCert,
|
|
/// Phase 1 received; its answer is held until [`HostPairingSession::supply_pin`].
|
|
AwaitPin,
|
|
/// Phase 1 answered (`plaincert`); waiting for phase 2 (`clientchallenge`).
|
|
AwaitClientChallenge,
|
|
/// Phase 2 answered (`challengeresponse`); waiting for phase 3 (`serverchallengeresp`).
|
|
AwaitServerChallengeResp,
|
|
/// Phase 3 answered (`pairingsecret`); waiting for phase 4 (`clientpairingsecret`).
|
|
AwaitClientPairingSecret,
|
|
/// Phase 4 checked and answered; waiting for phase 5 (`pairchallenge` over HTTPS).
|
|
AwaitPairChallenge,
|
|
/// Done; see [`HostPairingSession::paired_client`].
|
|
Paired,
|
|
/// Stopped; see [`HostPairingFailure`]. No further calls are accepted.
|
|
Failed(HostPairingFailure),
|
|
}
|
|
|
|
/// Why the host stopped a pairing.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
pub enum HostPairingFailure {
|
|
/// The client's proof `H_c` did not match: the PIN typed on the host differs from the client's (or someone is in
|
|
/// the middle).
|
|
WrongPin,
|
|
/// The client's signature over its secret did not verify against the certificate from phase 1.
|
|
BadSignature,
|
|
/// A phase arrived that is not the one expected now (replayed, reordered or skipped).
|
|
WrongOrder,
|
|
/// A phase came from another client than phase 1 (other `uniqueid`, or phase 5 without the phase-1 certificate
|
|
/// over HTTPS).
|
|
WrongClient,
|
|
/// A phase's value had the wrong length or the client certificate did not parse.
|
|
Malformed,
|
|
/// The caller's time passed the deadline (PIN not typed in time, or the client stopped answering).
|
|
TimedOut,
|
|
/// The caller cancelled (the owner closed the code box).
|
|
Cancelled,
|
|
}
|
|
|
|
/// Timeouts of one pairing.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct HostPairingConfig {
|
|
/// How long the owner has to type the PIN after phase 1 arrives.
|
|
pub pin_timeout: Duration,
|
|
/// How long the client has for each phase after the host's previous answer (and for phase 1 after `new`).
|
|
pub phase_timeout: Duration,
|
|
}
|
|
|
|
impl Default for HostPairingConfig {
|
|
fn default() -> Self {
|
|
Self { pin_timeout: DEFAULT_PIN_TIMEOUT, phase_timeout: DEFAULT_PHASE_TIMEOUT }
|
|
}
|
|
}
|
|
|
|
/// What to do with the request just handled.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub enum HostPairingStep {
|
|
/// Answer it now with this.
|
|
Answer(PairAnswer),
|
|
/// Hold it open: the answer comes from [`HostPairingSession::supply_pin`] (or is [`PairAnswer::Refused`] when the
|
|
/// session fails or times out first). Show the owner the code box for [`HostPairingSession::pending_client`].
|
|
HoldForPin,
|
|
/// Pairing finished: answer with [`PairAnswer::Paired`] and store the client.
|
|
Paired(PairedClient),
|
|
}
|
|
|
|
/// One pairing attempt by one client.
|
|
pub struct HostPairingSession {
|
|
state: HostPairingState,
|
|
config: HostPairingConfig,
|
|
deadline: Instant,
|
|
host_cert_der: Vec<u8>,
|
|
pending: Option<PendingClient>,
|
|
client_cert: Option<ServerCert>,
|
|
salt: [u8; SALT_LEN],
|
|
key: zeroize::Zeroizing<[u8; 16]>,
|
|
server_challenge: [u8; CHALLENGE_LEN],
|
|
host_secret: zeroize::Zeroizing<[u8; SECRET_LEN]>,
|
|
client_proof: [u8; HASH_LEN],
|
|
paired: Option<PairedClient>,
|
|
}
|
|
|
|
impl HostPairingSession {
|
|
/// A new pairing, waiting for phase 1 until `now + config.phase_timeout`. `identity` must be passed to every
|
|
/// later call (it is borrowed per call, so the session never holds a copy of the private key).
|
|
#[must_use]
|
|
pub fn new(identity: &HostIdentity, config: HostPairingConfig, now: Instant) -> Self {
|
|
Self {
|
|
state: HostPairingState::AwaitGetServerCert,
|
|
config,
|
|
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],
|
|
host_secret: zeroize::Zeroizing::new([0; SECRET_LEN]),
|
|
client_proof: [0; HASH_LEN],
|
|
paired: None,
|
|
}
|
|
}
|
|
|
|
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
|
|
/// [`Error::PairingRefused`] for a wrong phase, client, signature or PIN; [`Error::Malformed`] /
|
|
/// [`Error::TooLarge`] for bad values; [`Error::TimedOut`] past the deadline; in each case the state becomes
|
|
/// [`HostPairingState::Failed`]. [`Error::State`] after `Paired` or `Failed`; [`Error::Malformed`] for a
|
|
/// different identity than at `new` (state unchanged).
|
|
pub fn handle(
|
|
&mut self,
|
|
identity: &HostIdentity,
|
|
request: &PairRequest,
|
|
transport: Transport<'_>,
|
|
now: Instant,
|
|
rng: &mut dyn RandomSource,
|
|
) -> Result<HostPairingStep> {
|
|
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),
|
|
}
|
|
}
|
|
|
|
/// 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
|
|
/// [`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<PairAnswer> {
|
|
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) {
|
|
if !self.is_over() {
|
|
self.state = HostPairingState::Failed(HostPairingFailure::Cancelled);
|
|
}
|
|
}
|
|
|
|
/// When the session times out, if it is still in progress. The session is late only after this instant.
|
|
#[must_use]
|
|
pub const fn poll_timeout(&self) -> Option<Instant> {
|
|
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 {
|
|
if self.is_over() || now <= self.deadline {
|
|
return false;
|
|
}
|
|
self.state = HostPairingState::Failed(HostPairingFailure::TimedOut);
|
|
true
|
|
}
|
|
|
|
/// Where the handshake is.
|
|
#[must_use]
|
|
pub const fn state(&self) -> HostPairingState {
|
|
self.state
|
|
}
|
|
|
|
/// The client of phase 1 (for the owner's prompt and the grant check), once phase 1 has arrived.
|
|
#[must_use]
|
|
pub const fn pending_client(&self) -> Option<&PendingClient> {
|
|
self.pending.as_ref()
|
|
}
|
|
|
|
/// The paired client, once [`HostPairingState::Paired`].
|
|
#[must_use]
|
|
pub const fn paired_client(&self) -> Option<&PairedClient> {
|
|
self.paired.as_ref()
|
|
}
|
|
}
|
|
|
|
impl fmt::Debug for HostPairingSession {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.debug_struct("HostPairingSession")
|
|
.field("state", &self.state)
|
|
.field("deadline", &self.deadline)
|
|
.finish_non_exhaustive()
|
|
}
|
|
}
|