[repo] Lab relay: recorder, redacting dump, TCP/TLS-terminating/UDP relays, CLI (never compiled yet)

This commit is contained in:
2026-11-25 12:36:56 +01:00
parent fbb8833f3d
commit a2b834ed87
9 changed files with 983 additions and 1 deletions
+159
View File
@@ -0,0 +1,159 @@
//! lab-relay: our own logging relay for the one GameStream lab capture (`docs/LAB_CAPTURE.md`).
//!
//! ```text
//! lab-relay run [--listen 127.0.0.1] [--upstream 127.0.0.2] [--upstream-port-offset N] [--capture-dir DIR]
//! [--key-dir DIR] [--https-passthrough] [--wait-for-keys-secs N] [--rewrite FROM=TO]... [--no-rewrite]
//! lab-relay dump <file.dslr> list records, secrets redacted
//! lab-relay strip-video <in> <out> copy with video payloads cut to their 32 header bytes
//! ```
//!
//! Binds and connects only on loopback (refused otherwise). Never sends anything of its own.
mod config;
mod record;
mod recorder;
mod redact;
mod rewrite;
mod tcp;
mod tls;
mod udp;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Write};
use std::process::ExitCode;
use std::sync::Arc;
use std::thread;
use config::{Config, Transport};
use record::{Kind, Protocol, Record};
use recorder::Recorder;
/// Bytes of a video packet kept by `strip-video`: RTP header, reserved bytes and the NV header.
const VIDEO_HEADER_KEEP: usize = 32;
/// Text shown per record by `dump`.
const DUMP_TEXT_LIMIT: usize = 4000;
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let result = match args.split_first() {
Some((cmd, rest)) if cmd == "run" => run(rest),
Some((cmd, [file])) if cmd == "dump" => dump(file),
Some((cmd, [input, output])) if cmd == "strip-video" => strip_video(input, output),
_ => Err("usage: lab-relay run [options] | dump <file> | strip-video <in> <out>".into()),
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("lab-relay: {e}");
ExitCode::FAILURE
}
}
}
type AnyResult = Result<(), Box<dyn std::error::Error>>;
fn run(args: &[String]) -> AnyResult {
let config = Arc::new(Config::from_args(args)?);
let (rec, path) = Recorder::create(&config.capture_dir)?;
let rec = Arc::new(rec);
println!("lab-relay: recording to {}", path.display());
let mut threads = Vec::new();
for spec in config.ports()? {
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
println!(
"lab-relay: {:?} {} -> {}",
spec.protocol,
config.listen_addr(&spec),
config.upstream_addr(&spec)
);
threads.push(thread::spawn(move || {
let r = match spec.transport {
Transport::Tcp => tcp::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
Transport::Tls => tls::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
Transport::Udp => udp::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
};
if let Err(e) = r {
eprintln!("lab-relay: port {} stopped: {e}", spec.listen_port);
rec.note(Protocol::Meta, 0, &format!("port {} stopped: {e}", spec.listen_port));
}
}));
}
rec.note(Protocol::Meta, 0, "relay started");
for t in threads {
let _ = t.join();
}
Ok(())
}
fn is_text(r: &Record) -> bool {
r.kind == Kind::Note
|| r.kind == Kind::Open
|| matches!(r.protocol, Protocol::Http | Protocol::HttpsPlain | Protocol::Rtsp)
}
fn dump(file: &str) -> AnyResult {
let mut input = BufReader::new(File::open(file)?);
let header = record::read_header(&mut input)?;
let stdout = io::stdout();
let mut out = stdout.lock();
writeln!(out, "capture started at unix {} us", header.start_unix_micros)?;
let mut index = 0u64;
loop {
let r = match record::read_record(&mut input) {
Ok(Some(r)) => r,
Ok(None) => break,
Err(e) => {
writeln!(out, "stopped at record {index}: {e}")?;
break;
}
};
writeln!(
out,
"#{index} t={}.{:06}s conn={} {:?} {:?} {:?} {} bytes",
r.time_micros / 1_000_000,
r.time_micros % 1_000_000,
r.connection,
r.kind,
r.protocol,
r.direction,
r.payload.len()
)?;
if is_text(&r) {
let text = redact::redact(&r.payload);
let shown = &text[..text.len().min(DUMP_TEXT_LIMIT)];
writeln!(out, " {}", String::from_utf8_lossy(shown).escape_debug())?;
} else {
let hex: String = r.payload.iter().take(32).map(|b| format!("{b:02x} ")).collect();
writeln!(out, " {hex}")?;
}
index += 1;
}
Ok(())
}
fn strip_video(input: &str, output: &str) -> AnyResult {
let mut reader = BufReader::new(File::open(input)?);
let header = record::read_header(&mut reader)?;
let mut writer = BufWriter::new(File::options().write(true).create_new(true).open(output)?);
record::write_header(&mut writer, header)?;
let mut stripped = 0u64;
while let Some(mut r) = record::read_record(&mut reader)? {
if r.kind == Kind::Data && r.protocol == Protocol::Video && r.payload.len() > VIDEO_HEADER_KEEP {
r.payload.truncate(VIDEO_HEADER_KEEP);
stripped += 1;
}
record::write_record(&mut writer, &r)?;
}
let note = Record {
kind: Kind::Note,
protocol: Protocol::Meta,
direction: record::Direction::None,
connection: 0,
time_micros: u64::MAX,
payload: format!("strip-video: {stripped} video payloads cut to {VIDEO_HEADER_KEEP} bytes").into_bytes(),
};
record::write_record(&mut writer, &note)?;
writer.flush()?;
println!("lab-relay: {stripped} video records stripped");
Ok(())
}
+1 -1
View File
@@ -70,7 +70,7 @@ pub enum Direction {
}
macro_rules! codes {
($t:ty { $($v:ident = $c:expr),* $(,)? }) => {
($t:ty { $($v:ident = $c:literal),* $(,)? }) => {
impl $t {
/// Wire code.
pub const fn code(self) -> u8 {
+73
View File
@@ -0,0 +1,73 @@
//! The shared, thread-safe writer of the record file. Every record is flushed at once, so a killed relay leaves a
//! file that reads cleanly up to its last whole record.
use std::fs::{File, OpenOptions};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use crate::record::{self, Direction, Header, Kind, Protocol, Record};
/// Writes records for one capture.
pub struct Recorder {
out: Mutex<BufWriter<File>>,
start: Instant,
next_connection: AtomicU32,
failed: AtomicBool,
}
impl Recorder {
/// Creates `session-<unix seconds>.dslr` in `dir` (never overwrites) and writes the header.
///
/// # Errors
/// I/O errors, including an existing file of the same name.
pub fn create(dir: &Path) -> io::Result<(Self, PathBuf)> {
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
let path = dir.join(format!("session-{}.dslr", now.as_secs()));
let file = OpenOptions::new().write(true).create_new(true).open(&path)?;
let mut out = BufWriter::new(file);
let start_unix_micros = u64::try_from(now.as_micros()).unwrap_or(u64::MAX);
record::write_header(&mut out, Header { start_unix_micros })?;
out.flush()?;
let rec = Self {
out: Mutex::new(out),
start: Instant::now(),
next_connection: AtomicU32::new(1),
failed: AtomicBool::new(false),
};
Ok((rec, path))
}
/// A fresh connection or flow id.
pub fn new_connection(&self) -> u32 {
self.next_connection.fetch_add(1, Ordering::Relaxed)
}
/// Records bytes (split into several records if over [`record::MAX_PAYLOAD`]).
pub fn log(&self, kind: Kind, protocol: Protocol, direction: Direction, connection: u32, payload: &[u8]) {
let time_micros = u64::try_from(self.start.elapsed().as_micros()).unwrap_or(u64::MAX);
let chunks: Vec<&[u8]> =
if payload.is_empty() { vec![payload] } else { payload.chunks(record::MAX_PAYLOAD).collect() };
let Ok(mut out) = self.out.lock() else { return self.fail("lock poisoned") };
for chunk in chunks {
let r = Record { kind, protocol, direction, connection, time_micros, payload: chunk.to_vec() };
if let Err(e) = record::write_record(&mut *out, &r).and_then(|()| out.flush()) {
return self.fail(&e.to_string());
}
}
}
/// Records a note (never pass key material here).
pub fn note(&self, protocol: Protocol, connection: u32, text: &str) {
self.log(Kind::Note, protocol, Direction::None, connection, text.as_bytes());
}
/// Reports the first write failure on stderr; later ones stay silent.
fn fail(&self, why: &str) {
if !self.failed.swap(true, Ordering::Relaxed) {
eprintln!("lab-relay: writing the record file failed: {why}");
}
}
}
+122
View File
@@ -0,0 +1,122 @@
//! Hides secrets when records are printed (`lab-relay dump`). The record file itself keeps everything; it never
//! leaves the lab folder.
/// Query parameters whose values are secret or let someone redo the pairing proofs.
pub const SECRET_PARAMS: [&str; 6] =
["rikey", "salt", "clientchallenge", "serverchallengeresp", "clientpairingsecret", "pin"];
/// XML elements whose text is secret.
pub const SECRET_ELEMENTS: [&str; 2] = ["challengeresponse", "pairingsecret"];
/// HTTP headers whose values are secret.
pub const SECRET_HEADERS: [&str; 2] = ["authorization", "cookie"];
/// What replaces a secret.
pub const MARK: &[u8] = b"<redacted>";
fn ends_param_value(b: u8) -> bool {
matches!(b, b'&' | b' ' | b'"' | b'\r' | b'\n' | b'<' | b'#')
}
/// Returns `text` with every secret value replaced by [`MARK`].
pub fn redact(text: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(text.len());
let mut i = 0;
let lower: Vec<u8> = text.to_ascii_lowercase();
'scan: while i < text.len() {
// `name=` at a parameter boundary.
if i == 0 || matches!(text[i - 1], b'?' | b'&' | b' ' | b'\n') {
for name in SECRET_PARAMS {
let key = [name.as_bytes(), b"="].concat();
if lower[i..].starts_with(&key) {
out.extend_from_slice(&text[i..i + key.len()]);
out.extend_from_slice(MARK);
i += key.len();
while i < text.len() && !ends_param_value(text[i]) {
i += 1;
}
continue 'scan;
}
}
}
// `<element>` … `</`.
if text[i] == b'<' {
for name in SECRET_ELEMENTS {
let open = [b"<", name.as_bytes(), b">"].concat();
if lower[i..].starts_with(&open) {
out.extend_from_slice(&text[i..i + open.len()]);
out.extend_from_slice(MARK);
i += open.len();
while i < text.len() && !text[i..].starts_with(b"</") {
i += 1;
}
continue 'scan;
}
}
}
// `Header:` at a line start, up to the end of the line.
if i == 0 || text[i - 1] == b'\n' {
for name in SECRET_HEADERS {
let key = [name.as_bytes(), b":"].concat();
if lower[i..].starts_with(&key) {
out.extend_from_slice(&text[i..i + key.len()]);
out.extend_from_slice(b" ");
out.extend_from_slice(MARK);
i += key.len();
while i < text.len() && text[i] != b'\r' && text[i] != b'\n' {
i += 1;
}
continue 'scan;
}
}
}
out.push(text[i]);
i += 1;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn r(s: &str) -> String {
String::from_utf8(redact(s.as_bytes())).unwrap()
}
#[test]
fn launch_key_is_hidden() {
assert_eq!(
r("GET /launch?uniqueid=0123&appid=1&rikey=00112233445566778899aabbccddeeff&rikeyid=7 HTTP/1.1"),
"GET /launch?uniqueid=0123&appid=1&rikey=<redacted>&rikeyid=7 HTTP/1.1"
);
}
#[test]
fn pairing_values_are_hidden_but_names_and_certs_stay() {
assert_eq!(
r("GET /pair?uniqueid=1&phrase=getservercert&salt=ABCD&clientcert=2D2D HTTP/1.1"),
"GET /pair?uniqueid=1&phrase=getservercert&salt=<redacted>&clientcert=2D2D HTTP/1.1"
);
assert_eq!(
r("<root status_code=\"200\"><paired>1</paired><pairingsecret>ffee</pairingsecret></root>"),
"<root status_code=\"200\"><paired>1</paired><pairingsecret><redacted></pairingsecret></root>"
);
}
#[test]
fn auth_headers_are_hidden() {
assert_eq!(
r("POST /api/pin HTTP/1.1\r\nAuthorization: Basic dXNlcjpwYXNz\r\nHost: x\r\n"),
"POST /api/pin HTTP/1.1\r\nAuthorization: <redacted>\r\nHost: x\r\n"
);
}
#[test]
fn lookalike_names_are_not_touched() {
assert_eq!(r("GET /x?rikeyid=5&nosalt=1"), "GET /x?rikeyid=5&nosalt=1");
}
#[test]
fn value_at_end_of_input_is_hidden() {
assert_eq!(r("?rikey=abc"), "?rikey=<redacted>");
assert_eq!(r("<challengeresponse>abc"), "<challengeresponse><redacted>");
}
}
+5
View File
@@ -55,6 +55,11 @@ impl Rewriter {
std::mem::take(&mut self.held)
}
/// Whether there are no rules (the rewriter then passes bytes through and never holds any).
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
/// Bytes currently held back.
pub fn held(&self) -> usize {
self.held.len()
+133
View File
@@ -0,0 +1,133 @@
//! Plain TCP relaying (HTTP, RTSP, and HTTPS in pass-through mode).
use std::io::{self, Read, Write};
use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use crate::config::{Config, PortSpec, Rewrite};
use crate::record::{Direction, Kind, Protocol};
use crate::recorder::Recorder;
use crate::rewrite::Rewriter;
/// How long the host-to-client side waits for more bytes before releasing bytes held by the rewriter.
pub const HOLD_TIMEOUT: Duration = Duration::from_millis(50);
/// Timeout for connecting to Sunshine.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Whether a protocol's bytes are plaintext the rewriter may touch.
pub fn rewritable(protocol: Protocol) -> bool {
matches!(protocol, Protocol::Http | Protocol::Rtsp | Protocol::HttpsPlain)
}
/// Accepts connections on `spec`'s port forever.
///
/// # Errors
/// Binding fails.
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> 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(spec.protocol, 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(spec.protocol, conn, &format!("connection ended with error: {e}"));
}
rec.log(Kind::Close, spec.protocol, Direction::None, conn, &[]);
});
}
Ok(())
}
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, spec.protocol, Direction::None, conn, format!("{peer} -> {upstream_addr}").as_bytes());
let upstream = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
let _ = client.set_nodelay(true);
let _ = upstream.set_nodelay(true);
let rules = if rewritable(spec.protocol) { config.rewrites.clone() } else { Vec::new() };
pump_pair(client, upstream, spec.protocol, rec, conn, rules)
}
/// Copies both directions until both sides are closed; rewrites host-to-client bytes with `rules`.
///
/// # Errors
/// Socket errors.
pub fn pump_pair(
client: TcpStream,
upstream: TcpStream,
protocol: Protocol,
rec: &Recorder,
conn: u32,
rules: Vec<Rewrite>,
) -> io::Result<()> {
let (mut c_read, mut u_write) = (client.try_clone()?, upstream.try_clone()?);
thread::scope(|s| {
s.spawn(|| {
let mut buf = vec![0u8; 64 * 1024];
loop {
match c_read.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
rec.log(Kind::Data, protocol, Direction::ClientToHost, conn, &buf[..n]);
if u_write.write_all(&buf[..n]).is_err() {
break;
}
}
}
}
let _ = u_write.shutdown(Shutdown::Write);
});
host_to_client(upstream, client, protocol, rec, conn, rules)
})
}
fn host_to_client(
mut upstream: TcpStream,
mut client: TcpStream,
protocol: Protocol,
rec: &Recorder,
conn: u32,
rules: Vec<Rewrite>,
) -> io::Result<()> {
let mut rewriter = Rewriter::new(rules);
if !rewriter.is_empty() {
upstream.set_read_timeout(Some(HOLD_TIMEOUT))?;
}
let mut buf = vec![0u8; 64 * 1024];
let result = loop {
match upstream.read(&mut buf) {
Ok(0) => break Ok(()),
Ok(n) => {
rec.log(Kind::Data, protocol, Direction::HostToClient, conn, &buf[..n]);
let (out, count) = rewriter.push(&buf[..n]);
if count > 0 {
rec.note(protocol, conn, &format!("rewrote {count} occurrence(s) in the bytes above"));
}
if let Err(e) = client.write_all(&out) {
break Err(e);
}
}
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {
let held = rewriter.flush();
if let Err(e) = client.write_all(&held) {
break Err(e);
}
}
Err(e) => break Err(e),
}
};
let rest = rewriter.flush();
let _ = client.write_all(&rest);
let _ = client.shutdown(Shutdown::Write);
result
}
+386
View File
@@ -0,0 +1,386 @@
//! 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<Config>, spec: PortSpec, rec: Arc<Recorder>) -> 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<CertificateDer<'static>>,
host_key: PrivateKeyDer<'static>,
client_certs: Vec<CertificateDer<'static>>,
client_key: PrivateKeyDer<'static>,
}
fn load(files: &TlsFiles) -> io::Result<Material> {
fn certs(path: &Path) -> io::Result<Vec<CertificateDer<'static>>> {
let certs = CertificateDer::pem_file_iter(path)
.map_err(|e| io::Error::other(format!("{}: {e:?}", path.display())))?
.collect::<Result<Vec<_>, _>>()
.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<PrivateKeyDer<'static>> {
// 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<Material> {
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<CryptoProvider>,
pinned: Vec<u8>,
certs: Vec<CertificateDer<'static>>,
key: PrivateKeyDer<'static>,
) -> io::Result<ClientConfig> {
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<u8>, 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<ClientCertVerified, rustls::Error> {
Ok(ClientCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls12_signature(message, cert, dss, &self.algs)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls13_signature(message, cert, dss, &self.algs)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.algs.supported_schemes()
}
}
/// Accepts exactly Sunshine's lab certificate, byte for byte.
#[derive(Debug)]
struct PinnedHost {
pinned: Vec<u8>,
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<ServerCertVerified, rustls::Error> {
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<HandshakeSignatureValid, rustls::Error> {
verify_tls12_signature(message, cert, dss, &self.algs)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls13_signature(message, cert, dss, &self.algs)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.algs.supported_schemes()
}
}
+101
View File
@@ -0,0 +1,101 @@
//! UDP relaying (video, control, audio, mic).
//!
//! Each client address gets its own upstream socket on the listen address, so Sunshine sends the stream to the
//! relay (the address its PING or ENet connect came from) and the relay hands it to Moonlight.
use std::collections::HashMap;
use std::io;
use std::net::{SocketAddr, UdpSocket};
use std::sync::{Arc, Mutex};
use std::thread;
use crate::config::{Config, PortSpec};
use crate::record::{Direction, Kind};
use crate::recorder::Recorder;
/// Most client flows per port (one Moonlight uses one).
pub const MAX_FLOWS: usize = 16;
/// Largest datagram.
pub const MAX_DATAGRAM: usize = 64 * 1024;
/// Windows reports an ICMP "port unreachable" from an earlier send as a reset on the next receive; that is not
/// fatal for UDP.
fn transient(e: &io::Error) -> bool {
matches!(e.kind(), io::ErrorKind::ConnectionReset | io::ErrorKind::ConnectionRefused | io::ErrorKind::Interrupted)
}
/// Relays one UDP port forever.
///
/// # Errors
/// Binding fails.
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
let listen = Arc::new(UdpSocket::bind(config.listen_addr(&spec))?);
let upstream_addr = config.upstream_addr(&spec);
let flows: Mutex<HashMap<SocketAddr, (Arc<UdpSocket>, u32)>> = Mutex::new(HashMap::new());
let mut buf = vec![0u8; MAX_DATAGRAM];
loop {
let (n, from) = match listen.recv_from(&mut buf) {
Ok(v) => v,
Err(e) if transient(&e) => continue,
Err(e) => {
rec.note(spec.protocol, 0, &format!("receive failed: {e}"));
continue;
}
};
let flow = {
let Ok(mut map) = flows.lock() else { return Err(io::Error::other("flow table poisoned")) };
if let Some(f) = map.get(&from) {
Some(f.clone())
} else if map.len() >= MAX_FLOWS {
rec.note(spec.protocol, 0, &format!("dropping datagram from {from}: flow table full"));
None
} else {
let up = Arc::new(UdpSocket::bind(SocketAddr::new(config.listen, 0))?);
up.connect(upstream_addr)?;
let conn = rec.new_connection();
rec.log(Kind::Open, spec.protocol, Direction::None, conn, format!("{from} -> {upstream_addr}").as_bytes());
spawn_return_path(Arc::clone(&up), Arc::clone(&listen), from, spec, Arc::clone(&rec), conn);
map.insert(from, (Arc::clone(&up), conn));
Some((up, conn))
}
};
let Some((up, conn)) = flow else { continue };
rec.log(Kind::Data, spec.protocol, Direction::ClientToHost, conn, &buf[..n]);
if let Err(e) = up.send(&buf[..n]) {
if !transient(&e) {
rec.note(spec.protocol, conn, &format!("send to host failed: {e}"));
}
}
}
}
fn spawn_return_path(
up: Arc<UdpSocket>,
listen: Arc<UdpSocket>,
client: SocketAddr,
spec: PortSpec,
rec: Arc<Recorder>,
conn: u32,
) {
thread::spawn(move || {
let mut buf = vec![0u8; MAX_DATAGRAM];
loop {
match up.recv(&mut buf) {
Ok(n) => {
rec.log(Kind::Data, spec.protocol, Direction::HostToClient, conn, &buf[..n]);
if let Err(e) = listen.send_to(&buf[..n], client) {
if !transient(&e) {
rec.note(spec.protocol, conn, &format!("send to client failed: {e}"));
}
}
}
Err(e) if transient(&e) => {}
Err(e) => {
rec.note(spec.protocol, conn, &format!("receive from host failed: {e}"));
break;
}
}
}
rec.log(Kind::Close, spec.protocol, Direction::None, conn, &[]);
});
}