//! HTTPS as a GameStream client does it: the probe presents its own client certificate and accepts exactly the host //! certificate it pinned while pairing (`plaincert`), byte for byte (`ServerCert::matches`). Handshake signatures //! are still checked against that certificate's key. use std::sync::Arc; use domistream::pairing::{ClientIdentity, ServerCert}; use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; use rustls::crypto::{WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature}; use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime}; use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme}; /// Accepts exactly the pinned host certificate. #[derive(Debug)] struct PinnedHost { pinned: ServerCert, algs: WebPkiSupportedAlgorithms, } impl ServerCertVerifier for PinnedHost { fn verify_server_cert( &self, end_entity: &CertificateDer<'_>, _intermediates: &[CertificateDer<'_>], _server_name: &ServerName<'_>, _ocsp_response: &[u8], _now: UnixTime, ) -> Result { match self.pinned.matches(end_entity.as_ref()) { Ok(true) => Ok(ServerCertVerified::assertion()), _ => { Err(rustls::Error::General("the host presented another certificate than the one it paired with".into())) } } } fn verify_tls12_signature( &self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct, ) -> Result { verify_tls12_signature(message, cert, dss, &self.algs) } fn verify_tls13_signature( &self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct, ) -> Result { verify_tls13_signature(message, cert, dss, &self.algs) } fn supported_verify_schemes(&self) -> Vec { self.algs.supported_schemes() } } /// A client configuration presenting `identity` and pinning `host`. TLS 1.2 and 1.3 are both offered (U24 is /// whatever the host picks; the log records it). pub fn client_config(identity: &ClientIdentity, host: &ServerCert) -> Result, String> { let provider = Arc::new(rustls::crypto::ring::default_provider()); let algs = provider.signature_verification_algorithms; let cert = CertificateDer::from(identity.cert_der().to_vec()); let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(identity.key_pkcs8_der().to_vec())); let cfg = ClientConfig::builder_with_provider(provider) .with_safe_default_protocol_versions() .map_err(|e| format!("TLS setup failed: {e}"))? .dangerous() .with_custom_certificate_verifier(Arc::new(PinnedHost { pinned: host.clone(), algs })) .with_client_auth_cert(vec![cert], key) // The error text never carries key bytes. .map_err(|e| format!("TLS client certificate refused: {e}"))?; Ok(Arc::new(cfg)) }