//! 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`]. use core::fmt; use crate::http::HttpRequest; use crate::{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; /// A 4-digit GameStream PIN. #[derive(Clone, Copy, PartialEq, Eq)] pub struct Pin([u8; PIN_LEN]); impl Pin { /// Draws a uniformly random PIN (no modulo bias). /// /// # Errors /// Phase A: always [`crate::Error::Unimplemented`]. pub fn generate(rng: &mut dyn RandomSource) -> Result { let _ = rng; Err(crate::Error::Unimplemented) } /// Parses exactly four ASCII digits. /// /// # Errors /// [`crate::Error::Malformed`] for anything else. Phase A: always [`crate::Error::Unimplemented`]. pub fn from_digits(digits: &str) -> Result { let _ = digits; Err(crate::Error::Unimplemented) } /// 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 /// [`crate::Error::TooLarge`] over [`MAX_PAIR_RESPONSE_BYTES`], [`crate::Error::HostStatus`] for a non-200 /// answer, [`crate::Error::Malformed`] for bad hex or a missing `paired`. Phase A: always /// [`crate::Error::Unimplemented`]. pub fn parse_pair_response(body: &[u8]) -> Result { let _ = body; Err(crate::Error::Unimplemented) } /// One pairing attempt with one host. pub struct PairingSession { state: PairingState, } 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 /// [`crate::Error::Malformed`] for a bad `unique_id` or `device_name`. Phase A: always /// [`crate::Error::Unimplemented`]. pub fn start( identity: &ClientIdentity, unique_id: &str, device_name: &str, pin: Pin, rng: &mut dyn RandomSource, ) -> Result<(Self, HttpRequest)> { let _ = (identity, unique_id, device_name, pin, rng); Err(crate::Error::Unimplemented) } /// 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 /// [`crate::Error::PairingRefused`] (the state becomes [`PairingState::Failed`]), parser errors as /// [`parse_pair_response`], [`crate::Error::State`] after `Paired` or `Failed`, [`crate::Error::Malformed`] for /// a different identity than at the start. Phase A: always [`crate::Error::Unimplemented`]. pub fn handle_response( &mut self, identity: &ClientIdentity, http_status: u16, body: &[u8], rng: &mut dyn RandomSource, ) -> Result { let _ = (identity, http_status, body, rng); Err(crate::Error::Unimplemented) } /// 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() } }