// 區網直連的 HTTPS: the phone's password and login used to cross the Wi-Fi in the clear. The // port a phone opens now speaks TLS with a certificate this computer makes for itself (kept in // the data folder; the phone's browser asks once whether to trust it — 設定 shows its // fingerprint to compare). Behind it the same plain server as before answers, on this machine // only. Plain HTTP on that port still works from this machine and over Tailscale (already // encrypted); from anywhere else it is sent to https://. use std::io::{Read, Write}; use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; /// Connections carried at once. const MAX_CARRIED: usize = 512; /// How long a new connection has to say something (and to finish the TLS handshake). const HELLO: Duration = Duration::from_secs(10); /// A reader that stopped reading doesn't hold a connection forever. const WRITE_WAIT: Duration = Duration::from_secs(30); /// How long a certificate is good for (browsers refuse long-lived ones). const CERT_DAYS: i64 = 800; /// This computer's certificate and key (DER), made the first time and again when it runs out or /// the computer has an address it doesn't name. pub fn identity(dir: &std::path::Path, hosts: &[String]) -> Result<(Vec, Vec), String> { let (cert_p, key_p, meta_p) = (dir.join("lan-cert.der"), dir.join("lan-key.der"), dir.join("lan-cert.json")); let now = chrono::Utc::now(); let meta: serde_json::Value = std::fs::read(&meta_p).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); let named: Vec<&str> = meta["hosts"].as_array().map(|a| a.iter().filter_map(|h| h.as_str()).collect()).unwrap_or_default(); let good = meta["until"].as_i64().is_some_and(|u| u > now.timestamp() + 86_400) && hosts.iter().all(|h| named.contains(&h.as_str())); if good { if let (Ok(c), Ok(k)) = (std::fs::read(&cert_p), std::fs::read(&key_p)) { return Ok((c, k)); } } use chrono::Datelike; let mut names: Vec = vec!["localhost".into(), "127.0.0.1".into()]; // (Addresses it had before stay named: back on the home Wi-Fi, the same certificate.) names.extend(named.iter().map(|s| s.to_string()).chain(hosts.iter().cloned()).filter(|h| h != "localhost" && h != "127.0.0.1")); names.sort(); names.dedup(); names.truncate(40); let key = rcgen::KeyPair::generate().map_err(|e| e.to_string())?; let mut p = rcgen::CertificateParams::new(names.clone()).map_err(|e| e.to_string())?; p.distinguished_name.push(rcgen::DnType::CommonName, "AnyBot"); let (from, until) = (now - chrono::Duration::days(1), now + chrono::Duration::days(CERT_DAYS)); p.not_before = rcgen::date_time_ymd(from.year(), from.month() as u8, from.day() as u8); p.not_after = rcgen::date_time_ymd(until.year(), until.month() as u8, until.day() as u8); p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth]; let cert = p.self_signed(&key).map_err(|e| e.to_string())?; let (c, k) = (cert.der().to_vec(), key.serialize_der()); crate::httpd::ensure_private_dir(dir); crate::httpd::write_private(&key_p, &k).map_err(|e| e.to_string())?; crate::httpd::write_private(&cert_p, &c).map_err(|e| e.to_string())?; let meta = serde_json::json!({"hosts": names, "until": until.timestamp() - 86_400}); crate::httpd::write_private(&meta_p, meta.to_string().as_bytes()).map_err(|e| e.to_string())?; Ok((c, k)) } /// What a person compares with the browser's certificate details: its SHA-256, in pairs. pub fn fingerprint(cert: &[u8]) -> String { let d = ring::digest::digest(&ring::digest::SHA256, cert); d.as_ref().iter().map(|b| format!("{b:02X}")).collect::>().join(":") } pub fn config(cert: Vec, key: Vec) -> Result, String> { use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}; let c = rustls::ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) .with_safe_default_protocol_versions() .map_err(|e| e.to_string())? .with_no_client_auth() .with_single_cert(vec![CertificateDer::from(cert)], PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key))) .map_err(|e| e.to_string())?; Ok(Arc::new(c)) } /// Plain HTTP is fine from this machine and over Tailscale (WireGuard underneath). fn plain_ok(ip: IpAddr) -> bool { match ip { IpAddr::V4(v) => v.is_loopback() || (v.octets()[0] == 100 && (64..128).contains(&v.octets()[1])), IpAddr::V6(v) => v.is_loopback() || v.to_ipv4_mapped().is_some_and(|m| plain_ok(IpAddr::V4(m))) || (v.segments()[0] == 0xfd7a && v.segments()[1] == 0x115c && v.segments()[2] == 0xa1e0), } } struct Slot(Arc); impl Drop for Slot { fn drop(&mut self) { self.0.fetch_sub(1, Ordering::SeqCst); } } /// The server behind (`inner`, on this machine) sees who really asked. struct Carried(u16); impl Drop for Carried { fn drop(&mut self) { crate::httpd::carried().lock().unwrap().remove(&self.0); } } fn reach(inner: SocketAddr, peer: IpAddr) -> Option<(TcpStream, Carried)> { let up = TcpStream::connect_timeout(&inner, Duration::from_secs(5)).ok()?; let port = up.local_addr().ok()?.port(); // (Before a byte goes through: the server reads who asked once it has the request.) crate::httpd::carried().lock().unwrap().insert(port, peer); Some((up, Carried(port))) } /// Take connections on `listener` until `alive` says stop: TLS is opened here and carried to /// `inner`; plain HTTP goes through as it is where that is safe, and is sent to https elsewhere. pub fn front(listener: TcpListener, inner: SocketAddr, cfg: Arc, alive: Arc bool + Send + Sync>) { listener.set_nonblocking(true).ok(); let active = Arc::new(AtomicUsize::new(0)); while alive() { match listener.accept() { Ok((c, peer)) => { c.set_nonblocking(false).ok(); if active.fetch_add(1, Ordering::SeqCst) >= MAX_CARRIED { active.fetch_sub(1, Ordering::SeqCst); continue; } let (slot, cfg) = (Slot(active.clone()), cfg.clone()); let _ = std::thread::Builder::new().spawn(move || { let _slot = slot; carry(c, peer.ip(), inner, cfg); }); } Err(_) => std::thread::sleep(Duration::from_millis(50)), } } } fn carry(c: TcpStream, peer: IpAddr, inner: SocketAddr, cfg: Arc) { let _ = c.set_read_timeout(Some(HELLO)); let _ = c.set_write_timeout(Some(WRITE_WAIT)); let mut first = [0u8; 1]; if !matches!(c.peek(&mut first), Ok(1)) { return; } // A TLS connection opens with a handshake record (0x16); HTTP with a letter. if first[0] == 0x16 { tls(c, peer, inner, cfg); } else if plain_ok(peer) { plain(c, peer, inner); } else { to_https(c); } } fn plain(mut c: TcpStream, peer: IpAddr, inner: SocketAddr) { let Some((mut up, _carried)) = reach(inner, peer) else { return }; let _ = c.set_read_timeout(None); let (Ok(mut c2), Ok(mut up2)) = (c.try_clone(), up.try_clone()) else { return }; let back = std::thread::spawn(move || { let _ = std::io::copy(&mut up2, &mut c2); let _ = c2.shutdown(Shutdown::Both); }); let _ = std::io::copy(&mut c, &mut up); let _ = up.shutdown(Shutdown::Both); let _ = back.join(); } /// 「http://…」 from the local network: the same address with https. fn to_https(mut c: TcpStream) { let mut head = Vec::new(); let mut buf = [0u8; 1024]; while head.len() < 8192 && !head.windows(4).any(|w| w == b"\r\n\r\n") { match c.read(&mut buf) { Ok(n) if n > 0 => head.extend_from_slice(&buf[..n]), _ => break, } } let text = String::from_utf8_lossy(&head); let path = text.lines().next().and_then(|l| l.split(' ').nth(1)).filter(|p| p.starts_with('/')).unwrap_or("/"); let host = text.lines().skip(1).find_map(|l| l.split_once(':').filter(|(k, _)| k.eq_ignore_ascii_case("host")).map(|(_, v)| v.trim())); // (Only what a host and a path are made of goes back out.) let clean = |s: &str| !s.is_empty() && s.chars().all(|ch| ch.is_ascii_graphic() && !matches!(ch, '"' | '<' | '>' | '\\')); let out = match host { Some(h) if clean(h) && clean(path) => format!("HTTP/1.1 308 Permanent Redirect\r\nLocation: https://{h}{path}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"), _ => "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_string(), }; let _ = c.write_all(out.as_bytes()); let _ = c.shutdown(Shutdown::Both); } /// Send what TLS has ready for the phone (called with the connection's lock held, so the two /// directions never interleave their records). fn flush(conn: &mut rustls::ServerConnection, to: &mut TcpStream) -> bool { while conn.wants_write() { if conn.write_tls(to).is_err() { return false; } } true } fn tls(mut c: TcpStream, peer: IpAddr, inner: SocketAddr, cfg: Arc) { let Ok(conn) = rustls::ServerConnection::new(cfg) else { return }; let conn = Arc::new(Mutex::new(conn)); let Some((mut up, _carried)) = reach(inner, peer) else { return }; let (Ok(mut to_phone), Ok(mut to_phone2), Ok(mut up2)) = (c.try_clone(), c.try_clone(), up.try_clone()) else { return }; // The server's answer → the phone. (Each direction blocks on its own socket, never on a // timer; the lock is held only while bytes are turned into records.) let conn2 = conn.clone(); let back = std::thread::spawn(move || { let mut buf = [0u8; 16 * 1024]; loop { let n = match up2.read(&mut buf) { Ok(n) if n > 0 => n, _ => break, }; let mut g = conn2.lock().unwrap(); if g.writer().write_all(&buf[..n]).is_err() || !flush(&mut g, &mut to_phone2) { break; } } let mut g = conn2.lock().unwrap(); g.send_close_notify(); flush(&mut g, &mut to_phone2); let _ = to_phone2.shutdown(Shutdown::Both); }); // The phone → the server. let mut buf = [0u8; 16 * 1024]; let mut shaken = false; 'live: loop { let n = match c.read(&mut buf) { Ok(n) if n > 0 => n, _ => break, }; let mut plain = Vec::new(); let mut closed = false; { let mut g = conn.lock().unwrap(); let mut rd = &buf[..n]; while !rd.is_empty() { if g.read_tls(&mut rd).is_err() { break 'live; } let state = match g.process_new_packets() { Ok(s) => s, Err(_) => { // (The alert that says why.) flush(&mut g, &mut to_phone); break 'live; } }; let at = plain.len(); plain.resize(at + state.plaintext_bytes_to_read(), 0); if g.reader().read_exact(&mut plain[at..]).is_err() { break 'live; } closed |= state.peer_has_closed(); } if !flush(&mut g, &mut to_phone) { break; } if !shaken && !g.is_handshaking() { shaken = true; // From here the server behind keeps the time (its own deadlines close the // connection, which ends this one). let _ = c.set_read_timeout(None); } } if (!plain.is_empty() && up.write_all(&plain).is_err()) || closed { break; } } let _ = up.shutdown(Shutdown::Both); let _ = back.join(); let _ = c.shutdown(Shutdown::Both); } #[cfg(test)] mod tests { use super::*; /// HTTPS on the port reaches the server behind, which sees who asked; the certificate is /// kept and made again only for a new address. #[test] fn https_reaches_the_server_behind() { let dir = std::env::temp_dir().join(format!("anybot-lantls-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let (cert, key) = identity(&dir, &["192.168.7.7".into()]).unwrap(); assert_eq!(identity(&dir, &["192.168.7.7".into()]).unwrap().0, cert, "kept"); assert_ne!(identity(&dir, &["10.9.9.9".into()]).unwrap().0, cert, "a new address: a new one"); assert_eq!(fingerprint(&cert).len(), 32 * 3 - 1); let (cert, key) = { let _ = key; identity(&dir, &[]).unwrap() }; // (For looking at it with other tools: ANYBOT_TEST_CERT_OUT=file.) if let Ok(out) = std::env::var("ANYBOT_TEST_CERT_OUT") { let _ = std::fs::write(out, &cert); } let inner = TcpListener::bind("127.0.0.1:0").unwrap(); let inner_addr = inner.local_addr().unwrap(); let on = Arc::new(std::sync::atomic::AtomicBool::new(true)); let alive: Arc bool + Send + Sync> = { let on = on.clone(); Arc::new(move || on.load(Ordering::SeqCst)) }; let big = "長".repeat(200_000); let big2 = big.clone(); let handler: crate::httpd::Handler = Arc::new(move |r| crate::httpd::Resp::json(&serde_json::json!({"peer": r.peer, "path": r.path, "got": r.body.len(), "big": big2}))); { let alive = alive.clone(); std::thread::spawn(move || crate::httpd::serve(inner, handler, alive)); } let outer = TcpListener::bind("127.0.0.1:0").unwrap(); let port = outer.local_addr().unwrap().port(); let cfg = config(cert.clone(), key).unwrap(); { let alive = alive.clone(); std::thread::spawn(move || front(outer, inner_addr, cfg, alive)); } // A client that trusts exactly this certificate. let mut roots = rustls::RootCertStore::empty(); roots.add(rustls::pki_types::CertificateDer::from(cert)).unwrap(); let ccfg = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())).with_safe_default_protocol_versions().unwrap().with_root_certificates(roots).with_no_client_auth(); let name = rustls::pki_types::ServerName::try_from("127.0.0.1").unwrap(); let tcp = TcpStream::connect(("127.0.0.1", port)).unwrap(); let mut s = rustls::StreamOwned::new(rustls::ClientConnection::new(Arc::new(ccfg), name).unwrap(), tcp); let body = vec![b'x'; 150_000]; s.write_all(format!("POST /api/thing HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).as_bytes()).unwrap(); s.write_all(&body).unwrap(); let mut out = Vec::new(); let _ = s.read_to_end(&mut out); let text = String::from_utf8_lossy(&out); assert!(text.starts_with("HTTP/1.1 200"), "{}", &text[..text.len().min(200)]); let v: serde_json::Value = serde_json::from_str(text.split("\r\n\r\n").nth(1).unwrap()).unwrap(); assert_eq!((v["peer"].as_str(), v["path"].as_str(), v["got"].as_u64()), (Some("127.0.0.1"), Some("/api/thing"), Some(150_000))); assert_eq!(v["big"].as_str().unwrap().len(), big.len()); // Plain HTTP from this machine still goes through. let mut p = TcpStream::connect(("127.0.0.1", port)).unwrap(); p.write_all(format!("GET /plain HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n").as_bytes()).unwrap(); let mut out = String::new(); let _ = p.read_to_string(&mut out); assert!(out.starts_with("HTTP/1.1 200") && out.contains("/plain")); on.store(false, Ordering::SeqCst); let _ = std::fs::remove_dir_all(&dir); } #[test] fn plain_http_from_the_wifi_is_sent_to_https() { assert!(plain_ok("127.0.0.1".parse().unwrap()) && plain_ok("100.101.2.3".parse().unwrap()) && plain_ok("fd7a:115c:a1e0::1".parse().unwrap())); assert!(!plain_ok("192.168.1.20".parse().unwrap()) && !plain_ok("10.0.0.3".parse().unwrap()) && !plain_ok("8.8.8.8".parse().unwrap())); let l = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = l.local_addr().unwrap(); let t = std::thread::spawn(move || to_https(l.accept().unwrap().0)); let mut c = TcpStream::connect(addr).unwrap(); c.write_all(b"GET /a?b=1 HTTP/1.1\r\nHost: 192.168.1.5:8793\r\n\r\n").unwrap(); let mut out = String::new(); let _ = c.read_to_string(&mut out); t.join().unwrap(); assert!(out.contains("308") && out.contains("Location: https://192.168.1.5:8793/a?b=1\r\n"), "{out}"); } }