AnyBot/src/lantls.rs

726 lines
38 KiB
Rust

// 區網直連的 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::{AtomicBool, 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<u8>, Vec<u8>), 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<String> = 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::<Vec<_>>().join(":")
}
pub fn config(cert: Vec<u8>, key: Vec<u8>) -> Result<Arc<rustls::ServerConfig>, 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()))
}
/// What the interfaces look like now: the text `ifconfig` (macOS, Linux net-tools), `ip -o addr`
/// (Linux) or `ipconfig` (Windows) printed, and this machine's Tailscale addresses in it.
#[derive(Clone, Default)]
pub struct Interfaces {
pub text: String,
pub tunnels: Vec<IpAddr>,
}
/// The interfaces, read at most every 30 seconds — and never on the caller's thread after the
/// first time: an older answer is served while a fresh one is read in the background (設定 asks
/// every frame; on Windows each read starts `ipconfig`).
pub fn interfaces() -> Interfaces {
static CACHE: Snapshot = Snapshot::new();
CACHE.get(Duration::from_secs(30), read_interfaces)
}
/// A value read now and then: the first read on the caller's thread, then the last one served
/// while a new one is read on a thread of its own once it is `max_age` old.
pub struct Snapshot {
value: Mutex<Option<(std::time::Instant, Interfaces)>>,
reading: AtomicBool,
}
impl Snapshot {
pub const fn new() -> Snapshot {
Snapshot { value: Mutex::new(None), reading: AtomicBool::new(false) }
}
pub fn get(&'static self, max_age: Duration, read: fn() -> Interfaces) -> Interfaces {
let cached = self.value.lock().unwrap_or_else(|e| e.into_inner()).clone();
match cached {
Some((at, v)) => {
if at.elapsed() >= max_age && !self.reading.swap(true, Ordering::SeqCst) {
std::thread::spawn(move || {
let fresh = read();
*self.value.lock().unwrap_or_else(|e| e.into_inner()) = Some((std::time::Instant::now(), fresh));
self.reading.store(false, Ordering::SeqCst);
});
}
v
}
None => {
let fresh = read();
*self.value.lock().unwrap_or_else(|e| e.into_inner()) = Some((std::time::Instant::now(), fresh.clone()));
fresh
}
}
}
}
fn read_interfaces() -> Interfaces {
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()
};
if cfg!(windows) {
let text = run("ipconfig", &[]);
let tunnels = parse_ipconfig_tunnels(&text);
return Interfaces { text, tunnels };
}
let text = run("ifconfig", &[]);
let tunnels = parse_tunnel_addrs(&text);
if !tunnels.is_empty() {
return Interfaces { text, tunnels };
}
// No ifconfig, or one that prints the old way (busybox, old net-tools: "inet addr:…"):
// ask `ip` too, and keep its text when ifconfig said nothing.
let ip = run("ip", &["-o", "addr"]);
let tunnels = parse_tunnel_addrs(&ip);
Interfaces { text: if text.trim().is_empty() { ip } else { text }, tunnels }
}
/// This machine's Tailscale addresses (see `parse_tunnel_addrs`, `parse_ipconfig_tunnels`). Where
/// none can be read there are none, and plain HTTP over Tailscale is sent to https like the rest.
pub fn tunnel_addrs() -> Vec<IpAddr> {
#[cfg(test)]
if let Some(v) = TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()).clone() {
return v;
}
interfaces().tunnels
}
/// Tests that need to say which addresses are this machine's tunnel's (one at a time).
#[cfg(test)]
static TEST_TUNNELS: Mutex<Option<Vec<IpAddr>>> = Mutex::new(None);
#[cfg(test)]
pub fn with_tunnels<R>(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<IpAddr> {
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())
}
/// The addresses of a server reached through this machine's Tailscale tunnel, to connect to:
/// every address is a Tailscale one, and every one with a route at all leaves from a tunnel
/// address (`source` says from where). One with no route (IPv6 on a machine without it) is left
/// out — it can't be reached, so nothing goes to it. None: not Tailscale (a 100.x address on a
/// Wi-Fi that hands out 100.64.0.0/10 goes out of the Wi-Fi), or nothing left to connect to.
pub fn tunnel_route(addrs: &[IpAddr], tunnels: &[IpAddr], source: impl Fn(IpAddr) -> Option<IpAddr>) -> Option<Vec<IpAddr>> {
let mut keep = vec![];
for &a in addrs {
if !tailscale_range(a) {
return None;
}
match source(a) {
None => {}
Some(s) if tunnels.contains(&s.to_canonical()) => keep.push(a),
Some(_) => return None,
}
}
(!keep.is_empty()).then_some(keep)
}
/// 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<IpAddr> {
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::<IpAddr>() {
if tunnel && tailscale_range(ip) {
out.push(ip.to_canonical());
}
}
}
out.dedup();
out
}
/// The Tailscale addresses in `ifconfig` output (an interface starts at the left margin, its
/// addresses indented under it) or `ip -o addr` output (one address a line, the interface's name
/// second). An interface is Tailscale's when it is named tailscale… (Linux), or when it is a
/// point-to-point tunnel that also carries a Tailscale IPv6 address (fd7a:115c:a1e0::/48 —
/// macOS's utun): a 100.64.0.0/10 address alone isn't, since PPPoE, a phone's carrier NAT and
/// Cloudflare WARP use that range too. `ip -o addr` has no flags: tailscale… or the IPv6 address.
fn parse_tunnel_addrs(text: &str) -> Vec<IpAddr> {
// (interface, point-to-point, its Tailscale-range addresses)
let mut ifaces: Vec<(String, bool, Vec<IpAddr>)> = vec![];
let mut at = |name: &str, p2p: bool| -> usize {
match ifaces.iter().position(|(n, _, _)| n == name) {
Some(i) => i,
None => {
ifaces.push((name.to_string(), p2p, vec![]));
ifaces.len() - 1
}
}
};
let mut current: Option<usize> = None;
let mut found: Vec<(usize, IpAddr)> = vec![];
for line in text.lines() {
let words: Vec<&str> = line.split_whitespace().collect();
let family = |w: &&str| *w == "inet" || *w == "inet6";
let address = |w: &str| w.split(['%', '/']).next().unwrap_or(w).parse::<IpAddr>().ok();
// `ip -o addr`: "5: tailscale0 inet 100.101.2.3/32 scope global tailscale0 …".
if words.first().and_then(|w| w.strip_suffix(':')).is_some_and(|n| n.parse::<u32>().is_ok()) {
if let (Some(name), Some(i)) = (words.get(1), words.iter().position(family)) {
let i_face = at(name.trim_end_matches(':'), false);
if let Some(ip) = words.get(i + 1).and_then(|w| address(w)) {
found.push((i_face, ip));
}
}
continue;
}
if !line.is_empty() && !line.starts_with(char::is_whitespace) {
let name = line.split(':').next().unwrap_or("").trim();
current = Some(at(name, line.contains("POINTOPOINT")));
continue;
}
if let (Some(i_face), Some(w), Some(addr)) = (current, words.first(), words.get(1)) {
if family(w) {
if let Some(ip) = address(addr) {
found.push((i_face, ip));
}
}
}
}
for (i, ip) in found {
if tailscale_range(ip) {
ifaces[i].2.push(ip.to_canonical());
}
}
let ula = |ip: &IpAddr| matches!(ip, IpAddr::V6(_));
let mut out = vec![];
for (name, p2p, addrs) in ifaces {
let has_ula = addrs.iter().any(ula);
if name.starts_with("tailscale") || (has_ula && (p2p || !text.contains("flags="))) {
out.extend(addrs);
}
}
out.dedup();
out
}
struct Slot(Arc<AtomicUsize>);
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<rustls::ServerConfig>, alive: Arc<dyn Fn() -> 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<rustls::ServerConfig>) {
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<rustls::ServerConfig>) {
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<dyn Fn() -> 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::<IpAddr>().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::<IpAddr>().unwrap();
let mac = "en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> 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<UP,POINTOPOINT,RUNNING,MULTICAST> 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<UP,LOOPBACK,RUNNING,MULTICAST> 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<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500\n inet 192.168.1.9 netmask 255.255.255.0 broadcast 192.168.1.255\n\n\
tailscale0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> 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());
// Other tunnels in the same range aren't Tailscale: PPPoE or a phone's carrier NAT
// (POINTOPOINT, 100.x, no Tailscale IPv6), Cloudflare WARP (utun, 100.96.x, its own IPv6),
// and on `ip -o addr` a /32 that isn't on tailscale0 and has no Tailscale IPv6.
let others = "ppp0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500\n\tinet 100.72.9.1 --> 100.64.0.1 netmask 0xffffffff\n\
utun7: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1280\n\tinet 100.96.0.5 --> 100.96.0.5 netmask 0xffffffff\n\tinet6 2606:4700:110:8a1c::5 prefixlen 128\n";
assert!(parse_tunnel_addrs(others).is_empty(), "{:?}", parse_tunnel_addrs(others));
let iproute_others = "3: wwan0 inet 100.72.9.1/32 scope global wwan0\\ valid_lft forever preferred_lft forever\n";
assert!(parse_tunnel_addrs(iproute_others).is_empty());
// busybox / old net-tools print "inet addr:…": nothing here, so ip -o addr is asked too.
let busybox = "tailscale0 Link encap:UNSPEC HWaddr 00-00\n inet addr:100.101.2.3 P-t-P:100.101.2.3 Mask:255.255.255.255\n UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1280\n";
assert!(parse_tunnel_addrs(busybox).is_empty());
}
/// The interfaces are read on the caller's thread only the first time; after that an old
/// answer comes back at once and the new one is read on a thread of its own (設定 asks every
/// frame; a read is a program started).
#[test]
fn interfaces_are_read_off_the_callers_thread_after_the_first_time() {
static SNAP: Snapshot = Snapshot::new();
static READS: AtomicUsize = AtomicUsize::new(0);
fn slow() -> Interfaces {
std::thread::sleep(Duration::from_millis(300));
let n = READS.fetch_add(1, Ordering::SeqCst) + 1;
Interfaces { text: format!("read {n}"), tunnels: vec![] }
}
assert_eq!(SNAP.get(Duration::from_millis(50), slow).text, "read 1", "the first read is waited for");
std::thread::sleep(Duration::from_millis(80));
let t = std::time::Instant::now();
assert_eq!(SNAP.get(Duration::from_millis(50), slow).text, "read 1", "an old answer, at once");
assert!(t.elapsed() < Duration::from_millis(150), "waited {:?} on the caller's thread", t.elapsed());
let t = std::time::Instant::now();
while SNAP.get(Duration::from_secs(60), slow).text != "read 2" {
assert!(t.elapsed() < Duration::from_secs(3), "the new answer never came");
std::thread::sleep(Duration::from_millis(20));
}
}
/// 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::<IpAddr>().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::<IpAddr>().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_eq!(tunnel_route(&[ip("100.82.106.34")], &tunnels, via_tunnel), Some(vec![ip("100.82.106.34")]));
assert_eq!(tunnel_route(&[ip("100.70.0.10")], &tunnels, via_wifi), None, "a Wi-Fi of 100.x addresses");
assert_eq!(tunnel_route(&[ip("100.82.106.34")], &[], via_tunnel), None, "no Tailscale here");
assert_eq!(tunnel_route(&[ip("100.82.106.34"), ip("203.0.113.5")], &tunnels, via_tunnel), None, "every address, not one");
assert_eq!(tunnel_route(&[ip("192.168.1.10")], &tunnels, via_tunnel), None, "a subnet behind the tailnet is not a Tailscale address");
assert_eq!(tunnel_route(&[], &tunnels, via_tunnel), None);
// A machine without IPv6: the server's IPv6 address has no route at all, so it is left
// out and the IPv4 one is used (it used to refuse the server).
let no_v6 = |a: IpAddr| if a.is_ipv6() { None } else { Some(ip("100.84.144.91")) };
assert_eq!(tunnel_route(&[ip("fd7a:115c:a1e0::5"), ip("100.82.106.34")], &tunnels, no_v6), Some(vec![ip("100.82.106.34")]));
assert_eq!(tunnel_route(&[ip("fd7a:115c:a1e0::5")], &tunnels, no_v6), None, "nothing left to connect to");
// 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::<IpAddr>().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<dyn Fn() -> 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);
}
}