// 區網直連的 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)) } /// Tailscale's address ranges: 100.64.0.0/10 and fd7a:115c:a1e0::/48. fn tailscale_range(ip: IpAddr) -> bool { match ip.to_canonical() { IpAddr::V4(v) => v.octets()[0] == 100 && (64..128).contains(&v.octets()[1]), IpAddr::V6(v) => v.segments()[..3] == [0xfd7a, 0x115c, 0xa1e0], } } /// Plain HTTP is fine from this machine, and over Tailscale (WireGuard underneath): from a /// Tailscale address *to* this machine's address on its Tailscale tunnel (`tunnels`). The /// addresses alone don't say Tailscale — a Wi-Fi that hands out 100.64.0.0/10 itself (the /// carrier-grade NAT range, on some hotspots and campus networks) would have the phone's password /// cross the air in the clear. fn plain_ok(peer: IpAddr, local: IpAddr, tunnels: &[IpAddr]) -> bool { peer.to_canonical().is_loopback() || (tailscale_range(peer) && tunnels.contains(&local.to_canonical())) } /// This machine's Tailscale addresses: those in Tailscale's ranges on a point-to-point (tunnel) /// interface — macOS's utun, Linux's tailscale0, Windows's Tailscale adapter. Read from /// `ifconfig` (macOS, Linux net-tools), `ip -o addr` (Linux) or `ipconfig` (Windows), at most /// every 30 seconds. Where none answers there are none, and plain HTTP over Tailscale is sent to /// https like the rest. pub fn tunnel_addrs() -> Vec { #[cfg(test)] if let Some(v) = TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()).clone() { return v; } static CACHE: Mutex)>> = Mutex::new(None); let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); if let Some((_, v)) = cache.as_ref().filter(|(at, _)| at.elapsed() < Duration::from_secs(30)) { return v.clone(); } let run = |cmd: &str, args: &[&str]| { let mut c = std::process::Command::new(cmd); c.args(args); #[cfg(windows)] { use std::os::windows::process::CommandExt; // (No console window flashing up.) c.creation_flags(0x0800_0000); } c.output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default() }; let v = if cfg!(windows) { parse_ipconfig_tunnels(&run("ipconfig", &[])) } else { let mut text = run("ifconfig", &[]); if text.trim().is_empty() { text = run("ip", &["-o", "addr"]); } parse_tunnel_addrs(&text) }; *cache = Some((std::time::Instant::now(), v.clone())); v } /// Tests that need to say which addresses are this machine's tunnel's (one at a time). #[cfg(test)] static TEST_TUNNELS: Mutex>> = Mutex::new(None); #[cfg(test)] pub fn with_tunnels(tunnels: &[IpAddr], f: impl FnOnce() -> R) -> R { static ONE_AT_A_TIME: Mutex<()> = Mutex::new(()); let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); *TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()) = Some(tunnels.to_vec()); let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); *TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()) = None; r.unwrap_or_else(|p| std::panic::resume_unwind(p)) } /// The address this computer would send from to reach `dest` — which interface the routing table /// picks (a UDP socket's connect sends nothing). None: no route. pub fn source_for(dest: IpAddr) -> Option { let any: SocketAddr = if dest.is_ipv4() { (std::net::Ipv4Addr::UNSPECIFIED, 0).into() } else { (std::net::Ipv6Addr::UNSPECIFIED, 0).into() }; let s = std::net::UdpSocket::bind(any).ok()?; s.connect((dest, 9)).ok()?; s.local_addr().ok().map(|a| a.ip().to_canonical()) } /// A server reached through this machine's Tailscale tunnel: every one of its addresses is a /// Tailscale one *and* is sent out from a tunnel address (`source` says from where). A 100.x /// address on a Wi-Fi that hands out 100.64.0.0/10 goes out of the Wi-Fi: not Tailscale. pub fn tailscale_server(addrs: &[IpAddr], tunnels: &[IpAddr], source: impl Fn(IpAddr) -> Option) -> bool { !addrs.is_empty() && addrs.iter().all(|&a| tailscale_range(a) && source(a).is_some_and(|s| tunnels.contains(&s.to_canonical()))) } /// The Tailscale adapter's addresses in Windows's `ipconfig` output. An adapter's line starts at /// the left margin ("Unknown adapter Tailscale:", 「未知的介面卡 Tailscale:」); its values are /// indented, after the last ": " ("IPv4 Address. . . : 100.101.2.3", 「IPv4 位址 . . . : …」), /// sometimes with "(Preferred)" after them. The labels are in the system's language; the /// adapter's name and the addresses aren't. fn parse_ipconfig_tunnels(text: &str) -> Vec { let mut out = vec![]; let mut tunnel = false; for line in text.lines() { if line.trim().is_empty() { continue; } if !line.starts_with(char::is_whitespace) { tunnel = line.to_ascii_lowercase().contains("tailscale"); continue; } let Some((_, value)) = line.rsplit_once(": ") else { continue }; let value = value.trim().split(['(', '%']).next().unwrap_or("").trim(); if let Ok(ip) = value.parse::() { if tunnel && tailscale_range(ip) { out.push(ip.to_canonical()); } } } out.dedup(); out } /// The Tailscale addresses in `ifconfig` output (an interface's first line has its flags: /// POINTOPOINT is a tunnel) or `ip -o addr` output (one address a line: on tailscale0, or a /// /32 or /128 of its own). fn parse_tunnel_addrs(text: &str) -> Vec { let mut out = vec![]; let mut tunnel = false; for line in text.lines() { let words: Vec<&str> = line.split_whitespace().collect(); let is_family = |w: &&str| *w == "inet" || *w == "inet6"; // `ip -o addr`: "4: tailscale0 inet 100.101.2.3/32 scope global tailscale0 …". let numbered = words.first().and_then(|w| w.strip_suffix(':')).is_some_and(|n| n.parse::().is_ok()); if numbered { if let (Some(name), Some(i)) = (words.get(1), words.iter().position(is_family)) { let addr = words.get(i + 1).copied().unwrap_or(""); let (ip, prefix) = addr.split_once('/').unwrap_or((addr, "")); if let Ok(ip) = ip.parse::() { if tailscale_range(ip) && (name.starts_with("tailscale") || prefix == "32" || prefix == "128") { out.push(ip.to_canonical()); } } } continue; } // `ifconfig`: an interface starts at the left margin; its addresses are indented under it. if !line.is_empty() && !line.starts_with(char::is_whitespace) { tunnel = line.contains("POINTOPOINT"); continue; } if let (true, Some(family), Some(addr)) = (tunnel, words.first(), words.get(1)) { let addr = addr.split(['%', '/']).next().unwrap_or(addr); if is_family(family) { if let Ok(ip) = addr.parse::() { if tailscale_range(ip) { out.push(ip.to_canonical()); } } } } } out.dedup(); out } 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 c.local_addr().is_ok_and(|local| plain_ok(peer, local.ip(), &tunnel_addrs())) { 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() { let ip = |s: &str| s.parse::().unwrap(); let tunnels = [ip("100.84.144.91"), ip("fd7a:115c:a1e0::91")]; // From this machine; over Tailscale, to this machine's Tailscale address. assert!(plain_ok(ip("127.0.0.1"), ip("127.0.0.1"), &[])); assert!(plain_ok(ip("100.101.2.3"), ip("100.84.144.91"), &tunnels) && plain_ok(ip("fd7a:115c:a1e0::1"), ip("fd7a:115c:a1e0::91"), &tunnels)); assert!(plain_ok(ip("::ffff:100.101.2.3"), ip("::ffff:100.84.144.91"), &tunnels), "IPv4 written as IPv6"); // The Wi-Fi: sent to https. assert!(!plain_ok(ip("192.168.1.20"), ip("192.168.1.5"), &tunnels) && !plain_ok(ip("10.0.0.3"), ip("10.0.0.2"), &tunnels) && !plain_ok(ip("8.8.8.8"), ip("10.0.0.2"), &tunnels)); // A Wi-Fi that hands out the carrier-grade NAT range itself is not Tailscale: the phone // (100.70.0.9) reaches this Mac's Wi-Fi address (100.70.0.5), not its tunnel's. assert!(!plain_ok(ip("100.70.0.9"), ip("100.70.0.5"), &tunnels)); // …nor is Tailscale's range without Tailscale on this machine (no tunnel address). assert!(!plain_ok(ip("100.101.2.3"), ip("100.84.144.91"), &[])); // A device on the Wi-Fi aiming at the Tailscale address doesn't come from Tailscale's range. assert!(!plain_ok(ip("192.168.1.20"), ip("100.84.144.91"), &tunnels)); 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}"); } /// Tailscale is the tunnel interface's address, not any 100.64.0.0/10 one: macOS's ifconfig /// (utun, POINTOPOINT), Linux's ifconfig and `ip -o addr` (tailscale0), and a hotspot that /// hands out 100.70.0.5 on the Wi-Fi. #[test] fn tailscale_is_the_tunnel_not_the_range() { let ip = |s: &str| s.parse::().unwrap(); let mac = "en1: flags=8863 mtu 1500\n\tether 1c:f6:4c:00:00:01\n\tinet 100.70.0.5 netmask 0xffffff00 broadcast 100.70.0.255\n\ utun4: flags=8051 mtu 1280\n\tinet6 fe80::1ef6:4cff:fe5d:30f5%utun4 prefixlen 64 scopeid 0x1f\n\tinet 100.84.144.91 --> 100.84.144.91 netmask 0xffffffff\n\tinet6 fd7a:115c:a1e0::91 prefixlen 128\n\ lo0: flags=8049 mtu 16384\n\tinet 127.0.0.1 netmask 0xff000000\n"; assert_eq!(parse_tunnel_addrs(mac), vec![ip("100.84.144.91"), ip("fd7a:115c:a1e0::91")]); let net_tools = "eth0: flags=4163 mtu 1500\n inet 192.168.1.9 netmask 255.255.255.0 broadcast 192.168.1.255\n\n\ tailscale0: flags=4305 mtu 1280\n inet 100.101.2.3 netmask 255.255.255.255 destination 100.101.2.3\n"; assert_eq!(parse_tunnel_addrs(net_tools), vec![ip("100.101.2.3")]); let iproute = "1: lo inet 127.0.0.1/8 scope host lo\\ valid_lft forever preferred_lft forever\n\ 2: wlan0 inet 100.70.0.5/24 brd 100.70.0.255 scope global dynamic wlan0\\ valid_lft 86000sec\n\ 5: tailscale0 inet 100.101.2.3/32 scope global tailscale0\\ valid_lft forever preferred_lft forever\n\ 5: tailscale0 inet6 fd7a:115c:a1e0::3/128 scope global \\ valid_lft forever preferred_lft forever\n"; assert_eq!(parse_tunnel_addrs(iproute), vec![ip("100.101.2.3"), ip("fd7a:115c:a1e0::3")]); assert!(parse_tunnel_addrs("").is_empty()); } /// Windows: the Tailscale adapter in `ipconfig`, in English and in Traditional Chinese; a /// Wi-Fi with a 100.70.0.5 address isn't it. #[test] fn windows_finds_the_tailscale_adapter_in_ipconfig() { let ip = |s: &str| s.parse::().unwrap(); let en = "\r\nWindows IP Configuration\r\n\r\n\r\nUnknown adapter Tailscale:\r\n\r\n Connection-specific DNS Suffix . : tail1234.ts.net\r\n IPv6 Address. . . . . . . . . . . : fd7a:115c:a1e0::1234\r\n Link-local IPv6 Address . . . . . : fe80::abcd:1%5\r\n IPv4 Address. . . . . . . . . . . : 100.101.2.3\r\n Subnet Mask . . . . . . . . . . . : 255.255.255.255\r\n Default Gateway . . . . . . . . . :\r\n\r\nWireless LAN adapter Wi-Fi:\r\n\r\n IPv4 Address. . . . . . . . . . . : 100.70.0.5(Preferred)\r\n Subnet Mask . . . . . . . . . . . : 255.255.255.0\r\n"; assert_eq!(parse_ipconfig_tunnels(en), vec![ip("fd7a:115c:a1e0::1234"), ip("100.101.2.3")]); let zh = "Windows IP 設定\r\n\r\n未知的介面卡 Tailscale:\r\n\r\n IPv4 位址 . . . . . . . . . . . . : 100.101.2.3\r\n 子網路遮罩 . . . . . . . . . . . : 255.255.255.255\r\n\r\n無線區域網路介面卡 Wi-Fi:\r\n\r\n IPv4 位址 . . . . . . . . . . . . : 192.168.1.9\r\n"; assert_eq!(parse_ipconfig_tunnels(zh), vec![ip("100.101.2.3")]); assert!(parse_ipconfig_tunnels("").is_empty()); } /// A server is reached through Tailscale when its address is a Tailscale one and the route /// to it leaves from the tunnel's address — not when a Wi-Fi hands out 100.x addresses. #[test] fn a_server_is_tailscale_when_the_route_goes_through_the_tunnel() { let ip = |s: &str| s.parse::().unwrap(); let tunnels = [ip("100.84.144.91")]; let via_tunnel = |_| Some(ip("100.84.144.91")); let via_wifi = |_| Some(ip("100.70.0.5")); assert!(tailscale_server(&[ip("100.82.106.34")], &tunnels, via_tunnel)); assert!(!tailscale_server(&[ip("100.70.0.10")], &tunnels, via_wifi), "a Wi-Fi of 100.x addresses"); assert!(!tailscale_server(&[ip("100.82.106.34")], &[], via_tunnel), "no Tailscale here"); assert!(!tailscale_server(&[ip("100.82.106.34"), ip("203.0.113.5")], &tunnels, via_tunnel), "every address, not one"); assert!(!tailscale_server(&[ip("192.168.1.10")], &tunnels, via_tunnel), "a subnet behind the tailnet is not a Tailscale address"); assert!(!tailscale_server(&[], &tunnels, via_tunnel)); // The route really is asked: to this machine itself it leaves from loopback. assert_eq!(source_for(ip("127.0.0.1")), Some(ip("127.0.0.1"))); } /// The front decides plain-or-https by the connection's own two ends: who sent it (`peer`), /// the address of this machine it arrived at, and this machine's tunnel addresses. A plain /// request from a Tailscale address that arrived at a tunnel address goes through; arriving /// anywhere else it is sent to https. #[test] fn the_front_uses_where_the_connection_arrived() { let ip = |s: &str| s.parse::().unwrap(); let dir = std::env::temp_dir().join(format!("anybot-lantls-carry-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let (cert, key) = identity(&dir, &[]).unwrap(); let cfg = config(cert, key).unwrap(); 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 handler: crate::httpd::Handler = Arc::new(|r| crate::httpd::Resp::json(&serde_json::json!({"peer": r.peer}))); std::thread::spawn(move || crate::httpd::serve(inner, handler, alive)); // One plain request through `carry`, as if it came from `peer` (this test's connection // arrives at 127.0.0.1). let ask = |peer: IpAddr| { let l = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = l.local_addr().unwrap(); let cfg = cfg.clone(); let t = std::thread::spawn(move || carry(l.accept().unwrap().0, peer, inner_addr, cfg)); let mut c = TcpStream::connect(addr).unwrap(); c.write_all(format!("GET /x HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n").as_bytes()).unwrap(); let mut out = String::new(); let _ = c.read_to_string(&mut out); t.join().unwrap(); out }; let from_tailnet = ip("100.101.2.3"); // 127.0.0.1 standing for this machine's tunnel address: plain goes through. let out = with_tunnels(&[ip("127.0.0.1")], || ask(from_tailnet)); assert!(out.starts_with("HTTP/1.1 200") && out.contains("100.101.2.3"), "{out}"); // The same connection when that address isn't a tunnel's (a Wi-Fi of 100.x addresses). let out = with_tunnels(&[ip("100.84.144.91")], || ask(from_tailnet)); assert!(out.contains("308"), "{out}"); let out = with_tunnels(&[], || ask(from_tailnet)); assert!(out.contains("308"), "{out}"); on.store(false, Ordering::SeqCst); let _ = std::fs::remove_dir_all(&dir); } }