[domistream] Implementation: HTTP, pairing, RTSP/SDP, ENet, control, input, RTP, FEC, video and audio receivers
Per PROTOCOL.md and the Wolf docs; interop with a real host is unverified. Strict, capped parsers throughout, shared helpers in util.rs. Where PROTOCOL.md says UNKNOWN the Wolf-documented behaviour is used. The audio receiver waits for the jitter budget before rebuilding a missing packet, so a late packet beats a rebuilt one.
This commit is contained in:
@@ -1,8 +1,13 @@
|
||||
//! 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 aes::Aes128;
|
||||
use aes::cipher::{BlockCipherDecrypt, BlockCipherEncrypt, KeyInit};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use super::{CHALLENGE_LEN, HASH_LEN, MAX_SIGNATURE_BYTES, Pin, SALT_LEN, SECRET_LEN};
|
||||
use crate::Result;
|
||||
use crate::util::{cap, malformed};
|
||||
|
||||
/// AES-128 key used for every encrypted pairing value.
|
||||
pub type PairingKey = [u8; 16];
|
||||
@@ -10,20 +15,40 @@ pub type PairingKey = [u8; 16];
|
||||
/// `K = SHA-256(salt ‖ PIN digits)[0..16]`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// None today; the `Result` keeps the signature uniform with the other steps.
|
||||
pub fn derive_key(salt: &[u8; SALT_LEN], pin: &Pin) -> Result<PairingKey> {
|
||||
let _ = (salt, pin);
|
||||
Err(crate::Error::Unimplemented)
|
||||
let mut h = Sha256::new();
|
||||
h.update(salt);
|
||||
h.update(pin.as_bytes());
|
||||
let digest = h.finalize();
|
||||
let mut key = [0u8; 16];
|
||||
key.copy_from_slice(digest.get(..16).ok_or(malformed("sha-256 output"))?);
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
fn ecb(key: &PairingKey, data: &[u8], encrypt: bool) -> Result<Vec<u8>> {
|
||||
if data.is_empty() || !data.len().is_multiple_of(16) {
|
||||
return Err(malformed("aes-ecb input is not whole blocks"));
|
||||
}
|
||||
let cipher = Aes128::new(key.into());
|
||||
let mut out = data.to_vec();
|
||||
for chunk in out.chunks_exact_mut(16) {
|
||||
let block: &mut aes::Block = chunk.try_into().map_err(|_| malformed("aes block"))?;
|
||||
if encrypt {
|
||||
cipher.encrypt_block(block);
|
||||
} else {
|
||||
cipher.decrypt_block(block);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 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`].
|
||||
/// [`crate::Error::Malformed`] when `data` is not a whole, non-zero number of 16-byte blocks.
|
||||
pub fn ecb_encrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
||||
let _ = (key, data);
|
||||
Err(crate::Error::Unimplemented)
|
||||
ecb(key, data, true)
|
||||
}
|
||||
|
||||
/// AES-128-ECB decryption without padding.
|
||||
@@ -31,8 +56,7 @@ pub fn ecb_encrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
||||
/// # Errors
|
||||
/// As [`ecb_encrypt`].
|
||||
pub fn ecb_decrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
||||
let _ = (key, data);
|
||||
Err(crate::Error::Unimplemented)
|
||||
ecb(key, data, false)
|
||||
}
|
||||
|
||||
/// `SHA-256(challenge ‖ cert_signature ‖ secret)`: the host's proof `H_s` (with the client challenge, the host
|
||||
@@ -40,32 +64,46 @@ pub fn ecb_decrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
||||
/// 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`].
|
||||
/// [`crate::Error::TooLarge`] for a signature over [`MAX_SIGNATURE_BYTES`].
|
||||
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)
|
||||
cap("certificate signature", MAX_SIGNATURE_BYTES, cert_signature.len())?;
|
||||
let mut h = Sha256::new();
|
||||
h.update(challenge);
|
||||
h.update(cert_signature);
|
||||
h.update(secret);
|
||||
let mut out = [0u8; HASH_LEN];
|
||||
out.copy_from_slice(&h.finalize());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 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`].
|
||||
/// [`crate::Error::Malformed`] unless exactly 48 bytes.
|
||||
pub fn split_challenge_response(decrypted: &[u8]) -> Result<([u8; HASH_LEN], [u8; CHALLENGE_LEN])> {
|
||||
let _ = decrypted;
|
||||
Err(crate::Error::Unimplemented)
|
||||
if decrypted.len() != HASH_LEN + CHALLENGE_LEN {
|
||||
return Err(malformed("challengeresponse is not 48 bytes"));
|
||||
}
|
||||
let hash = crate::util::array::<HASH_LEN>("challengeresponse", decrypted, 0)?;
|
||||
let challenge = crate::util::array::<CHALLENGE_LEN>("challengeresponse", decrypted, HASH_LEN)?;
|
||||
Ok((hash, challenge))
|
||||
}
|
||||
|
||||
/// 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`].
|
||||
/// [`MAX_SIGNATURE_BYTES`].
|
||||
pub fn split_pairing_secret(pairing_secret: &[u8]) -> Result<([u8; SECRET_LEN], &[u8])> {
|
||||
let _ = pairing_secret;
|
||||
Err(crate::Error::Unimplemented)
|
||||
if pairing_secret.len() <= SECRET_LEN {
|
||||
return Err(malformed("pairingsecret too short"));
|
||||
}
|
||||
let signature = pairing_secret.get(SECRET_LEN..).unwrap_or(&[]);
|
||||
cap("pairingsecret signature", MAX_SIGNATURE_BYTES, signature.len())?;
|
||||
let secret = crate::util::array::<SECRET_LEN>("pairingsecret", pairing_secret, 0)?;
|
||||
Ok((secret, signature))
|
||||
}
|
||||
|
||||
@@ -2,7 +2,16 @@
|
||||
|
||||
use core::fmt;
|
||||
|
||||
use crate::{RandomSource, Result};
|
||||
use rsa::pkcs1v15::{Signature, SigningKey, VerifyingKey};
|
||||
use rsa::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey};
|
||||
use rsa::signature::{SignatureEncoding, Signer, Verifier};
|
||||
use rsa::{PrivateKey, PublicKey};
|
||||
use sha2::Sha256;
|
||||
use x509_cert::Certificate;
|
||||
use x509_cert::der::{Decode, Encode};
|
||||
|
||||
use crate::util::{base64_decode, base64_pem_lines, cap, ct_eq, malformed};
|
||||
use crate::{Error, RandomSource, Result};
|
||||
|
||||
/// Maximum size of a certificate in PEM form, in bytes.
|
||||
pub const MAX_CERT_PEM_BYTES: usize = 16 * 1024;
|
||||
@@ -12,6 +21,13 @@ pub const MAX_CERT_DER_BYTES: usize = 12 * 1024;
|
||||
pub const MAX_KEY_DER_BYTES: usize = 8 * 1024;
|
||||
/// RSA modulus size of keys this client generates.
|
||||
pub const CLIENT_KEY_BITS: usize = 2048;
|
||||
/// Maximum length of a generated certificate's common name, in bytes.
|
||||
pub const MAX_COMMON_NAME_BYTES: usize = 64;
|
||||
/// Validity of a generated certificate: 20 years of 365.25 days.
|
||||
pub const CLIENT_CERT_VALIDITY_SECS: i64 = 20 * 31_557_600;
|
||||
|
||||
/// OID 1.2.840.113549.1.1.1, rsaEncryption.
|
||||
const RSA_ENCRYPTION: &str = "1.2.840.113549.1.1.1";
|
||||
|
||||
/// 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
|
||||
@@ -19,9 +35,116 @@ pub const CLIENT_KEY_BITS: usize = 2048;
|
||||
#[derive(Clone)]
|
||||
pub struct ClientIdentity {
|
||||
cert_der: Vec<u8>,
|
||||
key_pkcs8_der: Vec<u8>,
|
||||
key_pkcs8_der: zeroize::Zeroizing<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// A parsed certificate with an RSA key.
|
||||
fn parse_rsa_cert(der: &[u8]) -> Result<(Certificate, PublicKey)> {
|
||||
let cert = Certificate::from_der(der).map_err(|_| malformed("x509 certificate"))?;
|
||||
let spki = cert.tbs_certificate().subject_public_key_info();
|
||||
if spki.algorithm.oid.to_string() != RSA_ENCRYPTION {
|
||||
return Err(malformed("certificate key is not RSA"));
|
||||
}
|
||||
let spki_der = spki.to_der().map_err(|_| malformed("certificate key"))?;
|
||||
let key = PublicKey::from_public_key_der(&spki_der).map_err(|_| malformed("certificate RSA key"))?;
|
||||
Ok((cert, key))
|
||||
}
|
||||
|
||||
fn signature_bytes(cert: &Certificate) -> Vec<u8> {
|
||||
cert.signature().raw_bytes().to_vec()
|
||||
}
|
||||
|
||||
/// Adapts our [`RandomSource`] to the RustCrypto RNG traits (infallible, cryptographic by contract).
|
||||
struct Rng<'a>(&'a mut dyn RandomSource);
|
||||
|
||||
impl rand_core::TryRng for Rng<'_> {
|
||||
type Error = core::convert::Infallible;
|
||||
|
||||
fn try_next_u32(&mut self) -> core::result::Result<u32, Self::Error> {
|
||||
let mut b = [0u8; 4];
|
||||
self.0.fill(&mut b);
|
||||
Ok(u32::from_le_bytes(b))
|
||||
}
|
||||
|
||||
fn try_next_u64(&mut self) -> core::result::Result<u64, Self::Error> {
|
||||
let mut b = [0u8; 8];
|
||||
self.0.fill(&mut b);
|
||||
Ok(u64::from_le_bytes(b))
|
||||
}
|
||||
|
||||
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> core::result::Result<(), Self::Error> {
|
||||
self.0.fill(dst);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl rand_core::TryCryptoRng for Rng<'_> {}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ DER writer
|
||||
|
||||
/// One DER TLV.
|
||||
fn tlv(tag: u8, content: &[u8]) -> Vec<u8> {
|
||||
let mut out = vec![tag];
|
||||
let len = content.len();
|
||||
if len < 0x80 {
|
||||
out.push(len as u8);
|
||||
} else {
|
||||
let bytes = len.to_be_bytes();
|
||||
let skip = bytes.iter().take_while(|b| **b == 0).count();
|
||||
let used = bytes.get(skip..).unwrap_or(&[]);
|
||||
out.push(0x80 | used.len() as u8);
|
||||
out.extend_from_slice(used);
|
||||
}
|
||||
out.extend_from_slice(content);
|
||||
out
|
||||
}
|
||||
|
||||
fn seq(parts: &[&[u8]]) -> Vec<u8> {
|
||||
tlv(0x30, &parts.concat())
|
||||
}
|
||||
|
||||
/// Civil date from days since 1970-01-01 (proleptic Gregorian).
|
||||
fn civil(days: i64) -> (i64, u32, u32) {
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z.rem_euclid(146_097);
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
||||
let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
||||
let year = yoe + era * 400 + i64::from(month <= 2);
|
||||
(year, month, day)
|
||||
}
|
||||
|
||||
/// RFC 5280 time: UTCTime for 1950..=2049, GeneralizedTime otherwise.
|
||||
fn x509_time(unix: i64) -> Result<Vec<u8>> {
|
||||
if unix < 0 {
|
||||
return Err(malformed("certificate time before 1970"));
|
||||
}
|
||||
let (year, month, day) = civil(unix.div_euclid(86_400));
|
||||
if year > 9999 {
|
||||
return Err(malformed("certificate time after 9999"));
|
||||
}
|
||||
let secs = unix.rem_euclid(86_400);
|
||||
let (h, m, s) = (secs / 3600, secs / 60 % 60, secs % 60);
|
||||
if year < 2050 {
|
||||
Ok(tlv(0x17, format!("{:02}{month:02}{day:02}{h:02}{m:02}{s:02}Z", year % 100).as_bytes()))
|
||||
} else {
|
||||
Ok(tlv(0x18, format!("{year:04}{month:02}{day:02}{h:02}{m:02}{s:02}Z").as_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
/// `SEQ { SET { SEQ { id-at-commonName, UTF8String } } }`.
|
||||
fn name(common_name: &str) -> Vec<u8> {
|
||||
let atv = seq(&[&[0x06, 0x03, 0x55, 0x04, 0x03], &tlv(0x0C, common_name.as_bytes())]);
|
||||
seq(&[&tlv(0x31, &atv)])
|
||||
}
|
||||
|
||||
/// sha256WithRSAEncryption, NULL parameters.
|
||||
const SHA256_WITH_RSA: [u8; 15] =
|
||||
[0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00];
|
||||
|
||||
impl ClientIdentity {
|
||||
/// Generates a new key and self-signed certificate.
|
||||
///
|
||||
@@ -30,21 +153,56 @@ impl ClientIdentity {
|
||||
/// TV); call it once per device.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::Malformed`] for an empty or oversized `common_name`. Phase A: always
|
||||
/// [`crate::Error::Unimplemented`].
|
||||
/// [`Error::Malformed`] for an empty, oversized or control-character `common_name`, or a time before 1970;
|
||||
/// [`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(crate::Error::Unimplemented)
|
||||
if common_name.is_empty()
|
||||
|| common_name.len() > MAX_COMMON_NAME_BYTES
|
||||
|| common_name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(malformed("certificate common name"));
|
||||
}
|
||||
let not_before = x509_time(not_before_unix)?;
|
||||
let not_after = x509_time(not_before_unix.saturating_add(CLIENT_CERT_VALIDITY_SECS))?;
|
||||
let mut serial = [0u8; 16];
|
||||
rng.fill(&mut serial);
|
||||
if let Some(first) = serial.first_mut() {
|
||||
// Positive and with a non-zero top byte, so the INTEGER is 16 bytes, minimal.
|
||||
*first = (*first & 0x7F) | 0x40;
|
||||
}
|
||||
let key = PrivateKey::new(&mut Rng(rng), CLIENT_KEY_BITS).map_err(|_| Error::Crypto)?;
|
||||
let spki = key.to_public_key().to_public_key_der().map_err(|_| Error::Crypto)?;
|
||||
let subject = name(common_name);
|
||||
let tbs = seq(&[
|
||||
&[0xA0, 0x03, 0x02, 0x01, 0x02],
|
||||
&tlv(0x02, &serial),
|
||||
&SHA256_WITH_RSA,
|
||||
&subject,
|
||||
&seq(&[¬_before, ¬_after]),
|
||||
&subject,
|
||||
spki.as_bytes(),
|
||||
]);
|
||||
let signature = SigningKey::<Sha256>::new(key.clone()).try_sign(&tbs).map_err(|_| Error::Crypto)?.to_vec();
|
||||
let bits = [&[0u8][..], &signature].concat();
|
||||
let cert = seq(&[&tbs, &SHA256_WITH_RSA, &tlv(0x03, &bits)]);
|
||||
let pkcs8 = key.to_pkcs8_der().map_err(|_| Error::Crypto)?;
|
||||
Self::from_der(&cert, pkcs8.as_bytes())
|
||||
}
|
||||
|
||||
/// 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`].
|
||||
/// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`] / [`MAX_KEY_DER_BYTES`], [`Error::Malformed`] for bad DER, a
|
||||
/// certificate without an RSA key, or a key that does not match.
|
||||
pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result<Self> {
|
||||
let _ = (cert_der, key_pkcs8_der);
|
||||
Err(crate::Error::Unimplemented)
|
||||
cap("client certificate", MAX_CERT_DER_BYTES, cert_der.len())?;
|
||||
cap("client key", MAX_KEY_DER_BYTES, key_pkcs8_der.len())?;
|
||||
let (_, public) = parse_rsa_cert(cert_der)?;
|
||||
let key = PrivateKey::from_pkcs8_der(key_pkcs8_der).map_err(|_| malformed("client key"))?;
|
||||
if key.to_public_key() != public {
|
||||
return Err(malformed("client key does not match its certificate"));
|
||||
}
|
||||
Ok(Self { cert_der: cert_der.to_vec(), key_pkcs8_der: zeroize::Zeroizing::new(key_pkcs8_der.to_vec()) })
|
||||
}
|
||||
|
||||
/// The certificate, DER.
|
||||
@@ -62,26 +220,27 @@ impl ClientIdentity {
|
||||
/// The certificate as PEM text (what pairing step 1 sends, hex-encoded).
|
||||
///
|
||||
/// # Errors
|
||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// None today.
|
||||
pub fn cert_pem(&self) -> Result<String> {
|
||||
Err(crate::Error::Unimplemented)
|
||||
Ok(format!("-----BEGIN CERTIFICATE-----\n{}-----END CERTIFICATE-----\n", base64_pem_lines(&self.cert_der)))
|
||||
}
|
||||
|
||||
/// The raw `signatureValue` bytes of the certificate (input to the pairing proofs).
|
||||
///
|
||||
/// # Errors
|
||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// [`Error::Malformed`] if the stored certificate no longer parses (it was checked when loaded).
|
||||
pub fn cert_signature(&self) -> Result<Vec<u8>> {
|
||||
Err(crate::Error::Unimplemented)
|
||||
parse_rsa_cert(&self.cert_der).map(|(c, _)| signature_bytes(&c))
|
||||
}
|
||||
|
||||
/// RSASSA-PKCS1-v1_5 / SHA-256 signature over `data` with the client key.
|
||||
///
|
||||
/// # Errors
|
||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// [`Error::Crypto`] if signing fails.
|
||||
pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
|
||||
let _ = data;
|
||||
Err(crate::Error::Unimplemented)
|
||||
let key = PrivateKey::from_pkcs8_der(&self.key_pkcs8_der).map_err(|_| Error::Crypto)?;
|
||||
let sig = SigningKey::<Sha256>::new(key).try_sign(data).map_err(|_| Error::Crypto)?;
|
||||
Ok(sig.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,24 +260,36 @@ pub struct ServerCert {
|
||||
}
|
||||
|
||||
impl ServerCert {
|
||||
/// Parses the PEM the host sent (already hex-decoded). Exactly one `CERTIFICATE` block.
|
||||
/// Parses the PEM the host sent (already hex-decoded): exactly one `CERTIFICATE` block and nothing but
|
||||
/// whitespace around it.
|
||||
///
|
||||
/// # 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`].
|
||||
/// [`Error::TooLarge`] over [`MAX_CERT_PEM_BYTES`], [`Error::Malformed`] for anything that is not one
|
||||
/// well-formed X.509 certificate with an RSA key.
|
||||
pub fn from_pem(pem: &[u8]) -> Result<Self> {
|
||||
let _ = pem;
|
||||
Err(crate::Error::Unimplemented)
|
||||
const BEGIN: &[u8] = b"-----BEGIN CERTIFICATE-----";
|
||||
const END: &[u8] = b"-----END CERTIFICATE-----";
|
||||
cap("host certificate PEM", MAX_CERT_PEM_BYTES, pem.len())?;
|
||||
let trimmed = pem.trim_ascii();
|
||||
let body = trimmed
|
||||
.strip_prefix(BEGIN)
|
||||
.and_then(|b| b.strip_suffix(END))
|
||||
.ok_or(malformed("host certificate PEM"))?;
|
||||
if body.windows(5).any(|w| w == b"-----") {
|
||||
return Err(malformed("host certificate PEM holds more than one block"));
|
||||
}
|
||||
let der = base64_decode("host certificate PEM", body)?;
|
||||
Self::from_der(&der)
|
||||
}
|
||||
|
||||
/// Loads a stored certificate.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`], [`crate::Error::Malformed`] otherwise. Phase A:
|
||||
/// always [`crate::Error::Unimplemented`].
|
||||
/// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`], [`Error::Malformed`] otherwise.
|
||||
pub fn from_der(der: &[u8]) -> Result<Self> {
|
||||
let _ = der;
|
||||
Err(crate::Error::Unimplemented)
|
||||
cap("host certificate", MAX_CERT_DER_BYTES, der.len())?;
|
||||
parse_rsa_cert(der)?;
|
||||
Ok(Self { der: der.to_vec() })
|
||||
}
|
||||
|
||||
/// The certificate, DER.
|
||||
@@ -130,27 +301,28 @@ impl ServerCert {
|
||||
/// The raw `signatureValue` bytes (input to the pairing proofs).
|
||||
///
|
||||
/// # Errors
|
||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// [`Error::Malformed`] if the stored certificate no longer parses.
|
||||
pub fn signature(&self) -> Result<Vec<u8>> {
|
||||
Err(crate::Error::Unimplemented)
|
||||
parse_rsa_cert(&self.der).map(|(c, _)| signature_bytes(&c))
|
||||
}
|
||||
|
||||
/// 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`].
|
||||
/// [`Error::Crypto`] when it does not verify.
|
||||
pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
|
||||
let _ = (data, signature);
|
||||
Err(crate::Error::Unimplemented)
|
||||
let (_, key) = parse_rsa_cert(&self.der)?;
|
||||
let sig = Signature::try_from(signature).map_err(|_| Error::Crypto)?;
|
||||
VerifyingKey::<Sha256>::new(key).verify(data, &sig).map_err(|_| Error::Crypto)
|
||||
}
|
||||
|
||||
/// 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`].
|
||||
/// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`].
|
||||
pub fn matches(&self, presented_der: &[u8]) -> Result<bool> {
|
||||
let _ = presented_der;
|
||||
Err(crate::Error::Unimplemented)
|
||||
cap("presented certificate", MAX_CERT_DER_BYTES, presented_der.len())?;
|
||||
Ok(ct_eq(&self.der, presented_der))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,12 +11,14 @@
|
||||
//! ```
|
||||
//!
|
||||
//! Each [`PairingSession::handle_response`] consumes one HTTP answer body and returns the next request to send,
|
||||
//! or the finished [`PairedHost`].
|
||||
//! 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;
|
||||
use crate::{RandomSource, Result};
|
||||
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;
|
||||
@@ -37,28 +39,47 @@ pub const PIN_LEN: usize = 4;
|
||||
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 (no modulo bias).
|
||||
/// Draws a uniformly random PIN (rejection sampling, no modulo bias).
|
||||
///
|
||||
/// # Errors
|
||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// None today.
|
||||
pub fn generate(rng: &mut dyn RandomSource) -> Result<Self> {
|
||||
let _ = rng;
|
||||
Err(crate::Error::Unimplemented)
|
||||
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
|
||||
/// [`crate::Error::Malformed`] for anything else. Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// [`Error::Malformed`] for anything else.
|
||||
pub fn from_digits(digits: &str) -> Result<Self> {
|
||||
let _ = digits;
|
||||
Err(crate::Error::Unimplemented)
|
||||
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.
|
||||
@@ -140,17 +161,41 @@ pub struct PairResponse {
|
||||
/// 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`].
|
||||
/// [`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<PairResponse> {
|
||||
let _ = body;
|
||||
Err(crate::Error::Unimplemented)
|
||||
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<Option<Vec<u8>>> {
|
||||
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<u8>,
|
||||
key: zeroize::Zeroizing<[u8; 16]>,
|
||||
server_cert: Option<ServerCert>,
|
||||
client_challenge: [u8; CHALLENGE_LEN],
|
||||
host_proof: [u8; HASH_LEN],
|
||||
client_secret: zeroize::Zeroizing<[u8; SECRET_LEN]>,
|
||||
}
|
||||
|
||||
impl PairingSession {
|
||||
@@ -159,8 +204,7 @@ impl PairingSession {
|
||||
/// `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`].
|
||||
/// [`Error::Malformed`] for a bad `unique_id` or `device_name` (empty, too long, control characters).
|
||||
pub fn start(
|
||||
identity: &ClientIdentity,
|
||||
unique_id: &str,
|
||||
@@ -168,8 +212,47 @@ impl PairingSession {
|
||||
pin: Pin,
|
||||
rng: &mut dyn RandomSource,
|
||||
) -> Result<(Self, HttpRequest)> {
|
||||
let _ = (identity, unique_id, device_name, pin, rng);
|
||||
Err(crate::Error::Unimplemented)
|
||||
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<core::time::Duration>) -> 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<PairingStep> {
|
||||
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
|
||||
@@ -177,9 +260,9 @@ impl PairingSession {
|
||||
/// 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`].
|
||||
/// [`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,
|
||||
@@ -187,8 +270,89 @@ impl PairingSession {
|
||||
body: &[u8],
|
||||
rng: &mut dyn RandomSource,
|
||||
) -> Result<PairingStep> {
|
||||
let _ = (identity, http_status, body, rng);
|
||||
Err(crate::Error::Unimplemented)
|
||||
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<PairingStep, StepError> {
|
||||
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.
|
||||
|
||||
Reference in New Issue
Block a user