//! The PIN pairing handshake (`docs/PROTOCOL.md` 1.5), as a sans-I/O state machine. //! //! In Arena Domi the PIN is never shown: Arena Domi TV makes it with [`Pin::generate`], sends it to arena-host over //! its own signed channel, and arena-host submits it to Sunshine. On the GameStream wire the handshake is unchanged. //! //! ```text //! start ─▶ AwaitServerCert ─▶ AwaitChallengeResponse ─▶ AwaitPairingSecret ─▶ AwaitClientSecretAck //! │ //! Paired ◀── AwaitPairChallenge (HTTPS) ◀───────────────────────┘ //! any step: host says paired=0 / bad proof / bad signature ─▶ Failed //! ``` //! //! Each [`PairingSession::handle_response`] consumes one HTTP answer body and returns the next request to send, //! or the finished [`PairedHost`]. Every answer must carry the element of its own step; an answer meant for another //! step fails the session, so replayed or reordered answers can never skip a check. use core::fmt; use crate::http::{HttpRequest, MAX_DEVICE_NAME_BYTES, Scheme, build, check_unique_id}; use crate::util::{ct_eq, hex_decode, hex_encode, malformed}; use crate::{Error, RandomSource, Result}; pub mod crypto; pub mod identity; pub use identity::{ClientIdentity, ServerCert}; /// Length of the salt sent in step 1. pub const SALT_LEN: usize = 16; /// Length of the client and host challenges. pub const CHALLENGE_LEN: usize = 16; /// Length of the client and host pairing secrets. pub const SECRET_LEN: usize = 16; /// Length of the SHA-256 proofs exchanged in steps 2 and 3. pub const HASH_LEN: usize = 32; /// Number of PIN digits. pub const PIN_LEN: usize = 4; /// Maximum size of one pairing answer body, in bytes. pub const MAX_PAIR_RESPONSE_BYTES: usize = 64 * 1024; /// Maximum size of a signature accepted from the host (RSA-8192), in bytes. pub const MAX_SIGNATURE_BYTES: usize = 1024; /// How long the caller should wait for the step 1 answer: the host holds it until the PIN is entered. pub const STEP1_TIMEOUT: core::time::Duration = core::time::Duration::from_secs(120); /// A 4-digit GameStream PIN. #[derive(Clone, Copy, PartialEq, Eq)] pub struct Pin([u8; PIN_LEN]); impl Pin { /// Draws a uniformly random PIN (rejection sampling, no modulo bias). /// /// # Errors /// None today. pub fn generate(rng: &mut dyn RandomSource) -> Result { let mut digits = [0u8; PIN_LEN]; for d in &mut digits { loop { let mut b = [0u8; 1]; rng.fill(&mut b); let [v] = b; // 250 = 25 × 10: values 250..=255 would favour digits 0-5. if v < 250 { *d = b'0' + v % 10; break; } } } Ok(Self(digits)) } /// Parses exactly four ASCII digits. /// /// # Errors /// [`Error::Malformed`] for anything else. pub fn from_digits(digits: &str) -> Result { let b = digits.as_bytes(); if b.len() != PIN_LEN || !b.iter().all(u8::is_ascii_digit) { return Err(malformed("PIN")); } let mut out = [0u8; PIN_LEN]; out.copy_from_slice(b); Ok(Self(out)) } /// The four ASCII digits. #[must_use] pub const fn as_bytes(&self) -> &[u8; PIN_LEN] { &self.0 } } impl fmt::Debug for Pin { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Pin()") } } /// Where the handshake is. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PairingState { /// Step 1 sent (`phrase=getservercert`); waiting for `plaincert`. The host holds this answer until the PIN is in. AwaitServerCert, /// Step 2 sent (`clientchallenge`); waiting for `challengeresponse`. AwaitChallengeResponse, /// Step 3 sent (`serverchallengeresp`); waiting for `pairingsecret`. AwaitPairingSecret, /// Step 4 sent (`clientpairingsecret`); waiting for `paired=1`. AwaitClientSecretAck, /// Step 5 sent over HTTPS (`phrase=pairchallenge`); waiting for `paired=1`. AwaitPairChallenge, /// Done. Paired, /// Stopped; see [`PairingFailure`]. No further calls are accepted. Failed(PairingFailure), } /// Why pairing stopped. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PairingFailure { /// The host answered `paired=0`. HostRefused, /// The host's proof `H_s` did not match: wrong PIN, or someone in the middle. ProofMismatch, /// The host's signature over its secret did not verify against its certificate. BadHostSignature, /// An answer could not be parsed or missed its element. MalformedAnswer, /// A non-200 HTTP or XML status. HostStatus, } /// What to do next. #[derive(Clone, Debug, PartialEq, Eq)] pub enum PairingStep { /// Send this request and feed its answer to [`PairingSession::handle_response`]. Send(HttpRequest), /// Pairing finished; store this. Paired(PairedHost), } /// The result of a successful pairing, to store with the client identity. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PairedHost { /// The host certificate from step 1; HTTPS connections must present exactly this certificate. pub server_cert: ServerCert, } /// The fields a pairing answer can carry (`1…`), hex-decoded. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct PairResponse { /// `paired == 1`. pub paired: bool, /// `plaincert`: the host certificate PEM (step 1). pub plain_cert: Option>, /// `challengeresponse`: `E_K(H_s ‖ S_c)`, 48 bytes (step 2). pub challenge_response: Option>, /// `pairingsecret`: `secret_s ‖ signature` (step 3). pub pairing_secret: Option>, } /// Parses one pairing answer. /// /// # Errors /// [`Error::TooLarge`] over [`MAX_PAIR_RESPONSE_BYTES`], [`Error::HostStatus`] for a non-200 answer, /// [`Error::Malformed`] for bad hex or a missing or bad `paired`. pub fn parse_pair_response(body: &[u8]) -> Result { let doc = crate::http::document(body, MAX_PAIR_RESPONSE_BYTES, "pairing answer")?; let r = &doc.root; let paired = match r.child("paired").map(|p| p.text.as_str()) { Some("1") => true, Some("0") => false, _ => return Err(malformed("pairing answer: paired")), }; let hex_field = |name: &str| -> Result>> { r.child(name).map(|e| hex_decode("pairing answer hex", &e.text)).transpose() }; Ok(PairResponse { paired, plain_cert: hex_field("plaincert")?, challenge_response: hex_field("challengeresponse")?, pairing_secret: hex_field("pairingsecret")?, }) } /// A failed step: why, and the error to return. type StepError = (PairingFailure, Error); /// One pairing attempt with one host. pub struct PairingSession { state: PairingState, unique_id: String, device_name: String, cert_der: Vec, key: zeroize::Zeroizing<[u8; 16]>, server_cert: Option, client_challenge: [u8; CHALLENGE_LEN], host_proof: [u8; HASH_LEN], client_secret: zeroize::Zeroizing<[u8; SECRET_LEN]>, } impl PairingSession { /// Starts pairing: draws the salt, derives the AES key from salt and PIN, and returns step 1. /// /// `unique_id` is this client's id (stable per device), `device_name` is shown on the host. /// /// # Errors /// [`Error::Malformed`] for a bad `unique_id` or `device_name` (empty, too long, control characters). pub fn start( identity: &ClientIdentity, unique_id: &str, device_name: &str, pin: Pin, rng: &mut dyn RandomSource, ) -> Result<(Self, HttpRequest)> { check_unique_id(unique_id)?; if device_name.is_empty() || device_name.len() > MAX_DEVICE_NAME_BYTES || device_name.chars().any(char::is_control) { return Err(malformed("device name")); } let mut salt = [0u8; SALT_LEN]; rng.fill(&mut salt); let key = crypto::derive_key(&salt, &pin)?; let session = Self { state: PairingState::AwaitServerCert, unique_id: unique_id.to_owned(), device_name: device_name.to_owned(), cert_der: identity.cert_der().to_vec(), key: zeroize::Zeroizing::new(key), server_cert: None, client_challenge: [0; CHALLENGE_LEN], host_proof: [0; HASH_LEN], client_secret: zeroize::Zeroizing::new([0; SECRET_LEN]), }; let cert = hex_encode(identity.cert_pem()?.as_bytes()); let salt = hex_encode(&salt); let req = session.request( Scheme::Http, &[("phrase", "getservercert"), ("salt", &salt), ("clientcert", &cert)], Some(STEP1_TIMEOUT), ); Ok((session, req)) } fn request(&self, scheme: Scheme, extra: &[(&str, &str)], timeout: Option) -> HttpRequest { let mut params: Vec<(&str, &str)> = vec![("uniqueid", &self.unique_id), ("devicename", &self.device_name), ("updateState", "1")]; params.extend_from_slice(extra); build(scheme, "/pair", ¶ms, timeout) } fn fail(&mut self, why: PairingFailure, error: Error) -> Result { self.state = PairingState::Failed(why); Err(error) } /// Feeds the answer to the last request: its HTTP status and body. `identity` must be the one passed to /// [`Self::start`] (it is borrowed per call so the session never holds a copy of the private key). Draws /// randomness for steps 2 and 3. /// /// # Errors /// [`Error::PairingRefused`] (the state becomes [`PairingState::Failed`]), parser errors as /// [`parse_pair_response`], [`Error::State`] after `Paired` or `Failed`, [`Error::Malformed`] for a different /// identity than at the start. pub fn handle_response( &mut self, identity: &ClientIdentity, http_status: u16, body: &[u8], rng: &mut dyn RandomSource, ) -> Result { if matches!(self.state, PairingState::Paired | PairingState::Failed(_)) { return Err(Error::State { expected: "a pairing step in progress" }); } if identity.cert_der() != self.cert_der.as_slice() { return Err(malformed("pairing: a different identity than at the start")); } if http_status != 200 { return self.fail(PairingFailure::HostStatus, Error::HostStatus { code: u32::from(http_status) }); } let answer = match parse_pair_response(body) { Ok(a) => a, Err(e @ Error::HostStatus { .. }) => return self.fail(PairingFailure::HostStatus, e), Err(e) => return self.fail(PairingFailure::MalformedAnswer, e), }; if !answer.paired { return self.fail(PairingFailure::HostRefused, Error::PairingRefused); } match self.step(identity, answer, rng) { Ok(step) => Ok(step), Err((why, e)) => self.fail(why, e), } } fn step( &mut self, identity: &ClientIdentity, answer: PairResponse, rng: &mut dyn RandomSource, ) -> core::result::Result { let bad = |e: Error| (PairingFailure::MalformedAnswer, e); match self.state { PairingState::AwaitServerCert => { let pem = answer.plain_cert.ok_or_else(|| bad(malformed("pairing: no plaincert")))?; let cert = ServerCert::from_pem(&pem).map_err(bad)?; self.server_cert = Some(cert); rng.fill(&mut self.client_challenge); let enc = crypto::ecb_encrypt(&self.key, &self.client_challenge).map_err(bad)?; self.state = PairingState::AwaitChallengeResponse; Ok(PairingStep::Send(self.request(Scheme::Http, &[("clientchallenge", &hex_encode(&enc))], None))) } PairingState::AwaitChallengeResponse => { let cr = answer.challenge_response.ok_or_else(|| bad(malformed("pairing: no challengeresponse")))?; let plain = crypto::ecb_decrypt(&self.key, &cr).map_err(bad)?; let (host_proof, server_challenge) = crypto::split_challenge_response(&plain).map_err(bad)?; self.host_proof = host_proof; rng.fill(&mut *self.client_secret); let client_sig = identity.cert_signature().map_err(bad)?; let client_proof = crypto::proof_hash(&server_challenge, &client_sig, &self.client_secret).map_err(bad)?; let enc = crypto::ecb_encrypt(&self.key, &client_proof).map_err(bad)?; self.state = PairingState::AwaitPairingSecret; Ok(PairingStep::Send(self.request(Scheme::Http, &[("serverchallengeresp", &hex_encode(&enc))], None))) } PairingState::AwaitPairingSecret => { let ps = answer.pairing_secret.ok_or_else(|| bad(malformed("pairing: no pairingsecret")))?; let (secret, signature) = crypto::split_pairing_secret(&ps).map_err(bad)?; let cert = self.server_cert.as_ref().ok_or_else(|| bad(malformed("pairing: no host certificate")))?; cert.verify(&secret, signature) .map_err(|_| (PairingFailure::BadHostSignature, Error::PairingRefused))?; let host_sig = cert.signature().map_err(bad)?; let expected = crypto::proof_hash(&self.client_challenge, &host_sig, &secret).map_err(bad)?; if !ct_eq(&expected, &self.host_proof) { return Err((PairingFailure::ProofMismatch, Error::PairingRefused)); } let sig = identity.sign(&*self.client_secret).map_err(bad)?; let value = [&self.client_secret[..], &sig].concat(); self.state = PairingState::AwaitClientSecretAck; Ok(PairingStep::Send(self.request(Scheme::Http, &[("clientpairingsecret", &hex_encode(&value))], None))) } PairingState::AwaitClientSecretAck => { self.state = PairingState::AwaitPairChallenge; Ok(PairingStep::Send(self.request(Scheme::Https, &[("phrase", "pairchallenge")], None))) } PairingState::AwaitPairChallenge => { let server_cert = self.server_cert.clone().ok_or_else(|| bad(malformed("pairing: no host certificate")))?; self.state = PairingState::Paired; Ok(PairingStep::Paired(PairedHost { server_cert })) } PairingState::Paired | PairingState::Failed(_) => { Err((PairingFailure::MalformedAnswer, Error::State { expected: "a pairing step in progress" })) } } } /// Where the handshake is. #[must_use] pub const fn state(&self) -> PairingState { self.state } } impl fmt::Debug for PairingSession { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PairingSession").field("state", &self.state).finish_non_exhaustive() } }