[domistream] Host HTTP: tests first (request head and query parsing, caps, XML answers read back by the client parsers); API stubs return Unimplemented

This commit is contained in:
2026-12-04 12:24:42 +01:00
parent 7b9b1f4e9c
commit 3aa3775de8
7 changed files with 1545 additions and 0 deletions
+113
View File
@@ -0,0 +1,113 @@
//! The host's XML answers (`docs/PROTOCOL.md` 1.1-1.5): every body is `<root status_code="…">` with elements
//! inside. Text and attribute values are escaped; a value the client's parser would refuse (too long, empty where
//! required, control characters) is refused here first, so the host never sends what its clients cannot read.
use crate::host::pairing::PairAnswer;
use crate::http::{App, Scheme};
use crate::{Error, Result};
/// What the host says about itself in `serverinfo` (`docs/PROTOCOL.md` 1.2).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostInfo {
/// `hostname`: the name the client shows. Non-empty.
pub hostname: String,
/// `appversion`, the protocol version string, e.g. `7.1.431.-1`.
pub app_version: String,
/// `GfeVersion`, the compatibility version string.
pub gfe_version: String,
/// `uniqueid`: the host's stable id. Non-empty.
pub unique_id: String,
/// `HttpsPort`.
pub https_port: u16,
/// `ExternalPort`: the HTTP port.
pub http_port: u16,
/// `mac` for Wake-on-LAN, written `aa:bb:cc:dd:ee:ff`; `None` writes an empty element.
pub mac: Option<[u8; 6]>,
/// `LocalIP`: the host's address as this client reached it; empty is allowed.
pub local_ip: String,
/// `MaxLumaPixelsHEVC`; 0 = no HEVC.
pub max_luma_pixels_hevc: u64,
/// `ServerCodecModeSupport` bitmask (bit meanings UNKNOWN U25).
pub codec_mode_support: u32,
/// `currentgame`: id of the running app, 0 = none.
pub current_game: u32,
/// Prefix of `state`: written `<prefix>_SERVER_BUSY` when `current_game != 0`, else `<prefix>_SERVER_FREE`.
/// Letters, digits and `_` only.
pub state_prefix: String,
}
/// `serverinfo`. `PairStatus` is 1 only when the request came over HTTPS (`scheme`) with a paired client certificate
/// (`client_paired`); over plain HTTP it is always 0 (`docs/PROTOCOL.md` 1.2).
///
/// # Errors
/// [`Error::Malformed`] for an empty `hostname` or `unique_id`, a bad `state_prefix`, or control characters;
/// [`Error::TooLarge`] for a field over [`crate::http::serverinfo::MAX_SERVERINFO_FIELD_BYTES`].
pub fn server_info_xml(info: &HostInfo, scheme: Scheme, client_paired: bool) -> Result<Vec<u8>> {
let _ = (info, scheme, client_paired);
Err(Error::Unimplemented)
}
/// `applist`: one `<App>` per app with `AppTitle`, `ID` and `IsHdrSupported`, in the given order.
///
/// # Errors
/// [`Error::TooLarge`] over [`crate::http::applist::MAX_APPS`] apps or a title over
/// [`crate::http::applist::MAX_APP_TITLE_BYTES`]; [`Error::Malformed`] for a duplicate id or control characters.
pub fn app_list_xml(apps: &[App]) -> Result<Vec<u8>> {
let _ = apps;
Err(Error::Unimplemented)
}
/// `launch`: `gamesession=1` and `sessionUrl0=rtsp://<rtsp_host>:<rtsp_port>` (`docs/PROTOCOL.md` 1.4).
///
/// # Errors
/// [`Error::Malformed`] unless `rtsp_host` is a host name, an IPv4 address or a bracketed IPv6 literal and the
/// port is not 0; [`Error::TooLarge`] for a URL over [`crate::http::launch::MAX_SESSION_URL_BYTES`].
pub fn launch_xml(rtsp_host: &str, rtsp_port: u16) -> Result<Vec<u8>> {
let _ = (rtsp_host, rtsp_port);
Err(Error::Unimplemented)
}
/// `resume`: the same body as [`launch_xml`] (the client reads both with one parser).
///
/// # Errors
/// As [`launch_xml`].
pub fn resume_xml(rtsp_host: &str, rtsp_port: u16) -> Result<Vec<u8>> {
let _ = (rtsp_host, rtsp_port);
Err(Error::Unimplemented)
}
/// A bare `<root status_code="200"/>`: the answer to `cancel` and `unpair`.
#[must_use]
pub fn ok_xml() -> Vec<u8> {
Vec::new()
}
/// One pairing answer: `paired` and the phase's element, hex-encoded (`docs/PROTOCOL.md` 1.5).
///
/// # Errors
/// [`Error::TooLarge`] for a value over the client's caps (a certificate over
/// [`crate::pairing::identity::MAX_CERT_PEM_BYTES`], a body over [`crate::pairing::MAX_PAIR_RESPONSE_BYTES`]).
pub fn pair_answer_xml(answer: &PairAnswer) -> Result<Vec<u8>> {
let _ = answer;
Err(Error::Unimplemented)
}
/// The error root: `<root status_code="<code>" status_message="<message>"/>` (`docs/PROTOCOL.md` 1.1).
///
/// # Errors
/// [`Error::Malformed`] for code 200 or a code outside 100..=999, or control characters in `message`;
/// [`Error::TooLarge`] for a message over [`MAX_STATUS_MESSAGE_BYTES`].
pub fn error_xml(status_code: u32, message: &str) -> Result<Vec<u8>> {
let _ = (status_code, message);
Err(Error::Unimplemented)
}
/// Maximum length of an error's `status_message`, in bytes.
pub const MAX_STATUS_MESSAGE_BYTES: usize = 256;
/// Most apps one `applist` answer carries: the client's [`crate::http::applist::MAX_APPS`], lowered so the
/// document stays within the client's [`crate::http::xml::MAX_XML_ELEMENTS`] (the root plus four elements per app).
pub const MAX_WRITTEN_APPS: usize = {
let by_elements = (crate::http::xml::MAX_XML_ELEMENTS - 1) / 4;
if crate::http::applist::MAX_APPS < by_elements { crate::http::applist::MAX_APPS } else { by_elements }
};
+176
View File
@@ -0,0 +1,176 @@
//! The host's HTTP side (`docs/PROTOCOL.md` section 1): strict parsing of an incoming `GET` request head and its
//! query into a typed [`Route`], and the XML answers ([`answer`]).
//!
//! Every request is hostile input. Caps are checked before anything is allocated: the head
//! ([`MAX_HEAD_BYTES`]), the target ([`MAX_PATH_BYTES`], [`MAX_QUERY_BYTES`]), the number of parameters
//! ([`MAX_PARAMS`]) and each name and value ([`MAX_PARAM_NAME_BYTES`], [`MAX_PARAM_VALUE_BYTES`]), then each typed
//! field's own limit. A request never carries a body; a `Content-Length` other than 0 or any `Transfer-Encoding` is
//! refused.
//!
//! Callers whose HTTP server already split the head (TLS front end, an HTTP library) pass the request target to
//! [`parse_target`]; callers reading the raw TCP stream cut the head with [`find_head_end`] and pass it to
//! [`parse_request_head`].
use crate::host::pairing::PairRequest;
use crate::{Error, Result, SessionKeys};
pub mod answer;
pub use answer::{HostInfo, app_list_xml, error_xml, launch_xml, ok_xml, pair_answer_xml, resume_xml, server_info_xml};
/// Maximum size of a request head (request line, headers and the empty line), in bytes.
pub const MAX_HEAD_BYTES: usize = 64 * 1024;
/// Maximum number of header lines.
pub const MAX_HEADERS: usize = 64;
/// Maximum length of the path (before `?`), in bytes.
pub const MAX_PATH_BYTES: usize = 256;
/// Maximum length of the query (after `?`), in bytes. Room for a phase-1 `clientcert` at its cap.
pub const MAX_QUERY_BYTES: usize = 40 * 1024;
/// Maximum number of query parameters.
pub const MAX_PARAMS: usize = 32;
/// Maximum length of a parameter name, in bytes.
pub const MAX_PARAM_NAME_BYTES: usize = 64;
/// Maximum length of one parameter value as sent (percent-encoded), in bytes: a hex `clientcert` at
/// [`crate::pairing::identity::MAX_CERT_PEM_BYTES`].
pub const MAX_PARAM_VALUE_BYTES: usize = 2 * crate::pairing::identity::MAX_CERT_PEM_BYTES;
/// Maximum length of a hex value other than `clientcert`, in characters (16 bytes of secret plus an RSA-8192
/// signature).
pub const MAX_HEX_VALUE_CHARS: usize = 2 * (crate::pairing::SECRET_LEN + crate::pairing::MAX_SIGNATURE_BYTES);
/// Maximum length of `devicename`, in bytes.
pub const MAX_DEVICE_NAME_BYTES: usize = crate::host::pairing::MAX_PAIR_DEVICE_NAME_BYTES;
/// Largest width or height accepted in `mode`.
pub const MAX_MODE_DIMENSION: u32 = 16_384;
/// Largest frame rate accepted in `mode`.
pub const MAX_MODE_FPS: u32 = 1000;
/// A stream mode, `mode=<width>x<height>x<fps>`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DisplayMode {
/// Width in pixels, 1..=[`MAX_MODE_DIMENSION`].
pub width: u32,
/// Height in pixels, 1..=[`MAX_MODE_DIMENSION`].
pub height: u32,
/// Frames per second, 1..=[`MAX_MODE_FPS`].
pub fps: u32,
}
/// `GET /launch` (`docs/PROTOCOL.md` 1.4).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LaunchRequest {
/// `appid`.
pub app_id: u32,
/// `mode`.
pub mode: DisplayMode,
/// `rikey` and `rikeyid`.
pub keys: SessionKeys,
/// `hdrMode`, if sent.
pub hdr: Option<bool>,
/// `surroundAudioInfo`, if sent: `(channel_mask << 16) | channel_count`.
pub surround_audio_info: Option<u32>,
}
/// `GET /resume` (`docs/PROTOCOL.md` 1.4): fresh keys; the launch parameters only if the client repeats them.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResumeRequest {
/// `rikey` and `rikeyid`.
pub keys: SessionKeys,
/// `appid`, if sent.
pub app_id: Option<u32>,
/// `mode`, if sent.
pub mode: Option<DisplayMode>,
/// `hdrMode`, if sent.
pub hdr: Option<bool>,
/// `surroundAudioInfo`, if sent.
pub surround_audio_info: Option<u32>,
}
/// What the request asks for.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Route {
/// `/serverinfo` (HTTP or HTTPS).
ServerInfo,
/// `/applist` (HTTPS).
AppList,
/// `/launch` (HTTPS).
Launch(LaunchRequest),
/// `/resume` (HTTPS).
Resume(ResumeRequest),
/// `/cancel` (HTTPS).
Cancel,
/// `/pair` (phases 1-4 over HTTP, phase 5 over HTTPS); feed it to [`crate::host::pairing::HostPairingSession`].
Pair(PairRequest),
/// `/unpair` (HTTPS).
Unpair,
/// `/appasset` (HTTPS): box art of one app.
AppAsset {
/// `appid`.
app_id: u32,
},
/// Any other path (answer 404). The path as sent, never decoded, never used to open anything.
Unknown {
/// The path.
path: String,
},
}
/// One parsed request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostRequest {
/// The route and its typed parameters.
pub route: Route,
/// `uniqueid`, if sent (required for `/pair`).
pub unique_id: Option<String>,
/// Parameters this parser does not know, decoded, in order: kept for logs so black-box clients can be measured
/// (`docs/PROTOCOL.md` UNKNOWN U4). Never used to decide anything.
pub other_params: Vec<(String, String)>,
}
/// Finds the end of a request head in the bytes read so far: `Some(len)` (the head is `buf[..len]`, ending in the
/// empty line) or `None` (read more).
///
/// # Errors
/// [`Error::TooLarge`] when no head end is within the first [`MAX_HEAD_BYTES`].
pub fn find_head_end(buf: &[u8]) -> Result<Option<usize>> {
let _ = buf;
Err(Error::Unimplemented)
}
/// Parses one complete request head (`GET <target> HTTP/1.1`, headers, the empty line, nothing after it).
///
/// # Errors
/// [`Error::TooLarge`] over a cap, [`Error::Unsupported`] for a method other than `GET`, [`Error::Malformed`] for
/// anything else that is not a strict HTTP/1.x head or a valid target (see [`parse_target`]).
pub fn parse_request_head(head: &[u8]) -> Result<HostRequest> {
let _ = head;
Err(Error::Unimplemented)
}
/// Parses a request target (`/path?query`) into a typed request.
///
/// # Errors
/// [`Error::TooLarge`] over a cap, [`Error::Malformed`] for a bad character, a bad or repeated parameter, or a
/// missing or bad required parameter of a known route.
pub fn parse_target(target: &str) -> Result<HostRequest> {
let _ = target;
Err(Error::Unimplemented)
}
/// Parses a query string (without `?`) into decoded `(name, value)` pairs, in order. Names are taken as sent
/// (letters, digits, `_`, `-`, `.`); values are percent-decoded (`+` is a space) and must be UTF-8 without control
/// characters. Empty segments (`a=1&&b=2`) are skipped; a repeated name is refused.
///
/// # Errors
/// [`Error::TooLarge`] over [`MAX_QUERY_BYTES`], [`MAX_PARAMS`], [`MAX_PARAM_NAME_BYTES`] or
/// [`MAX_PARAM_VALUE_BYTES`]; [`Error::Malformed`] otherwise.
pub fn parse_query(query: &str) -> Result<Vec<(String, String)>> {
let _ = query;
Err(Error::Unimplemented)
}
/// Encodes `(name, value)` pairs as a query string (without `?`): values percent-encoded except RFC 3986 unreserved
/// characters, names as given. The inverse of [`parse_query`] for valid names and values.
#[must_use]
pub fn encode_query(params: &[(&str, &str)]) -> String {
let _ = params;
String::new()
}
+16
View File
@@ -0,0 +1,16 @@
//! The host side of GameStream, for Lumen (Arena Domi's own streaming host). Sans-I/O like the rest of the crate:
//! lumen-host owns the sockets, TLS, the clock, randomness and storage; this module only turns bytes into typed
//! requests, runs the pairing state machine and writes the XML answers.
//!
//! | Module | What (see `docs/PROTOCOL.md`) |
//! | :-- | :-- |
//! | [`http`] | strict parsing of an incoming `GET` request head and query into a typed [`http::Route`], and the XML answers (section 1) |
//! | [`pairing`] | the host's half of the PIN handshake, with a pending-PIN slot fed by the caller (section 1.5) |
//!
//! The client half of this crate ([`crate::pairing`], [`crate::http`]) is tested against this half in memory.
pub mod http;
pub mod pairing;
pub use http::{HostRequest, Route, parse_request_head, parse_target};
pub use pairing::{HostIdentity, HostPairingFailure, HostPairingSession, HostPairingState, PairAnswer, PairedClient};
+425
View File
@@ -0,0 +1,425 @@
//! 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;
use crate::pairing::{CHALLENGE_LEN, HASH_LEN, Pin, SALT_LEN, SECRET_LEN};
use crate::{Error, Instant, RandomSource, Result};
/// 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: crate::pairing::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> {
let _ = (rng, common_name, not_before_unix);
Err(Error::Unimplemented)
}
/// 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> {
let _ = (cert_der, key_pkcs8_der);
Err(Error::Unimplemented)
}
/// 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> {
let _ = cert_der;
Err(Error::Unimplemented)
}
/// 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> {
let _ = presented_der;
Err(Error::Unimplemented)
}
}
/// 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>,
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,
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,
}
}
/// Handles one `/pair` request. Draws randomness in phase 2 (host challenge and host secret).
///
/// # 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> {
let _ = (identity, request, transport, now, rng);
Err(Error::Unimplemented)
}
/// The owner typed the PIN: derives the key and returns the held answer to phase 1.
///
/// # 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.
pub fn supply_pin(&mut self, identity: &HostIdentity, pin: Pin, now: Instant) -> Result<PairAnswer> {
let _ = (identity, pin, now);
Err(Error::Unimplemented)
}
/// 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) {}
/// When the session times out, if it is still in progress.
#[must_use]
pub fn poll_timeout(&self) -> Option<Instant> {
None
}
/// 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
}
/// 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()
}
}