Files
DomiStream/crates/domistream/src/pairing/identity.rs
T

327 lines
13 KiB
Rust

//! The client's certificate and key, and the host certificate learnt while pairing.
use core::fmt;
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;
/// 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;
/// 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
/// in the platform's secret store). `Debug` never prints the key.
#[derive(Clone)]
pub struct ClientIdentity {
cert_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.
///
/// `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
/// [`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> {
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(&[&not_before, &not_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
/// [`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> {
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.
#[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
/// None today.
pub fn cert_pem(&self) -> Result<String> {
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
/// [`Error::Malformed`] if the stored certificate no longer parses (it was checked when loaded).
pub fn cert_signature(&self) -> Result<Vec<u8>> {
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
/// [`Error::Crypto`] if signing fails.
pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
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())
}
}
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 and nothing but
/// whitespace around it.
///
/// # Errors
/// [`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> {
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
/// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`], [`Error::Malformed`] otherwise.
pub fn from_der(der: &[u8]) -> Result<Self> {
cap("host certificate", MAX_CERT_DER_BYTES, der.len())?;
parse_rsa_cert(der)?;
Ok(Self { der: der.to_vec() })
}
/// The certificate, DER.
#[must_use]
pub fn der(&self) -> &[u8] {
&self.der
}
/// The raw `signatureValue` bytes (input to the pairing proofs).
///
/// # Errors
/// [`Error::Malformed`] if the stored certificate no longer parses.
pub fn signature(&self) -> Result<Vec<u8>> {
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
/// [`Error::Crypto`] when it does not verify.
pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
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
/// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`].
pub fn matches(&self, presented_der: &[u8]) -> Result<bool> {
cap("presented certificate", MAX_CERT_DER_BYTES, presented_der.len())?;
Ok(ct_eq(&self.der, presented_der))
}
}