[domistream] Pairing API: PIN handshake state machine, pure crypto steps, client identity, pinned host cert

This commit is contained in:
2026-11-25 11:45:57 +01:00
parent 0188ffba97
commit 736a8f42b0
4 changed files with 433 additions and 0 deletions
+1
View File
@@ -39,6 +39,7 @@ pub mod entropy;
pub mod error;
pub mod http;
pub mod keys;
pub mod pairing;
pub mod time;
pub use entropy::RandomSource;
+71
View File
@@ -0,0 +1,71 @@
//! The pure cryptographic steps of pairing (`docs/PROTOCOL.md` 1.5), public so QA can test them against
//! independent vectors (for example Python `hashlib` + `cryptography` with fixed test keys).
use super::{CHALLENGE_LEN, HASH_LEN, Pin, SALT_LEN, SECRET_LEN};
use crate::Result;
/// AES-128 key used for every encrypted pairing value.
pub type PairingKey = [u8; 16];
/// `K = SHA-256(salt ‖ PIN digits)[0..16]`.
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn derive_key(salt: &[u8; SALT_LEN], pin: &Pin) -> Result<PairingKey> {
let _ = (salt, pin);
Err(crate::Error::Unimplemented)
}
/// AES-128-ECB encryption without padding.
///
/// # Errors
/// [`crate::Error::Malformed`] when `data` is not a whole number of 16-byte blocks. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn ecb_encrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
let _ = (key, data);
Err(crate::Error::Unimplemented)
}
/// AES-128-ECB decryption without padding.
///
/// # Errors
/// As [`ecb_encrypt`].
pub fn ecb_decrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
let _ = (key, data);
Err(crate::Error::Unimplemented)
}
/// `SHA-256(challenge ‖ cert_signature ‖ secret)`: the host's proof `H_s` (with the client challenge, the host
/// certificate's signature and the host secret) and the client's proof `H_c` (with the host challenge, the client
/// certificate's signature and the client secret).
///
/// # Errors
/// [`crate::Error::TooLarge`] for a signature over [`super::MAX_SIGNATURE_BYTES`]. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn proof_hash(
challenge: &[u8; CHALLENGE_LEN],
cert_signature: &[u8],
secret: &[u8; SECRET_LEN],
) -> Result<[u8; HASH_LEN]> {
let _ = (challenge, cert_signature, secret);
Err(crate::Error::Unimplemented)
}
/// Splits a decrypted `challengeresponse` (48 bytes) into the host proof `H_s` and the host challenge `S_c`.
///
/// # Errors
/// [`crate::Error::Malformed`] unless exactly 48 bytes. Phase A: always [`crate::Error::Unimplemented`].
pub fn split_challenge_response(decrypted: &[u8]) -> Result<([u8; HASH_LEN], [u8; CHALLENGE_LEN])> {
let _ = decrypted;
Err(crate::Error::Unimplemented)
}
/// Splits a `pairingsecret` into the host secret (16 bytes) and its signature (the rest).
///
/// # Errors
/// [`crate::Error::Malformed`] when shorter than 17 bytes, [`crate::Error::TooLarge`] when the signature is over
/// [`super::MAX_SIGNATURE_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn split_pairing_secret(pairing_secret: &[u8]) -> Result<([u8; SECRET_LEN], &[u8])> {
let _ = pairing_secret;
Err(crate::Error::Unimplemented)
}
+156
View File
@@ -0,0 +1,156 @@
//! The client's certificate and key, and the host certificate learnt while pairing.
use core::fmt;
use crate::{RandomSource, Result};
/// Maximum size of a certificate in PEM form, in bytes.
pub const MAX_CERT_PEM_BYTES: usize = 16 * 1024;
/// Maximum size of a certificate in DER form, in bytes.
pub const MAX_CERT_DER_BYTES: usize = 12 * 1024;
/// Maximum size of a PKCS#8 private key in DER form, in bytes.
pub const MAX_KEY_DER_BYTES: usize = 8 * 1024;
/// RSA modulus size of keys this client generates.
pub const CLIENT_KEY_BITS: usize = 2048;
/// The client's long-lived identity towards GameStream hosts: a self-signed RSA-2048 / SHA-256 X.509 certificate
/// and its private key. Generated once per device and kept by the platform layer (never in logs; the key belongs
/// in the platform's secret store). `Debug` never prints the key.
#[derive(Clone)]
pub struct ClientIdentity {
cert_der: Vec<u8>,
key_pkcs8_der: Vec<u8>,
}
impl ClientIdentity {
/// Generates a new key and self-signed certificate.
///
/// `common_name` becomes the subject and issuer CN. `not_before_unix` is the validity start in Unix seconds
/// (passed in: no clock reads); validity runs 20 years from it. RSA key generation is slow (hundreds of ms on a
/// TV); call it once per device.
///
/// # Errors
/// [`crate::Error::Malformed`] for an empty or oversized `common_name`. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn generate(rng: &mut dyn RandomSource, common_name: &str, not_before_unix: i64) -> Result<Self> {
let _ = (rng, common_name, not_before_unix);
Err(crate::Error::Unimplemented)
}
/// Loads a stored identity. Checks that the key matches the certificate.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`] / [`MAX_KEY_DER_BYTES`], [`crate::Error::Malformed`]
/// for bad DER or a key that does not match. Phase A: always [`crate::Error::Unimplemented`].
pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result<Self> {
let _ = (cert_der, key_pkcs8_der);
Err(crate::Error::Unimplemented)
}
/// The certificate, DER.
#[must_use]
pub fn cert_der(&self) -> &[u8] {
&self.cert_der
}
/// The private key, PKCS#8 DER, for the platform's secret store and its TLS stack.
#[must_use]
pub fn key_pkcs8_der(&self) -> &[u8] {
&self.key_pkcs8_der
}
/// The certificate as PEM text (what pairing step 1 sends, hex-encoded).
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn cert_pem(&self) -> Result<String> {
Err(crate::Error::Unimplemented)
}
/// The raw `signatureValue` bytes of the certificate (input to the pairing proofs).
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn cert_signature(&self) -> Result<Vec<u8>> {
Err(crate::Error::Unimplemented)
}
/// RSASSA-PKCS1-v1_5 / SHA-256 signature over `data` with the client key.
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
let _ = data;
Err(crate::Error::Unimplemented)
}
}
impl fmt::Debug for ClientIdentity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ClientIdentity")
.field("cert_der_len", &self.cert_der.len())
.field("key", &"<redacted>")
.finish()
}
}
/// The host certificate received as `plaincert` in pairing step 1, kept to pin HTTPS connections.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerCert {
der: Vec<u8>,
}
impl ServerCert {
/// Parses the PEM the host sent (already hex-decoded). Exactly one `CERTIFICATE` block.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_CERT_PEM_BYTES`], [`crate::Error::Malformed`] for anything that is
/// not one well-formed X.509 certificate with an RSA key. Phase A: always [`crate::Error::Unimplemented`].
pub fn from_pem(pem: &[u8]) -> Result<Self> {
let _ = pem;
Err(crate::Error::Unimplemented)
}
/// Loads a stored certificate.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`], [`crate::Error::Malformed`] otherwise. Phase A:
/// always [`crate::Error::Unimplemented`].
pub fn from_der(der: &[u8]) -> Result<Self> {
let _ = der;
Err(crate::Error::Unimplemented)
}
/// The certificate, DER.
#[must_use]
pub fn der(&self) -> &[u8] {
&self.der
}
/// The raw `signatureValue` bytes (input to the pairing proofs).
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn signature(&self) -> Result<Vec<u8>> {
Err(crate::Error::Unimplemented)
}
/// Verifies an RSASSA-PKCS1-v1_5 / SHA-256 `signature` over `data` with the certificate's public key.
///
/// # Errors
/// [`crate::Error::Crypto`] when it does not verify. Phase A: always [`crate::Error::Unimplemented`].
pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
let _ = (data, signature);
Err(crate::Error::Unimplemented)
}
/// TLS pinning: whether the certificate a host presents over HTTPS (DER) is exactly this one, compared in
/// constant time. The platform's TLS verifier calls this and nothing else to accept the host.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn matches(&self, presented_der: &[u8]) -> Result<bool> {
let _ = presented_der;
Err(crate::Error::Unimplemented)
}
}
+205
View File
@@ -0,0 +1,205 @@
//! 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<Self> {
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<Self> {
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(<redacted>)")
}
}
/// 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 (`<root status_code="200"><paired>1</paired>…</root>`), 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<Vec<u8>>,
/// `challengeresponse`: `E_K(H_s ‖ S_c)`, 48 bytes (step 2).
pub challenge_response: Option<Vec<u8>>,
/// `pairingsecret`: `secret_s ‖ signature` (step 3).
pub pairing_secret: Option<Vec<u8>>,
}
/// 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<PairResponse> {
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<PairingStep> {
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()
}
}