//! TLS termination on the HTTPS port (LAB_CAPTURE.md section 4). //! //! Towards Moonlight the relay presents Sunshine's own lab certificate, the one Moonlight pinned while pairing, and //! asks for (but accepts any) client certificate. Towards Sunshine it presents Moonlight's own lab client //! certificate and accepts only Sunshine's lab certificate. Both sides see the certificates they expect; the relay //! records the plaintext in between. All key material is lab-only and is never written to the record file. use std::io::{self, Read, Write}; use std::net::{TcpListener, TcpStream}; use std::path::Path; use std::sync::Arc; use std::thread; use std::time::{Duration, Instant}; use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; use rustls::crypto::{CryptoProvider, WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature}; use rustls::pki_types::pem::PemObject; use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime}; use rustls::server::danger::{ClientCertVerified, ClientCertVerifier}; use rustls::{ClientConfig, ClientConnection, Connection, DigitallySignedStruct, DistinguishedName, ServerConfig}; use rustls::{ServerConnection, SignatureScheme}; use crate::config::{Config, PortSpec, TlsFiles}; use crate::record::{Direction, Kind, Protocol}; use crate::recorder::Recorder; use crate::rewrite::Rewriter; use crate::tcp::{self, CONNECT_TIMEOUT}; /// Read timeout while pumping plaintext between the two TLS sessions. const POLL: Duration = Duration::from_millis(20); /// Accepts connections on the HTTPS port forever. /// /// # Errors /// Binding fails. pub fn serve(config: Arc, spec: PortSpec, rec: Arc) -> io::Result<()> { let listener = TcpListener::bind(config.listen_addr(&spec))?; for client in listener.incoming() { let client = match client { Ok(c) => c, Err(e) => { rec.note(Protocol::HttpsPlain, 0, &format!("accept failed: {e}")); continue; } }; let (config, rec) = (Arc::clone(&config), Arc::clone(&rec)); thread::spawn(move || { let conn = rec.new_connection(); if let Err(e) = relay(client, &config, spec, &rec, conn) { rec.note(Protocol::HttpsPlain, conn, &format!("connection ended with error: {e}")); } rec.log(Kind::Close, Protocol::HttpsPlain, Direction::None, conn, &[]); }); } Ok(()) } /// The lab TLS material, loaded per connection (Moonlight's key may appear only after pairing step 1). struct Material { host_certs: Vec>, host_key: PrivateKeyDer<'static>, client_certs: Vec>, client_key: PrivateKeyDer<'static>, } fn load(files: &TlsFiles) -> io::Result { fn certs(path: &Path) -> io::Result>> { let certs = CertificateDer::pem_file_iter(path) .map_err(|e| io::Error::other(format!("{}: {e:?}", path.display())))? .collect::, _>>() .map_err(|e| io::Error::other(format!("{}: {e:?}", path.display())))?; if certs.is_empty() { return Err(io::Error::other(format!("{}: no certificate", path.display()))); } Ok(certs) } fn key(path: &Path) -> io::Result> { // The error text names the file only; it never echoes key bytes. PrivateKeyDer::from_pem_file(path).map_err(|_| io::Error::other(format!("{}: no usable key", path.display()))) } Ok(Material { host_certs: certs(&files.host_cert)?, host_key: key(&files.host_key)?, client_certs: certs(&files.client_cert)?, client_key: key(&files.client_key)?, }) } /// Waits up to `wait` for all four files to load. fn load_waiting(files: &TlsFiles, wait: Duration) -> io::Result { let deadline = Instant::now() + wait; loop { match load(files) { Ok(m) => return Ok(m), Err(e) if Instant::now() >= deadline => return Err(e), Err(_) => thread::sleep(Duration::from_millis(200)), } } } fn sha256_hex(bytes: &[u8]) -> String { ring::digest::digest(&ring::digest::SHA256, bytes).as_ref().iter().map(|b| format!("{b:02x}")).collect() } fn relay(client: TcpStream, config: &Config, spec: PortSpec, rec: &Recorder, conn: u32) -> io::Result<()> { let upstream_addr = config.upstream_addr(&spec); let peer = client.peer_addr()?; rec.log( Kind::Open, Protocol::HttpsPlain, Direction::None, conn, format!("{peer} -> {upstream_addr} (TLS terminated)").as_bytes(), ); let Some(files) = &config.tls else { return Err(io::Error::other("TLS files not configured")); }; let material = match load_waiting(files, config.wait_for_keys) { Ok(m) => m, Err(e) => { // No keys: carry the raw TLS bytes, so the session still works and is still recorded. rec.note(Protocol::HttpsTls, conn, &format!("lab keys not available ({e}); passing TLS through")); let upstream = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?; return tcp::pump_pair(client, upstream, Protocol::HttpsTls, rec, conn, Vec::new()); } }; let provider = Arc::new(rustls::crypto::ring::default_provider()); let algs = provider.signature_verification_algorithms; let server_config = ServerConfig::builder_with_provider(Arc::clone(&provider)) .with_safe_default_protocol_versions() .map_err(io::Error::other)? .with_client_cert_verifier(Arc::new(AnyClientCert { algs })) .with_single_cert(material.host_certs.clone(), material.host_key) .map_err(io::Error::other)?; let pinned = material.host_certs[0].as_ref().to_vec(); let client_config = client_config(&provider, pinned, material.client_certs.clone(), material.client_key)?; // Moonlight side first: it has already sent its ClientHello. let mut moonlight = client; let mut down = Connection::Server(ServerConnection::new(Arc::new(server_config)).map_err(io::Error::other)?); while down.is_handshaking() { down.complete_io(&mut moonlight)?; } let presented = down.peer_certificates().and_then(|c| c.first()).map(|c| sha256_hex(c.as_ref())); let expected = sha256_hex(material.client_certs[0].as_ref()); rec.note( Protocol::HttpsPlain, conn, &format!( "client side: {:?}, {:?}, client certificate sha256 {} ({})", down.protocol_version(), down.negotiated_cipher_suite().map(|s| s.suite()), presented.as_deref().unwrap_or("none"), if presented.as_deref() == Some(expected.as_str()) { "matches the lab client certificate" } else { "differs from the lab client certificate" }, ), ); let mut sunshine = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?; let name = ServerName::from(upstream_addr.ip()); let mut up = Connection::Client(ClientConnection::new(Arc::new(client_config), name).map_err(io::Error::other)?); while up.is_handshaking() { up.complete_io(&mut sunshine)?; } rec.note( Protocol::HttpsPlain, conn, &format!("host side: {:?}, {:?}", up.protocol_version(), up.negotiated_cipher_suite().map(|s| s.suite())), ); for s in [&moonlight, &sunshine] { s.set_read_timeout(Some(POLL))?; let _ = s.set_nodelay(true); } pump(&mut down, &mut moonlight, &mut up, &mut sunshine, rec, conn, Rewriter::new(config.rewrites.clone())) } fn client_config( provider: &Arc, pinned: Vec, certs: Vec>, key: PrivateKeyDer<'static>, ) -> io::Result { let algs = provider.signature_verification_algorithms; ClientConfig::builder_with_provider(Arc::clone(provider)) .with_safe_default_protocol_versions() .map_err(io::Error::other)? .dangerous() .with_custom_certificate_verifier(Arc::new(PinnedHost { pinned, algs })) .with_client_auth_cert(certs, key) .map_err(io::Error::other) } /// Moves plaintext both ways until both sides are done. fn pump( down: &mut Connection, moonlight: &mut TcpStream, up: &mut Connection, sunshine: &mut TcpStream, rec: &Recorder, conn: u32, mut rewriter: Rewriter, ) -> io::Result<()> { let (mut down_open, mut up_open) = (true, true); while down_open || up_open { if down_open { let (data, eof) = pull(down, moonlight)?; if !data.is_empty() { rec.log(Kind::Data, Protocol::HttpsPlain, Direction::ClientToHost, conn, &data); if up_open { push(up, sunshine, &data)?; } } if eof { down_open = false; if up_open { up.send_close_notify(); flush(up, sunshine)?; } } } if up_open { let (data, eof) = pull(up, sunshine)?; if data.is_empty() { let held = rewriter.flush(); if !held.is_empty() && down_open { push(down, moonlight, &held)?; } } else { rec.log(Kind::Data, Protocol::HttpsPlain, Direction::HostToClient, conn, &data); let (out, count) = rewriter.push(&data); if count > 0 { rec.note(Protocol::HttpsPlain, conn, &format!("rewrote {count} occurrence(s) in the bytes above")); } if down_open { push(down, moonlight, &out)?; } } if eof { up_open = false; if down_open { let held = rewriter.flush(); push(down, moonlight, &held)?; down.send_close_notify(); flush(down, moonlight)?; } } } } Ok(()) } /// Reads what TLS bytes are there (or waits [`POLL`]) and returns the new plaintext and whether the peer is done. fn pull(conn: &mut Connection, sock: &mut TcpStream) -> io::Result<(Vec, bool)> { let mut eof = false; match conn.read_tls(sock) { Ok(0) => eof = true, Ok(_) => { conn.process_new_packets().map_err(io::Error::other)?; } Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {} Err(e) => return Err(e), } let mut data = Vec::new(); let mut buf = [0u8; 16 * 1024]; loop { match conn.reader().read(&mut buf) { Ok(0) => { eof = true; break; } Ok(n) => data.extend_from_slice(&buf[..n]), Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => { eof = true; break; } Err(e) => return Err(e), } } flush(conn, sock)?; Ok((data, eof)) } fn push(conn: &mut Connection, sock: &mut TcpStream, data: &[u8]) -> io::Result<()> { conn.writer().write_all(data)?; flush(conn, sock) } fn flush(conn: &mut Connection, sock: &mut TcpStream) -> io::Result<()> { while conn.wants_write() { conn.write_tls(sock)?; } Ok(()) } /// Accepts any client certificate (it is recorded by fingerprint, and Sunshine checks the real one). #[derive(Debug)] struct AnyClientCert { algs: WebPkiSupportedAlgorithms, } impl ClientCertVerifier for AnyClientCert { fn offer_client_auth(&self) -> bool { true } fn client_auth_mandatory(&self) -> bool { false } fn root_hint_subjects(&self) -> &[DistinguishedName] { &[] } fn verify_client_cert( &self, _end_entity: &CertificateDer<'_>, _intermediates: &[CertificateDer<'_>], _now: UnixTime, ) -> Result { Ok(ClientCertVerified::assertion()) } 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() } } /// Accepts exactly Sunshine's lab certificate, byte for byte. #[derive(Debug)] struct PinnedHost { pinned: Vec, 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 { if end_entity.as_ref() == self.pinned.as_slice() { Ok(ServerCertVerified::assertion()) } else { Err(rustls::Error::General("host certificate is not the pinned lab certificate".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() } }