AnyBot/src/lantls.rs

451 lines
23 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::{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()))
}
/// This machine's Tailscale addresses: those in Tailscale's ranges on a point-to-point (tunnel)
/// interface — macOS's utun, Linux's tailscale0. Read from `ifconfig` (macOS, Linux net-tools)
/// or `ip -o addr` (Linux), at most every 30 seconds. Where neither answers (Windows) there are
/// none, and plain HTTP over Tailscale is sent to https like the rest.
pub fn tunnel_addrs() -> Vec<IpAddr> {
static CACHE: Mutex<Option<(std::time::Instant, Vec<IpAddr>)>> = 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]| std::process::Command::new(cmd).args(args).output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default();
let mut text = run("ifconfig", &[]);
if text.trim().is_empty() {
text = run("ip", &["-o", "addr"]);
}
let v = parse_tunnel_addrs(&text);
*cache = Some((std::time::Instant::now(), v.clone()));
v
}
/// 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<IpAddr> {
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::<u32>().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::<IpAddr>() {
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::<IpAddr>() {
if tailscale_range(ip) {
out.push(ip.to_canonical());
}
}
}
}
}
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());
}
}