From a275547268bd370599f6f3fee57d5d20e671f2fe Mon Sep 17 00:00:00 2001 From: i2cjak Date: Tue, 24 Nov 2026 02:15:49 -0500 Subject: [PATCH 1/2] web: support Web UI hosting on Linux, macOS, and Windows --- native/host/src/net/devicespage.rs | 2 - native/host/src/net/listener.rs | 8 +- native/host/src/net/start.rs | 1 - native/host/src/net/tailnet.rs | 277 ++++++++- native/host/src/net/webingress.rs | 210 ++++++- native/host/src/net/webprovision.rs | 860 +++++++++++++++++++++++++--- native/host/src/net/webtransport.rs | 208 ++++++- native/host/src/plat/mod.rs | 58 ++ native/host/src/plat/windows.rs | 161 ++++++ native/host/src/present/settings.rs | 21 +- native/host/src/proc.rs | 2 +- 11 files changed, 1667 insertions(+), 141 deletions(-) diff --git a/native/host/src/net/devicespage.rs b/native/host/src/net/devicespage.rs index ef1f7dc098..3893825a66 100644 --- a/native/host/src/net/devicespage.rs +++ b/native/host/src/net/devicespage.rs @@ -48,11 +48,9 @@ fn browser_rows(list: &Value, current_id: &str) -> Value { } async fn browser_action(hub: &Hub, action: &str, value: &str) -> Result<(), &'static str> { - #[cfg(target_os = "linux")] if action == "device-web-setup" { return super::listener::webprovision::request_setup(&hub.cfg.home, value); } - if action == "device-web-setup" { return Err("web setup unavailable on this system"); } let reg = super::start::registry(&hub.cfg.home).ok_or("registry unavailable")?; if action == "device-web-access" { if !matches!(value, "0" | "1") { return Err("invalid access setting") } diff --git a/native/host/src/net/listener.rs b/native/host/src/net/listener.rs index dc77614988..53a2d0b96a 100644 --- a/native/host/src/net/listener.rs +++ b/native/host/src/net/listener.rs @@ -38,12 +38,12 @@ pub trait Tailscale: Send + Sync { pub struct Cli; async fn run(args: Vec) -> String { if crate::copy::on() { return String::new() } - match tokio::time::timeout(Duration::from_secs(5), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(&args).stderr(std::process::Stdio::null()).kill_on_drop(true).output()).await { + match tokio::time::timeout(Duration::from_secs(5), crate::proc::tokio_cmd(crate::proc::Kind::Net, tailnet::tailscale_program()).args(&args).stderr(std::process::Stdio::null()).kill_on_drop(true).output()).await { Ok(Ok(o)) if o.status.success() => String::from_utf8_lossy(&o.stdout).into_owned(), _ => String::new() } } async fn run_ok(args: Vec) -> bool { if crate::copy::on() { return false } - matches!(tokio::time::timeout(Duration::from_secs(15), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(&args).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).kill_on_drop(true).status()).await, Ok(Ok(s)) if s.success()) + matches!(tokio::time::timeout(Duration::from_secs(15), crate::proc::tokio_cmd(crate::proc::Kind::Net, tailnet::tailscale_program()).args(&args).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).kill_on_drop(true).status()).await, Ok(Ok(s)) if s.success()) } impl Tailscale for Cli { fn serve(&self, port: u16, https: u16) -> Fut { Box::pin(async move { run_ok(vec!["serve".into(), "--bg".into(), format!("--https={https}"), format!("http://127.0.0.1:{port}")]).await }) } @@ -334,13 +334,9 @@ mod tests { } } -#[cfg(any(target_os = "linux", target_os = "macos"))] #[path = "webtransport.rs"] pub(crate) mod webtransport; -#[cfg(target_os = "linux")] #[path = "webprovision.rs"] pub(crate) mod webprovision; - -#[cfg(target_os = "linux")] #[path = "webprobe.rs"] pub(crate) mod webprobe; diff --git a/native/host/src/net/start.rs b/native/host/src/net/start.rs index cd212421f7..2dac89a464 100644 --- a/native/host/src/net/start.rs +++ b/native/host/src/net/start.rs @@ -95,7 +95,6 @@ pub fn start_full(hub: &Arc, host: &str, port: u16, tailnet: bool, https: b // the reverse link: polls to the linked machines that cannot reach this one, and the route for those that poll it super::alwayson::tunnel::install(hub, peering.clone()); if tailnet { - #[cfg(target_os = "linux")] { let browser_hub = hub.clone(); tokio::spawn(async move { super::listener::webprovision::monitor(browser_hub, &super::listener::Cli).await; }); diff --git a/native/host/src/net/tailnet.rs b/native/host/src/net/tailnet.rs index 6b358f4fed..fe47f8fca9 100644 --- a/native/host/src/net/tailnet.rs +++ b/native/host/src/net/tailnet.rs @@ -120,10 +120,185 @@ pub async fn find(status: &str, port: u16, extra: &str) -> Value { } pub async fn status_json() -> String { if crate::copy::on() { return String::new() } - match tokio::time::timeout(std::time::Duration::from_secs(10), crate::proc::tokio_cmd(crate::proc::Kind::Net, "tailscale").args(["status", "--json"]).stderr(std::process::Stdio::null()).kill_on_drop(true).output()).await { + match tokio::time::timeout(std::time::Duration::from_secs(10), crate::proc::tokio_cmd(crate::proc::Kind::Net, tailscale_program()).args(["status", "--json"]).stderr(std::process::Stdio::null()).kill_on_drop(true).output()).await { Ok(Ok(o)) if o.status.success() => String::from_utf8_lossy(&o.stdout).into_owned(), _ => String::new() } } +fn join_windows_path(dir: &str, suffix: &str) -> std::path::PathBuf { + let trimmed = dir.trim_end_matches(['\\', '/']); + std::path::PathBuf::from(format!(r"{trimmed}\{suffix}")) +} + +/// Locate the Tailscale CLI on Linux, macOS (App Store / standalone app and Homebrew/CLI), or Windows. +pub fn resolve_tailscale_in( + os: &str, + path_env: Option<&str>, + program_files: Option<&str>, + program_files_x86: Option<&str>, + home_dir: Option<&str>, + has_macos_brew_socket: bool, + is_executable: impl Fn(&std::path::Path) -> bool, +) -> Option { + let mut candidates: Vec = Vec::new(); + match os { + "linux" => { + candidates.push("/usr/bin/tailscale".into()); + candidates.push("/usr/local/bin/tailscale".into()); + if let Some(path) = path_env { + for dir in path.split(':').filter(|d| !d.is_empty()) { + candidates.push(std::path::Path::new(dir).join("tailscale")); + } + } + } + "macos" => { + let mut app_candidates = vec![std::path::PathBuf::from( + "/Applications/Tailscale.app/Contents/MacOS/Tailscale", + )]; + if let Some(home) = home_dir.map(str::trim).filter(|h| !h.is_empty()) { + app_candidates.push( + std::path::Path::new(home.trim_end_matches('/')) + .join("Applications/Tailscale.app/Contents/MacOS/Tailscale"), + ); + } + let mut cli_candidates = Vec::new(); + if let Some(path) = path_env { + for dir in path.split(':').filter(|d| !d.is_empty()) { + cli_candidates.push(std::path::Path::new(dir).join("tailscale")); + } + } + cli_candidates.push("/opt/homebrew/bin/tailscale".into()); + cli_candidates.push("/usr/local/bin/tailscale".into()); + if has_macos_brew_socket { + candidates.extend(cli_candidates); + candidates.extend(app_candidates); + } else { + candidates.extend(app_candidates); + candidates.extend(cli_candidates); + } + } + "windows" => { + if let Some(pf) = program_files.map(str::trim).filter(|s| !s.is_empty()) { + candidates.push(join_windows_path(pf, r"Tailscale\tailscale.exe")); + } + candidates.push(std::path::PathBuf::from(r"C:\Program Files\Tailscale\tailscale.exe")); + if let Some(pf86) = program_files_x86.map(str::trim).filter(|s| !s.is_empty()) { + candidates.push(join_windows_path(pf86, r"Tailscale\tailscale.exe")); + } + if let Some(path) = path_env { + for dir in path.split(';').filter(|d| !d.is_empty()) { + candidates.push(join_windows_path(dir, "tailscale.exe")); + } + } + } + _ => { + if let Some(path) = path_env { + for dir in std::env::split_paths(path) { + candidates.push(dir.join("tailscale")); + } + } + } + } + candidates.into_iter().find(|p| is_executable(p)) +} + +/// Locate the system curl executable for HTTPS probe verification. +pub fn resolve_curl_in( + os: &str, + path_env: Option<&str>, + system_root: Option<&str>, + is_executable: impl Fn(&std::path::Path) -> bool, +) -> Option { + let mut candidates: Vec = Vec::new(); + match os { + "linux" => { + candidates.push("/usr/bin/curl".into()); + candidates.push("/bin/curl".into()); + if let Some(path) = path_env { + for dir in path.split(':').filter(|d| !d.is_empty()) { + candidates.push(std::path::Path::new(dir).join("curl")); + } + } + } + "macos" => { + candidates.push("/usr/bin/curl".into()); + if let Some(path) = path_env { + for dir in path.split(':').filter(|d| !d.is_empty()) { + candidates.push(std::path::Path::new(dir).join("curl")); + } + } + } + "windows" => { + let root = system_root + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or(r"C:\Windows"); + candidates.push(join_windows_path(root, r"System32\curl.exe")); + if let Some(path) = path_env { + for dir in path.split(';').filter(|d| !d.is_empty()) { + candidates.push(join_windows_path(dir, "curl.exe")); + } + } + } + _ => { + if let Some(path) = path_env { + for dir in std::env::split_paths(path) { + candidates.push(dir.join("curl")); + } + } + } + } + candidates.into_iter().find(|p| is_executable(p)) +} + +pub fn macos_has_brew_socket() -> bool { + #[cfg(unix)] + { + use crate::plat::fs::FileTypeExt; + std::fs::metadata("/var/run/tailscaled.socket").is_ok_and(|m| m.file_type().is_socket()) + } + #[cfg(not(unix))] + { + false + } +} + +fn is_runnable(path: &std::path::Path) -> bool { + std::fs::metadata(path).is_ok_and(|m| crate::plat::fs::runnable(&m)) +} + +pub fn tailscale_cli() -> Option { + let path_env = std::env::var("PATH").ok(); + let pf = std::env::var("ProgramFiles").ok(); + let pf86 = std::env::var("ProgramFiles(x86)").ok(); + let home = std::env::var("HOME").ok(); + resolve_tailscale_in( + std::env::consts::OS, + path_env.as_deref(), + pf.as_deref(), + pf86.as_deref(), + home.as_deref(), + macos_has_brew_socket(), + is_runnable, + ) +} + +pub fn tailscale_program() -> std::ffi::OsString { + tailscale_cli() + .map(|p| p.into_os_string()) + .unwrap_or_else(|| std::ffi::OsString::from("tailscale")) +} + +pub fn curl_cli() -> Option { + let path_env = std::env::var("PATH").ok(); + let system_root = std::env::var("SystemRoot").ok(); + resolve_curl_in( + std::env::consts::OS, + path_env.as_deref(), + system_root.as_deref(), + is_runnable, + ) +} + #[cfg(test)] mod tests { use super::*; @@ -208,4 +383,104 @@ mod tests { let j = r#"{"Web":{"a.ts.net:443":{"Handlers":{"/":{"Proxy":"http://127.0.0.1:3773"}}},"a.ts.net:8443":{"Handlers":{"/":{"Proxy":"http://127.0.0.1:3787"}}}}}"#; assert_eq!(serve(j, "3787"), "https://a.ts.net:8443"); } + + #[test] fn resolve_tailscale_and_curl_across_platforms() { + use std::path::Path; + let has = |targets: &[&str]| { + let set: Vec = targets.iter().map(|s| (*s).to_string()).collect(); + move |p: &Path| set.iter().any(|t| t == p.to_string_lossy().as_ref()) + }; + assert_eq!( + resolve_tailscale_in("linux", Some("/opt/bin"), None, None, None, false, has(&["/usr/bin/tailscale"])), + Some(Path::new("/usr/bin/tailscale").to_path_buf()) + ); + assert_eq!( + resolve_tailscale_in("linux", Some("/opt/bin"), None, None, None, false, has(&["/opt/bin/tailscale"])), + Some(Path::new("/opt/bin/tailscale").to_path_buf()) + ); + // macOS App Store / standalone app preferred when no brew socket + assert_eq!( + resolve_tailscale_in( + "macos", + Some("/opt/homebrew/bin:/usr/local/bin"), + None, + None, + Some("/Users/alex"), + false, + has(&["/Applications/Tailscale.app/Contents/MacOS/Tailscale", "/opt/homebrew/bin/tailscale"]) + ), + Some(Path::new("/Applications/Tailscale.app/Contents/MacOS/Tailscale").to_path_buf()) + ); + // macOS Homebrew CLI preferred when brew socket is active + assert_eq!( + resolve_tailscale_in( + "macos", + Some("/opt/homebrew/bin:/usr/local/bin"), + None, + None, + Some("/Users/alex"), + true, + has(&["/Applications/Tailscale.app/Contents/MacOS/Tailscale", "/opt/homebrew/bin/tailscale"]) + ), + Some(Path::new("/opt/homebrew/bin/tailscale").to_path_buf()) + ); + assert_eq!( + resolve_tailscale_in( + "macos", + None, + None, + None, + Some("/Users/alex"), + false, + has(&["/Users/alex/Applications/Tailscale.app/Contents/MacOS/Tailscale"]) + ), + Some(Path::new("/Users/alex/Applications/Tailscale.app/Contents/MacOS/Tailscale").to_path_buf()) + ); + // Windows ProgramFiles and PATH + assert_eq!( + resolve_tailscale_in( + "windows", + Some(r"C:\Tools"), + Some(r"D:\Programs"), + None, + None, + false, + has(&[r"D:\Programs\Tailscale\tailscale.exe", r"C:\Tools\tailscale.exe"]) + ), + Some(Path::new(r"D:\Programs\Tailscale\tailscale.exe").to_path_buf()) + ); + assert_eq!( + resolve_tailscale_in( + "windows", + Some(r"C:\Tools"), + None, + None, + None, + false, + has(&[r"C:\Program Files\Tailscale\tailscale.exe"]) + ), + Some(Path::new(r"C:\Program Files\Tailscale\tailscale.exe").to_path_buf()) + ); + assert_eq!( + resolve_tailscale_in("windows", Some(r"C:\Tools"), None, None, None, false, has(&[r"C:\Tools\tailscale.exe"])), + Some(Path::new(r"C:\Tools\tailscale.exe").to_path_buf()) + ); + + assert_eq!( + resolve_curl_in("linux", None, None, has(&["/usr/bin/curl"])), + Some(Path::new("/usr/bin/curl").to_path_buf()) + ); + assert_eq!( + resolve_curl_in("macos", None, None, has(&["/usr/bin/curl"])), + Some(Path::new("/usr/bin/curl").to_path_buf()) + ); + assert_eq!( + resolve_curl_in("windows", Some(r"C:\Tools"), Some(r"C:\Windows"), has(&[r"C:\Windows\System32\curl.exe"])), + Some(Path::new(r"C:\Windows\System32\curl.exe").to_path_buf()) + ); + assert_eq!( + resolve_curl_in("windows", Some(r"C:\Tools"), Some(r"C:\Windows"), has(&[r"C:\Tools\curl.exe"])), + Some(Path::new(r"C:\Tools\curl.exe").to_path_buf()) + ); + } } diff --git a/native/host/src/net/webingress.rs b/native/host/src/net/webingress.rs index 2917c40e66..45f3c7d9ab 100644 --- a/native/host/src/net/webingress.rs +++ b/native/host/src/net/webingress.rs @@ -368,6 +368,154 @@ mod tests { assert!(!ingress.accepts(&request, upgrade)); } } + + #[test] + fn loopback_proxy_normalizes_authority_and_rejects_mismatch() { + let authority = "bp.example.ts.net:8443"; + for host in ["127.0.0.1:49231", "localhost:49231", authority] { + let mut req = Req::new( + "GET", + "/", + vec![ + ("Host".into(), host.into()), + ("X-Forwarded-Host".into(), authority.into()), + ("X-Forwarded-Proto".into(), "https".into()), + ], + ); + assert!(normalize_proxy_authority(&mut req, authority, ProxyMode::Loopback(49231)), "{host}"); + assert_eq!(single_header(&req, "host"), Some(authority)); + } + for bad_host in ["127.0.0.1:9999", "evil.example.com", "localhost"] { + let mut req = Req::new( + "GET", + "/", + vec![ + ("Host".into(), bad_host.into()), + ("X-Forwarded-Host".into(), authority.into()), + ("X-Forwarded-Proto".into(), "https".into()), + ], + ); + assert!(!normalize_proxy_authority(&mut req, authority, ProxyMode::Loopback(49231)), "{bad_host}"); + } + } + + #[tokio::test] + async fn loopback_proxy_verifies_setup_probe_and_enforces_pairing_and_funnel_rejection() { + use serde_json::json; + use std::sync::Arc; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let dir = crate::plat::tmp::dir("webingress-loopback"); + std::fs::write(dir.join("token"), "tok").unwrap(); + std::fs::write( + dir.join("events.jsonl"), + "{\"$\":\"SettingSet\",\"key\":\"web.enabled\",\"value\":\"1\",\"at\":1700000040}\n", + ) + .unwrap(); + let cfg = crate::hub::Cfg { + home: dir.to_path_buf(), + version: "0.16.4".into(), + commit: "test".into(), + listen: "127.0.0.1:0".into(), + os: "windows".into(), + arch: "x64".into(), + }; + let hub = crate::hub::Hub::start(cfg, Arc::new(crate::presenter::Canned { reply: json!({}) })) + .await + .unwrap(); + let (reg, _routes) = crate::net::start::open(&hub.cfg.home, "127.0.0.1", 0).unwrap(); + let authority = "bp.example.ts.net:8443"; + let backend_port = 49231u16; + + let send_loopback = |raw_req: String| { + let hub = hub.clone(); + async move { + let (mut client, server) = tokio::io::duplex(16 * 1024); + let srv = tokio::spawn(async move { serve_loopback(hub, server, authority, backend_port).await }); + client.write_all(raw_req.as_bytes()).await.unwrap(); + let mut resp = Vec::new(); + client.read_to_end(&mut resp).await.unwrap(); + let _ = srv.await; + String::from_utf8_lossy(&resp).into_owned() + } + }; + + // Direct mode must not answer setup probe + let probe = super::super::webprobe::Probe::start(&hub.cfg.home, authority); + let nonce = probe.header().trim_start_matches("X-Backplane-Setup: ").trim().to_owned(); + let (mut client, server) = tokio::io::duplex(8 * 1024); + let h2 = hub.clone(); + let srv = tokio::spawn(async move { serve(h2, server, authority).await }); + client + .write_all( + format!( + "GET /auth/web/setup HTTP/1.1\r\nHost: {authority}\r\nX-Backplane-Setup: {nonce}\r\n\r\n" + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut direct_resp = Vec::new(); + client.read_to_end(&mut direct_resp).await.unwrap(); + let _ = srv.await; + assert!(String::from_utf8_lossy(&direct_resp).starts_with("HTTP/1.1 404 ")); + assert!(!probe.consumed()); + + // Funnel header on setup probe must be rejected and must not consume nonce + let funnel_resp = send_loopback(format!( + "GET /auth/web/setup HTTP/1.1\r\nHost: 127.0.0.1:{backend_port}\r\n\ + X-Forwarded-Host: {authority}\r\nX-Forwarded-Proto: https\r\n\ + Tailscale-Funnel-Request: true\r\nX-Backplane-Setup: {nonce}\r\n\r\n" + )) + .await; + assert!(funnel_resp.starts_with("HTTP/1.1 404 "), "{funnel_resp}"); + assert!(!probe.consumed()); + + // Valid loopback setup probe passes once, then fails on replay + let ok_resp = send_loopback(format!( + "GET /auth/web/setup HTTP/1.1\r\nHost: 127.0.0.1:{backend_port}\r\n\ + X-Forwarded-Host: {authority}\r\nX-Forwarded-Proto: https\r\n\ + X-Backplane-Setup: {nonce}\r\n\r\n" + )) + .await; + assert!(ok_resp.starts_with("HTTP/1.1 204 "), "{ok_resp}"); + assert!(probe.consumed()); + let replay_resp = send_loopback(format!( + "GET /auth/web/setup HTTP/1.1\r\nHost: 127.0.0.1:{backend_port}\r\n\ + X-Forwarded-Host: {authority}\r\nX-Forwarded-Proto: https\r\n\ + X-Backplane-Setup: {nonce}\r\n\r\n" + )) + .await; + assert!(replay_resp.starts_with("HTTP/1.1 404 "), "{replay_resp}"); + + // Funnel header on regular route is rejected with 401 + let regular_funnel = send_loopback(format!( + "GET /auth/web/info HTTP/1.1\r\nHost: 127.0.0.1:{backend_port}\r\n\ + X-Forwarded-Host: {authority}\r\nX-Forwarded-Proto: https\r\n\ + Tailscale-User-Login: person@example.com\r\nTailscale-Funnel-Request: 1\r\n\r\n" + )) + .await; + assert!(regular_funnel.starts_with("HTTP/1.1 401 "), "{regular_funnel}"); + + // Unpaired /assets/app.js is 401; paired succeeds + let unpaired = send_loopback(format!( + "GET /assets/app.js HTTP/1.1\r\nHost: 127.0.0.1:{backend_port}\r\n\ + X-Forwarded-Host: {authority}\r\nX-Forwarded-Proto: https\r\n\ + Tailscale-User-Login: person@example.com\r\n\r\n" + )) + .await; + assert!(unpaired.starts_with("HTTP/1.1 401 "), "{unpaired}"); + + let (req_json, poll_cookie) = reg.browser_request("person@example.com", "Win Browser").unwrap(); + assert!(reg.browser_decide(req_json["id"].as_str().unwrap(), true)); + let session_cookie = reg.browser_wait("person@example.com", &poll_cookie).await.unwrap().unwrap(); + let paired = send_loopback(format!( + "GET /assets/app.js HTTP/1.1\r\nHost: 127.0.0.1:{backend_port}\r\n\ + X-Forwarded-Host: {authority}\r\nX-Forwarded-Proto: https\r\n\ + Tailscale-User-Login: person@example.com\r\nCookie: __Host-bp_web={session_cookie}\r\n\r\n" + )) + .await; + assert!(paired.starts_with("HTTP/1.1 200 "), "{paired}"); + } } const SECURITY_HEADERS: &str = concat!( @@ -474,19 +622,50 @@ async fn pair_response(hub: &crate::hub::Hub, req: &Req, login: &str) -> Vec pub(crate) async fn serve(hub: std::sync::Arc, stream: S, authority: &str) -> anyhow::Result<()> where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send { - serve_request(hub, stream, authority, false).await + serve_request(hub, stream, authority, ProxyMode::Direct).await } /// Called only after the transport authenticates the Unix peer. #[cfg(unix)] pub(crate) async fn serve_unix(hub: std::sync::Arc, stream: tokio::net::UnixStream, authority: &str) -> anyhow::Result<()> { - serve_request(hub, stream, authority, true).await + serve_request(hub, stream, authority, ProxyMode::Unix).await } -fn normalize_unix_authority(req: &mut Req, authority: &str) -> bool { - if single_header(req, "host") != Some("localhost") +/// Called only after the transport verifies the loopback proxy peer. +pub(crate) async fn serve_loopback( + hub: std::sync::Arc, + stream: S, + authority: &str, + backend_port: u16, +) -> anyhow::Result<()> +where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send { + serve_request(hub, stream, authority, ProxyMode::Loopback(backend_port)).await +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ProxyMode { + Direct, + Unix, + Loopback(u16), +} + +fn normalize_proxy_authority(req: &mut Req, authority: &str, mode: ProxyMode) -> bool { + let host_ok = match mode { + ProxyMode::Direct => return true, + ProxyMode::Unix => single_header(req, "host") == Some("localhost"), + ProxyMode::Loopback(port) => { + let ip_host = format!("127.0.0.1:{port}"); + let local_host = format!("localhost:{port}"); + matches!( + single_header(req, "host"), + Some(h) if h == authority || h == ip_host || h == local_host + ) + } + }; + if !host_ok || single_header(req, "x-forwarded-host") != Some(authority) - || single_header(req, "x-forwarded-proto") != Some("https") { + || single_header(req, "x-forwarded-proto") != Some("https") + { return false; } for (name, value) in &mut req.headers { @@ -495,7 +674,12 @@ fn normalize_unix_authority(req: &mut Req, authority: &str) -> bool { true } -async fn serve_request(hub: std::sync::Arc, stream: S, authority: &str, unix_proxy: bool) +#[cfg(test)] +fn normalize_unix_authority(req: &mut Req, authority: &str) -> bool { + normalize_proxy_authority(req, authority, ProxyMode::Unix) +} + +async fn serve_request(hub: std::sync::Arc, stream: S, authority: &str, mode: ProxyMode) -> anyhow::Result<()> where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send { use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -547,16 +731,18 @@ where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send { let reply = if hub.setting("web.enabled").await.as_deref() != Some("1") { route_json("404 Not Found", json!({})) } else if req.route() == "/auth/web/setup" { - #[cfg(target_os = "linux")] - let ok = unix_proxy && req.method == "GET" && req.target == "/auth/web/setup" - && normalize_unix_authority(&mut req, authority) + let ok = mode != ProxyMode::Direct + && req.method == "GET" + && req.target == "/auth/web/setup" + && normalize_proxy_authority(&mut req, authority, mode) && !req.headers.iter().any(|(name, _)| name.eq_ignore_ascii_case("tailscale-funnel-request")) && single_header(&req, "x-backplane-setup").is_some_and(|n| super::webprobe::consume(&hub.cfg.home, authority, n)); - #[cfg(not(target_os = "linux"))] - let ok = false; crate::wire::response_for(if ok { "204 No Content" } else { "404 Not Found" }, "text/plain", SECURITY_HEADERS, &[]) - } else if (unix_proxy && !normalize_unix_authority(&mut req, authority)) || !ingress.accepts(&req, upgrade) || login == "tagged-devices" { + } else if req.headers.iter().any(|(name, _)| name.eq_ignore_ascii_case("tailscale-funnel-request")) + || !normalize_proxy_authority(&mut req, authority, mode) + || !ingress.accepts(&req, upgrade) + || login == "tagged-devices" { route_json("401 Unauthorized", json!({"state":"unauthorized"})) } else if req.target.split_once('?').is_some_and(|(_, query)| query.split('&').any(|field| { let key = field.split('=').next().unwrap_or(""); diff --git a/native/host/src/net/webprovision.rs b/native/host/src/net/webprovision.rs index 4446b124a8..1c1cea6092 100644 --- a/native/host/src/net/webprovision.rs +++ b/native/host/src/net/webprovision.rs @@ -71,6 +71,7 @@ pub fn mapping_status(raw: &str, authority: &str, proxy: &str) -> Mapping { /// Every directory used to resolve the persistent Serve target must be /// protected from replacement by other accounts, including after hub exit. +#[cfg(unix)] pub fn protected_directory(path: &std::path::Path) -> std::io::Result<()> { use std::{io, os::unix::fs::MetadataExt}; let uid = crate::plat::effective_uid(); @@ -96,22 +97,77 @@ pub fn protected_directory(path: &std::path::Path) -> std::io::Result<()> { Ok(()) } +#[cfg(windows)] +pub fn protected_directory(path: &std::path::Path) -> std::io::Result<()> { + use std::io; + if !path.is_absolute() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "canonical absolute directory required", + )); + } + let meta = std::fs::symlink_metadata(path)?; + if !meta.is_dir() || !crate::plat::fs::no_link_on(path)? { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "private socket path required", + )); + } + Ok(()) +} + +fn ensure_protected_directory(directory: &std::path::Path) -> std::io::Result { + #[cfg(unix)] + { + use std::os::unix::fs::{DirBuilderExt, MetadataExt}; + let _ = std::fs::DirBuilder::new().mode(0o700).create(directory); + let canonical = crate::plat::fs::canonicalize(directory)?; + let meta = std::fs::symlink_metadata(&canonical)?; + if !meta.is_dir() || meta.uid() != crate::plat::effective_uid() || meta.mode() & 0o777 != 0o700 { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "private socket path required", + )); + } + Ok(canonical) + } + #[cfg(not(unix))] + { + let _ = std::fs::create_dir(directory); + let canonical = crate::plat::fs::canonicalize(directory)?; + protected_directory(&canonical)?; + Ok(canonical) + } +} + /// Read the kernel identity of the daemon at the system LocalAPI socket. /// No HTTP request, login header, or hub credential is sent to this socket. +#[cfg(unix)] pub async fn system_proxy_identity() -> std::io::Result { use std::{io, time::Duration}; if crate::copy::on() { return Err(io::Error::new(io::ErrorKind::PermissionDenied, "copy run")); } + #[cfg(target_os = "linux")] + let sock_path = "/run/tailscale/tailscaled.sock"; + #[cfg(target_os = "macos")] + let sock_path = "/var/run/tailscaled.socket"; + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + return Err(io::Error::new(io::ErrorKind::Unsupported, "unix daemon socket unsupported")); + let stream = tokio::time::timeout( Duration::from_secs(2), - tokio::net::UnixStream::connect("/run/tailscale/tailscaled.sock"), + tokio::net::UnixStream::connect(sock_path), ) .await??; let peer = stream.peer_cred()?; + #[cfg(target_os = "linux")] + let trusted_uid = peer.uid() == 0; + #[cfg(target_os = "macos")] + let trusted_uid = peer.uid() == 0 || peer.uid() == crate::plat::effective_uid(); let pid = peer .pid() - .filter(|pid| *pid > 0 && peer.uid() == 0) + .filter(|pid| *pid > 0 && trusted_uid) .ok_or_else(|| { io::Error::new( io::ErrorKind::PermissionDenied, @@ -124,6 +180,7 @@ pub async fn system_proxy_identity() -> std::io::Result b if crate::copy::on() { return false; } + let Some(curl) = super::super::tailnet::curl_cli() else { + return false; + }; let url = format!("https://{authority}/auth/web/setup"); let probe = super::webprobe::Probe::start(home, authority); - let Ok(mut child) = crate::proc::tokio_cmd(crate::proc::Kind::Net, "/usr/bin/curl") + let Ok(mut child) = crate::proc::tokio_cmd(crate::proc::Kind::Net, &curl) .args([ "-q", "--silent", @@ -185,6 +245,37 @@ pub async fn https_address_answers(home: &std::path::Path, authority: &str) -> b .is_ok_and(|out| out.status.success() && out.stdout == b"204" && probe.consumed()) } +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum BackendTarget { + Unix(std::path::PathBuf), + Loopback(u16), +} + +impl BackendTarget { + pub fn proxy_url(&self) -> Option { + match self { + Self::Unix(socket) => { + let path = socket.to_str()?; + if !path.starts_with('/') || path.chars().any(char::is_control) { + return None; + } + Some(format!("unix:{path}")) + } + Self::Loopback(port) => (*port != 0).then(|| format!("http://127.0.0.1:{port}")), + } + } + + pub fn matches_proxy_value(&self, value: &str) -> bool { + let Some(url) = self.proxy_url() else { + return false; + }; + match self { + Self::Unix(_) => value == url, + Self::Loopback(_) => value == url || value == format!("{url}/"), + } + } +} + /// Pick a spare node HTTPS port from the status snapshot. Recheck before /// applying a configuration change; this selection alone grants no ownership. pub fn spare_node_port(config: &Value) -> Option { @@ -220,20 +311,15 @@ pub fn spare_node_port(config: &Value) -> Option { (8443..=u16::MAX).find(|p| !ports.contains(p)) } -/// Arguments for the system-installed Tailscale executable. Pass directly -/// to the process API so a path containing spaces stays a single argument. -pub fn private_serve_args( +pub fn private_serve_args_for( service: Option<&str>, port: u16, - socket: &std::path::Path, + target: &BackendTarget, ) -> Option> { - if port == 0 || (service.is_none() && port == 443) || !socket.is_absolute() { - return None; - } - let path = socket.to_str()?; - if path.chars().any(char::is_control) { + if port == 0 || (service.is_none() && port == 443) { return None; } + let proxy = target.proxy_url()?; let mut args = vec![String::from("serve"), String::from("--bg")]; if let Some(name) = service { if name.is_empty() @@ -249,22 +335,32 @@ pub fn private_serve_args( args.push(format!("--service=svc:{name}")); } args.push(format!("--https={port}")); - args.push(format!("unix:{path}")); + args.push(proxy); Some(args) } +/// Arguments for the system-installed Tailscale executable. Pass directly +/// to the process API so a path containing spaces stays a single argument. +pub fn private_serve_args( + service: Option<&str>, + port: u16, + socket: &std::path::Path, +) -> Option> { + private_serve_args_for(service, port, &BackendTarget::Unix(socket.to_path_buf())) +} + /// Inspect the exact node or Service scope before showing its URL. The /// caller separately verifies reachability and the identity of the proxy. -pub fn private_route_matches( +pub fn private_route_matches_target( config: &Value, service: Option<&str>, authority: &str, port: u16, - socket: &std::path::Path, + target: &BackendTarget, ) -> bool { - let Some(path) = socket.to_str().filter(|_| socket.is_absolute()) else { + if target.proxy_url().is_none() { return false; - }; + } let scope = match service { Some(name) => &config["Services"][name], None => config, @@ -277,18 +373,42 @@ pub fn private_route_matches( .as_object() .is_some_and(|map| map.get(&host_port).is_none_or(|flag| flag == false)), }; + let handler_matches = handlers.as_object().is_some_and(|map| { + map.len() == 1 + && map + .get("/") + .and_then(|entry| entry.get("Proxy")) + .and_then(Value::as_str) + .is_some_and(|proxy| target.matches_proxy_value(proxy)) + }); funnel_off(config) && funnel_off(scope) && scope["TCP"][port.to_string()] == serde_json::json!({"HTTPS":true}) - && *handlers == serde_json::json!({"/":{"Proxy":format!("unix:{path}")}}) + && handler_matches +} + +pub fn private_route_matches( + config: &Value, + service: Option<&str>, + authority: &str, + port: u16, + socket: &std::path::Path, +) -> bool { + private_route_matches_target( + config, + service, + authority, + port, + &BackendTarget::Unix(socket.to_path_buf()), + ) } /// Prefer a configured Service; fall back to this node's own HTTPS mapping. -fn configured_authority( +fn configured_authority_for( config: &Value, service: &str, node: &str, - socket: &std::path::Path, + target: &BackendTarget, ) -> Option { let suffix = node.split_once('.')?.1; let service_host = format!("{service}.{suffix}"); @@ -308,7 +428,7 @@ fn configured_authority( let Ok(port) = port.parse::() else { continue; }; - if name == host && private_route_matches(config, scope, host, port, socket) { + if name == host && private_route_matches_target(config, scope, host, port, target) { return Some(if port == 443 { host.to_owned() } else { @@ -320,6 +440,16 @@ fn configured_authority( None } +#[cfg(test)] +fn configured_authority( + config: &Value, + service: &str, + node: &str, + socket: &std::path::Path, +) -> Option { + configured_authority_for(config, service, node, &BackendTarget::Unix(socket.to_path_buf())) +} + // A setup request exists only while this hub's tailnet monitor is running. type SetupRequests = std::collections::HashMap>; static SETUP_REQUESTS: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -331,20 +461,199 @@ pub fn request_setup(home: &std::path::Path, plan: &str) -> Result<(), &'static } fn missing_setup_component() -> Option<&'static str> { - use std::os::unix::fs::{FileTypeExt, PermissionsExt}; - let executable = |path: &str| std::fs::metadata(path).is_ok_and(|file| - file.is_file() && file.permissions().mode() & 0o111 != 0); - let socket = std::fs::metadata("/run/tailscale/tailscaled.sock").is_ok_and(|file| file.file_type().is_socket()); - setup_component_reason(socket, executable) + let has_linux_socket = if cfg!(target_os = "linux") { + use crate::plat::fs::FileTypeExt; + std::fs::metadata("/run/tailscale/tailscaled.sock").is_ok_and(|file| file.file_type().is_socket()) + } else { + true + }; + let has_tailscale = if cfg!(target_os = "linux") { + std::fs::metadata("/usr/bin/tailscale").is_ok_and(|f| crate::plat::fs::runnable(&f)) + } else { + super::super::tailnet::tailscale_cli().is_some() + }; + let has_curl = if cfg!(target_os = "linux") { + std::fs::metadata("/usr/bin/curl").is_ok_and(|f| crate::plat::fs::runnable(&f)) + } else { + super::super::tailnet::curl_cli().is_some() + }; + setup_component_reason_for(std::env::consts::OS, has_linux_socket, has_tailscale, has_curl) } +#[cfg(test)] fn setup_component_reason(socket: bool, executable: impl Fn(&str) -> bool) -> Option<&'static str> { - if !socket { - return Some("Start Tailscale. Backplane needs its system socket at /run/tailscale/tailscaled.sock."); + setup_component_reason_for( + "linux", + socket, + executable("/usr/bin/tailscale"), + executable("/usr/bin/curl"), + ) +} + +pub fn setup_component_reason_for( + os: &str, + has_linux_socket: bool, + has_tailscale: bool, + has_curl: bool, +) -> Option<&'static str> { + match os { + "linux" => { + if !has_linux_socket { + return Some("Start Tailscale. Backplane needs its system socket at /run/tailscale/tailscaled.sock."); + } + if !has_tailscale { + return Some("HTTPS setup requires the Tailscale command at /usr/bin/tailscale."); + } + if !has_curl { + return Some("HTTPS verification requires curl at /usr/bin/curl."); + } + None + } + "macos" => { + if !has_tailscale { + return Some("Install Tailscale (from the App Store, tailscale.com, or Homebrew) to set up HTTPS forwarding."); + } + if !has_curl { + return Some("HTTPS verification requires curl at /usr/bin/curl."); + } + None + } + "windows" => { + if !has_tailscale { + return Some("Install Tailscale to set up HTTPS forwarding."); + } + if !has_curl { + return Some("HTTPS verification requires curl.exe."); + } + None + } + _ => { + if !has_tailscale { + return Some("Install Tailscale to set up HTTPS forwarding."); + } + if !has_curl { + return Some("HTTPS verification requires curl."); + } + None + } + } +} + +fn quote_posix_arg(arg: &str) -> String { + format!("'{}'", arg.replace('\'', "'\\''")) +} + +fn quote_posix_program(prog: &str) -> String { + if !prog.is_empty() + && prog + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'-' | b'_' | b'.')) + { + prog.to_owned() + } else { + quote_posix_arg(prog) + } +} + +fn quote_windows_arg(arg: &str) -> String { + if arg.is_empty() || arg.chars().any(|c| c.is_whitespace() || c == '"') { + format!("\"{}\"", arg.replace('"', "\\\"")) + } else { + arg.to_owned() + } +} + +pub fn format_command_for(os: &str, program: &str, args: &[String]) -> String { + if os == "windows" { + let mut parts = Vec::with_capacity(args.len() + 1); + parts.push(quote_windows_arg(program)); + parts.extend(args.iter().map(|a| quote_windows_arg(a))); + parts.join(" ") + } else { + let mut parts = Vec::with_capacity(args.len() + 1); + parts.push(quote_posix_program(program)); + parts.extend(args.iter().map(|a| quote_posix_arg(a))); + parts.join(" ") + } +} + +pub fn operator_guidance(os: &str, cli: &str, user_plan: &str) -> (String, &'static str) { + match os { + "linux" => ( + r#"sudo tailscale set --operator="$(id -un)""#.to_owned(), + "This user can manage Tailscale on this computer without sudo.", + ), + "macos" => ( + format!(r#"sudo {} set --operator="$(id -un)""#, quote_posix_program(cli)), + "This user can manage Tailscale on this computer without sudo.", + ), + "windows" => ( + user_plan.to_owned(), + "Run this command once in an Administrator terminal to set up HTTPS forwarding.", + ), + _ => ( + user_plan.to_owned(), + "Run this command with administrator privileges to set up HTTPS forwarding.", + ), + } +} + +fn read_saved_port(directory: &std::path::Path) -> Option { + std::fs::read_to_string(directory.join("backend-port")) + .ok()? + .trim() + .parse::() + .ok() + .filter(|p| *p != 0) +} + +fn write_saved_port(directory: &std::path::Path, port: u16) -> std::io::Result<()> { + use std::io::Write; + let path = directory.join("backend-port"); + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let mut file = opts.open(path)?; + writeln!(file, "{port}") +} + +fn is_permission_refusal(stderr: &str) -> bool { + let reason = stderr.to_ascii_lowercase(); + [ + "permission denied", + "access denied", + "requires root", + "permission is denied", + "not authorized", + "must be run as", + "requires elevation", + "administrator", + ] + .iter() + .any(|m| reason.contains(m)) +} + +fn use_unix_backend(directory: &std::path::Path) -> bool { + #[cfg(target_os = "linux")] + { + let _ = directory; + true + } + #[cfg(target_os = "macos")] + { + super::super::tailnet::macos_has_brew_socket() + && read_saved_port(directory).is_none() + && directory.join("browser.sock").to_string_lossy().len() < 100 + } + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + { + let _ = directory; + false } - if !executable("/usr/bin/tailscale") { return Some("HTTPS setup requires the Tailscale command at /usr/bin/tailscale."); } - if !executable("/usr/bin/curl") { return Some("HTTPS verification requires curl at /usr/bin/curl."); } - None } async fn enabled_changed(hub: &crate::hub::Hub, changes: &mut tokio::sync::broadcast::Receiver, enabled: bool) { @@ -368,14 +677,12 @@ async fn publish_status(hub: &crate::hub::Hub, previous: &mut Value, next: Value } pub async fn monitor(hub: std::sync::Arc, ts: &dyn super::Tailscale) { - use std::os::unix::fs::DirBuilderExt; if crate::copy::on() { return; } let (sender, mut requests) = tokio::sync::mpsc::channel(1); SETUP_REQUESTS.get_or_init(Default::default).lock().unwrap().insert(hub.cfg.home.clone(), sender); let directory = hub.cfg.home.join("web"); - let socket = directory.join("browser.sock"); let mut cleanup_pending = directory.exists(); let mut refused_plan = None; let mut changes = hub.subscribe(); @@ -383,6 +690,7 @@ pub async fn monitor(hub: std::sync::Arc, ts: &dyn super::Tails let mut previous = Value::Null; let mut last_action = std::time::Instant::now(); let mut verification_failed = false; + let mut reserved_listener: Option = None; loop { let enabled = hub.setting("web.enabled").await.as_deref() == Some("1"); let mut status_row = serde_json::json!({"canEnable":true}); @@ -392,7 +700,7 @@ pub async fn monitor(hub: std::sync::Arc, ts: &dyn super::Tails status_row["reason"] = Value::from(reason); } else { let status: Value = serde_json::from_str(&ts.status().await).unwrap_or(Value::Null); - let config: Value = + let mut config: Value = serde_json::from_str(&ts.serve_status().await).unwrap_or(Value::Null); let node = status["Self"]["DNSName"] .as_str() @@ -402,68 +710,218 @@ pub async fn monitor(hub: std::sync::Arc, ts: &dyn super::Tails .setting("web.service") .await .unwrap_or_else(|| "bp".into()); - status_row["reason"] = Value::from("Waiting for a verified private Tailscale HTTPS mapping."); - if !node.is_empty() && configured_authority(&config, &service, node, &socket).is_none() { - if let Some(args) = spare_node_port(&config).and_then(|port| private_serve_args(None, port, &socket)) { - let quoted = args.iter().map(|arg| format!("'{}'", arg.replace('\'', "'\\''"))).collect::>(); - let user_plan = format!("/usr/bin/tailscale {}", quoted.join(" ")); - if requested.as_ref() == Some(&user_plan) { - let _ = std::fs::DirBuilder::new().mode(0o700).create(&directory); - if protected_directory(&directory).is_ok() && system_proxy_identity().await.is_ok() { - let mut cmd = crate::proc::tokio_cmd(crate::proc::Kind::Net, "/usr/bin/tailscale"); - if let Ok(out) = cmd.args(&args).env("LC_ALL", "C").stdin(std::process::Stdio::null()).output().await { - let reason = String::from_utf8_lossy(&out.stderr).to_ascii_lowercase(); - if out.status.success() { - refused_plan = None; - } else if ["permission denied", "access denied", "requires root", "permission is denied", "not authorized"].iter().any(|m| reason.contains(m)) { - refused_plan = Some(user_plan.clone()); + if node.is_empty() { + status_row["reason"] = Value::from("Start and sign in to Tailscale to set up HTTPS forwarding."); + } else { + match ensure_protected_directory(&directory) { + Err(_) => { + status_row["reason"] = Value::from("Web UI runtime directory could not be prepared."); + } + Ok(canon_dir) => { + status_row["reason"] = Value::from("Waiting for a verified private Tailscale HTTPS mapping."); + #[cfg(target_os = "linux")] + let use_unix = true; + #[cfg(target_os = "macos")] + let use_unix = use_unix_backend(&canon_dir) + && protected_directory(&canon_dir).is_ok() + && system_proxy_identity().await.is_ok(); + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + let use_unix = false; + let target = if use_unix { + if protected_directory(&canon_dir).is_err() { + status_row["reason"] = Value::from("Web UI runtime directory permissions are too permissive."); + None + } else { + Some(BackendTarget::Unix(canon_dir.join("browser.sock"))) + } + } else { + let port = if let Some(ref listener) = reserved_listener { + listener.local_addr().ok().map(|a| a.port()) + } else if let Some(saved) = read_saved_port(&canon_dir) { + if let Ok(tcp) = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, saved)).await { + reserved_listener = Some(tcp); + Some(saved) + } else if configured_authority_for(&config, &service, node, &BackendTarget::Loopback(saved)).is_some() { + Some(saved) } else { - status_row["reason"] = Value::from("Private HTTPS setup did not complete."); + None + } + } else { + None + }; + if let Some(p) = port { + Some(BackendTarget::Loopback(p)) + } else if let Ok(tcp) = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).await { + let new_port = tcp.local_addr().ok().map(|a| a.port()).unwrap_or(0); + if new_port != 0 && write_saved_port(&canon_dir, new_port).is_ok() { + reserved_listener = Some(tcp); + Some(BackendTarget::Loopback(new_port)) + } else { + None + } + } else { + None + } + }; + if let Some(target) = target { + let cli_path = super::super::tailnet::tailscale_cli(); + let cli_str = cli_path + .as_ref() + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or_else(|| "tailscale".to_owned()); + if configured_authority_for(&config, &service, node, &target).is_none() { + if let Some(args) = spare_node_port(&config) + .and_then(|port| private_serve_args_for(None, port, &target)) + { + let user_plan = format_command_for(std::env::consts::OS, &cli_str, &args); + if requested.as_ref() == Some(&user_plan) { + #[cfg(unix)] + let unix_ok = !matches!(target, BackendTarget::Unix(_)) + || (protected_directory(&canon_dir).is_ok() + && system_proxy_identity().await.is_ok()); + #[cfg(not(unix))] + let unix_ok = true; + if unix_ok { + let mut cmd = crate::proc::tokio_cmd(crate::proc::Kind::Net, &cli_str); + if let Ok(out) = cmd.args(&args).env("LC_ALL", "C").stdin(std::process::Stdio::null()).output().await { + let reason = String::from_utf8_lossy(&out.stderr); + if out.status.success() { + refused_plan = None; + config = serde_json::from_str(&ts.serve_status().await).unwrap_or(Value::Null); + } else if is_permission_refusal(&reason) { + refused_plan = Some(user_plan.clone()); + } else { + status_row["reason"] = Value::from("Private HTTPS setup did not complete."); + } + } + } + } + if refused_plan.as_ref() == Some(&user_plan) { + let (op_cmd, op_note) = operator_guidance(std::env::consts::OS, &cli_str, &user_plan); + status_row["reason"] = Value::from("Tailscale refused setup. This account needs operator permission on this computer."); + status_row["operatorRequired"] = Value::Bool(true); + status_row["operatorCommand"] = Value::from(op_cmd); + status_row["operatorNote"] = Value::from(op_note); + } + status_row["command"] = Value::from(user_plan); + } + } + if let Some(authority) = configured_authority_for(&config, &service, node, &target) { + match target { + #[cfg(unix)] + BackendTarget::Unix(socket) => { + if let Ok(listener) = bind_private_backend(&canon_dir, authority.clone()).await { + let mut task = tokio::spawn(listener.run(hub.clone())); + if https_address_answers(&hub.cfg.home, &authority).await { + let active = serde_json::json!({"available":true, "address":format!("https://{authority}")}); + publish_status(&hub, &mut previous, active).await; + tokio::select! { + _ = &mut task => (), + _ = enabled_changed(&hub, &mut changes, true) => (), + } + task.abort(); + let _ = std::fs::remove_file(&socket); + requested = None; + verification_failed = false; + last_action = std::time::Instant::now(); + continue; + } + verification_failed = true; + status_row["reason"] = Value::from("Private HTTPS forwarding could not be verified. Backplane will retry."); + task.abort(); + let _ = std::fs::remove_file(&socket); + } + } + #[cfg(not(unix))] + BackendTarget::Unix(_) => {} + BackendTarget::Loopback(port) => { + let tcp = match reserved_listener.take() { + Some(l) if l.local_addr().is_ok_and(|a| a.port() == port) => Ok(l), + other => { + drop(other); + tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, port)).await + } + }; + match tcp { + Ok(tcp) => { + if let Ok(listener) = super::webtransport::LoopbackBrowserListener::from_listener(tcp, authority.clone()) { + let (stop_tx, stop_rx) = tokio::sync::oneshot::channel(); + let mut task = tokio::spawn(listener.run(hub.clone(), stop_rx)); + let verified = https_address_answers(&hub.cfg.home, &authority).await; + if verified { + let active = serde_json::json!({"available":true, "address":format!("https://{authority}")}); + publish_status(&hub, &mut previous, active).await; + tokio::select! { + res = &mut task => { + if let Ok(Ok(kept)) = res { + reserved_listener = Some(kept); + } + } + _ = enabled_changed(&hub, &mut changes, true) => { + let _ = stop_tx.send(()); + if let Ok(Ok(Ok(kept))) = tokio::time::timeout(std::time::Duration::from_secs(2), &mut task).await { + reserved_listener = Some(kept); + } else { + task.abort(); + } + } + } + requested = None; + verification_failed = false; + last_action = std::time::Instant::now(); + continue; + } + verification_failed = true; + status_row["reason"] = Value::from("Private HTTPS forwarding could not be verified. Backplane will retry."); + let _ = stop_tx.send(()); + if let Ok(Ok(Ok(kept))) = tokio::time::timeout(std::time::Duration::from_secs(2), &mut task).await { + reserved_listener = Some(kept); + } else { + task.abort(); + } + } + } + Err(_) => { + verification_failed = true; + status_row["reason"] = Value::from("Local Web UI port is in use by another process. Turn Browser access off and back on to reset forwarding."); + } + } + } } } } } - if refused_plan.as_ref() == Some(&user_plan) { - status_row["reason"] = Value::from("Tailscale refused setup. This account needs operator permission on this computer."); - status_row["operatorRequired"] = Value::Bool(true); - } - status_row["command"] = Value::from(user_plan); - } - } - if let Some(authority) = configured_authority(&config, &service, node, &socket) { - let _ = std::fs::DirBuilder::new().mode(0o700).create(&directory); - if let Ok(listener) = bind_private_backend(&directory, authority.clone()).await { - let mut task = tokio::spawn(listener.run(hub.clone())); - if https_address_answers(&hub.cfg.home, &authority).await { - let active = serde_json::json!({"available":true, "address":format!("https://{authority}")}); - publish_status(&hub, &mut previous, active).await; - tokio::select! { - _ = &mut task => (), - _ = enabled_changed(&hub, &mut changes, true) => (), - } - task.abort(); - let _ = std::fs::remove_file(&socket); - requested = None; - verification_failed = false; - last_action = std::time::Instant::now(); - continue; - } - verification_failed = true; - status_row["reason"] = Value::from("Private HTTPS forwarding could not be verified. Backplane will retry."); - task.abort(); - let _ = std::fs::remove_file(&socket); - } } } } else if cleanup_pending { refused_plan = None; let service = hub.setting("web.service").await.unwrap_or_else(|| "bp".into()); - cleanup_pending = !cleanup_disabled(ts, &service, &socket, |scope, host, port, path| async move { - remove_private_mapping(scope.as_deref(), &host, port, &path).await + let dir = crate::plat::fs::canonicalize(&directory).unwrap_or_else(|_| directory.clone()); + let target = if let Some(port) = reserved_listener + .as_ref() + .and_then(|l| l.local_addr().ok().map(|a| a.port())) + .or_else(|| read_saved_port(&dir)) + { + BackendTarget::Loopback(port) + } else { + BackendTarget::Unix(dir.join("browser.sock")) + }; + let ts_status_raw = ts.serve_status().await; + let ts_config: Value = serde_json::from_str(&ts_status_raw).unwrap_or(Value::Null); + cleanup_pending = !cleanup_disabled_target(ts, &service, &target, |scope, host, port, tgt| async move { + match tgt { + #[cfg(target_os = "linux")] + BackendTarget::Unix(path) => remove_private_mapping(scope.as_deref(), &host, port, &path).await, + _ => remove_private_mapping_cli(&ts_config, scope.as_deref(), &host, port, &tgt).await, + } }).await; if cleanup_pending { status_row["reason"] = Value::from("Browser access is off. Tailscale mapping removal could not be confirmed."); + } else { + reserved_listener = None; + let _ = std::fs::remove_file(directory.join("backend-port")); + let _ = std::fs::remove_file(directory.join("browser.sock")); } } publish_status(&hub, &mut previous, status_row).await; @@ -478,41 +936,90 @@ pub async fn monitor(hub: std::sync::Arc, ts: &dyn super::Tails } } -async fn cleanup_disabled(ts: &dyn super::Tailscale, service: &str, socket: &std::path::Path, remove: F) -> bool -where F: FnOnce(Option, String, u16, std::path::PathBuf) -> R, R: std::future::Future { +async fn cleanup_disabled_target( + ts: &dyn super::Tailscale, + service: &str, + target: &BackendTarget, + remove: F, +) -> bool +where + F: FnOnce(Option, String, u16, BackendTarget) -> R, + R: std::future::Future, +{ let Ok(status) = serde_json::from_str::(&ts.status().await) else { return false; }; let Some(node) = status["Self"]["DNSName"].as_str().map(|s| s.trim_end_matches('.')).filter(|s| !s.is_empty()) else { return false; }; let raw = ts.serve_status().await; let Ok(config) = serde_json::from_str::(&raw) else { return false; }; if !config.is_object() { return false; } - let Some(authority) = configured_authority(&config, service, node, socket) else { - return private_backend_absent(&raw, socket); + let Some(authority) = configured_authority_for(&config, service, node, target) else { + return private_backend_absent_target(&raw, target); }; let (host, port) = authority.rsplit_once(':').map_or((authority.as_str(), 443), |(host, port)| (host, port.parse().unwrap_or(0))); let scope = (host != node).then(|| service.to_owned()); - let _ = remove(scope, host.to_owned(), port, socket.to_owned()).await; + let _ = remove(scope, host.to_owned(), port, target.clone()).await; // Read back on the next pass. The other address mode may also have a mapping. false } +#[cfg(test)] +async fn cleanup_disabled(ts: &dyn super::Tailscale, service: &str, socket: &std::path::Path, remove: F) -> bool +where F: FnOnce(Option, String, u16, std::path::PathBuf) -> R, R: std::future::Future { + cleanup_disabled_target(ts, service, &BackendTarget::Unix(socket.to_path_buf()), |scope, host, port, target| async move { + let BackendTarget::Unix(path) = target else { return false; }; + remove(scope, host, port, path).await + }).await +} + // A shared handler cannot be removed automatically. Scan all scopes and paths: // either Present or Unconfirmed keeps the disabled-state warning visible. +fn private_backend_absent_target(raw: &str, target: &BackendTarget) -> bool { + let Some(url) = target.proxy_url() else { + return false; + }; + if mapping_status(raw, "", &url) != Mapping::Absent { + return false; + } + if matches!(target, BackendTarget::Loopback(_)) + && mapping_status(raw, "", &format!("{url}/")) != Mapping::Absent + { + return false; + } + true +} + +#[cfg(test)] fn private_backend_absent(raw: &str, socket: &std::path::Path) -> bool { - socket.to_str().is_some_and(|path| mapping_status(raw, "", &format!("unix:{path}")) == Mapping::Absent) + private_backend_absent_target(raw, &BackendTarget::Unix(socket.to_path_buf())) } -/// An administrator may have reassigned the endpoint since setup. Only -/// produce a removal command when the fresh status still names our backend. -pub fn private_remove_args( +pub fn other_authority_on_port( config: &Value, service: Option<&str>, hostname: &str, port: u16, - socket: &std::path::Path, +) -> bool { + let scope = match service { + Some(name) => &config["Services"][format!("svc:{name}")], + None => config, + }; + let Some(web) = scope.get("Web").and_then(Value::as_object) else { + return false; + }; + let own = format!("{hostname}:{port}"); + let suffix = format!(":{port}"); + web.keys().any(|k| k != &own && k.ends_with(&suffix)) +} + +pub fn private_remove_args_for( + config: &Value, + service: Option<&str>, + hostname: &str, + port: u16, + target: &BackendTarget, ) -> Option> { - let mut args = private_serve_args(service, port, socket)?; + let mut args = private_serve_args_for(service, port, target)?; let scope = service.map(|name| format!("svc:{name}")); - if !private_route_matches(config, scope.as_deref(), hostname, port, socket) { + if !private_route_matches_target(config, scope.as_deref(), hostname, port, target) { return None; } args.retain(|arg| arg != "--bg"); @@ -520,8 +1027,27 @@ pub fn private_remove_args( Some(args) } +/// An administrator may have reassigned the endpoint since setup. Only +/// produce a removal command when the fresh status still names our backend. +pub fn private_remove_args( + config: &Value, + service: Option<&str>, + hostname: &str, + port: u16, + socket: &std::path::Path, +) -> Option> { + private_remove_args_for( + config, + service, + hostname, + port, + &BackendTarget::Unix(socket.to_path_buf()), + ) +} + /// Prepare the minimal Serve config update for a conditional LocalAPI write. /// The caller must submit the original GET's ETag in If-Match. +#[allow(dead_code)] fn removal_update(mut config: Value, etag: &str, service: Option<&str>, hostname: &str, port: u16, socket: &std::path::Path) -> Option { if etag.trim().is_empty() || etag == "*" { return None; } @@ -542,6 +1068,7 @@ fn removal_update(mut config: Value, etag: &str, service: Option<&str>, hostname Some(config) } +#[cfg(target_os = "linux")] async fn remove_private_mapping(service: Option<&str>, host: &str, port: u16, socket: &std::path::Path) -> bool { use std::process::Stdio; use tokio::io::AsyncWriteExt; @@ -563,11 +1090,40 @@ async fn remove_private_mapping(service: Option<&str>, host: &str, port: u16, so let Ok(mut child) = local_api().args(["--data-binary", "@-", "--header", "Content-Type: application/json", "--header", &format!("If-Match: {etag}")]).stdin(Stdio::piped()).stdout(Stdio::null()).kill_on_drop(true).spawn() else { return false; }; let Some(mut input) = child.stdin.take() else { return false; }; - if input.write_all(updated.to_string().as_bytes()).await.is_err() { return false; } + if input.write_all(updated.to_string().as_bytes()).await.is_err() { return false; }; drop(input); child.wait().await.is_ok_and(|s| s.success()) } +async fn remove_private_mapping_cli( + config: &Value, + service: Option<&str>, + host: &str, + port: u16, + target: &BackendTarget, +) -> bool { + if crate::copy::on() || other_authority_on_port(config, service, host, port) { + return false; + } + let Some(args) = private_remove_args_for(config, service, host, port, target) else { + return false; + }; + let cli = super::super::tailnet::tailscale_program(); + matches!( + tokio::time::timeout( + std::time::Duration::from_secs(10), + crate::proc::tokio_cmd(crate::proc::Kind::Net, cli) + .args(&args) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .kill_on_drop(true) + .status(), + ) + .await, + Ok(Ok(s)) if s.success() + ) +} + #[cfg(test)] mod tests { use super::*; @@ -670,6 +1226,7 @@ mod tests { assert!(private_remove_args(&state, Some("bp"), host, 443, socket).is_none()); } + #[cfg(unix)] #[test] fn private_socket_directory_rejects_a_writable_parent() { use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; @@ -693,6 +1250,22 @@ mod tests { ); } + #[test] + fn ensure_protected_directory_creates_and_validates_directory() { + let scratch = crate::plat::tmp::dir("web-ensure-dir"); + let dir = scratch.join("web"); + let canon = ensure_protected_directory(&dir).unwrap(); + assert!(canon.is_absolute()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&canon).unwrap().permissions().mode() & 0o777, 0o700); + } + #[cfg(windows)] + assert!(protected_directory(&canon).is_ok()); + assert!(protected_directory(std::path::Path::new("relative")).is_err()); + } + #[test] fn node_port_selection_preserves_existing_and_foreground_routes() { let config = json!({"TCP":{"8443":{"HTTPS":true}}, @@ -789,4 +1362,101 @@ mod tests { assert_eq!(mapping_status(invalid, host, backend), Mapping::Unconfirmed); } } + + #[test] + fn loopback_target_supports_serve_args_route_matching_and_removal() { + let target = BackendTarget::Loopback(49231); + assert_eq!( + private_serve_args_for(None, 8443, &target).unwrap(), + ["serve", "--bg", "--https=8443", "http://127.0.0.1:49231"] + ); + assert_eq!( + private_serve_args_for(Some("bp"), 443, &target).unwrap(), + ["serve", "--bg", "--service=svc:bp", "--https=443", "http://127.0.0.1:49231"] + ); + assert!(private_serve_args_for(None, 8443, &BackendTarget::Loopback(0)).is_none()); + + let node = "win-box.tail1.ts.net"; + let config = json!({ + "TCP": {"8443": {"HTTPS": true}}, + "Web": {"win-box.tail1.ts.net:8443": {"Handlers": {"/": {"Proxy": "http://127.0.0.1:49231/"}}}} + }); + assert_eq!( + configured_authority_for(&config, "bp", node, &target).as_deref(), + Some("win-box.tail1.ts.net:8443") + ); + assert_eq!( + private_remove_args_for(&config, None, node, 8443, &target).unwrap(), + ["serve", "--https=8443", "off"] + ); + assert!(!other_authority_on_port(&config, None, node, 8443)); + + let shared = json!({ + "TCP": {"8443": {"HTTPS": true}}, + "Web": { + "win-box.tail1.ts.net:8443": {"Handlers": {"/": {"Proxy": "http://127.0.0.1:49231"}}}, + "other.tail1.ts.net:8443": {"Handlers": {"/": {"Text": "keep"}}} + } + }); + assert!(other_authority_on_port(&shared, None, node, 8443)); + assert!(!private_backend_absent_target(&config.to_string(), &target)); + assert!(private_backend_absent_target(&json!({}).to_string(), &target)); + } + + #[test] + fn cross_platform_commands_missing_reasons_and_operator_guidance() { + let args = vec![ + "serve".to_string(), + "--bg".to_string(), + "--https=8443".to_string(), + "http://127.0.0.1:49231".to_string(), + ]; + assert_eq!( + format_command_for("macos", "/Applications/Tailscale.app/Contents/MacOS/Tailscale", &args), + "/Applications/Tailscale.app/Contents/MacOS/Tailscale 'serve' '--bg' '--https=8443' 'http://127.0.0.1:49231'" + ); + assert_eq!( + format_command_for("windows", r"C:\Program Files\Tailscale\tailscale.exe", &args), + r#""C:\Program Files\Tailscale\tailscale.exe" serve --bg --https=8443 http://127.0.0.1:49231"# + ); + + assert!(setup_component_reason_for("macos", false, true, true).is_none()); + assert!(setup_component_reason_for("macos", false, false, true).unwrap().contains("App Store")); + assert!(setup_component_reason_for("windows", false, true, true).is_none()); + assert!(setup_component_reason_for("windows", false, true, false).unwrap().contains("curl.exe")); + + let (mac_cmd, mac_note) = operator_guidance("macos", "/Applications/Tailscale.app/Contents/MacOS/Tailscale", "plan"); + assert!(mac_cmd.contains("sudo /Applications/Tailscale.app/Contents/MacOS/Tailscale set --operator=")); + assert!(mac_note.contains("without sudo")); + + let (win_cmd, win_note) = operator_guidance("windows", r"C:\Program Files\Tailscale\tailscale.exe", "win-plan"); + assert_eq!(win_cmd, "win-plan"); + assert!(win_note.contains("Administrator")); + } + + #[tokio::test] + async fn disabling_loopback_target_triggers_removal_and_needs_readback() { + struct LoopbackTs; + impl super::super::Tailscale for LoopbackTs { + fn ip4(&self) -> super::super::Fut { unreachable!() } + fn whois(&self, _: String) -> super::super::Fut { unreachable!() } + fn status(&self) -> super::super::Fut { + Box::pin(async { json!({"Self":{"DNSName":"win.example.ts.net."}}).to_string() }) + } + fn serve_status(&self) -> super::super::Fut { + Box::pin(async { + json!({"TCP":{"8443":{"HTTPS":true}},"Web":{"win.example.ts.net:8443":{"Handlers":{"/":{"Proxy":"http://127.0.0.1:49231"}}}}}).to_string() + }) + } + } + let target = BackendTarget::Loopback(49231); + let mut called = false; + let confirmed = cleanup_disabled_target(&LoopbackTs, "bp", &target, |scope, host, port, tgt| { + called = true; + assert_eq!((scope, host.as_str(), port, tgt), (None, "win.example.ts.net", 8443, BackendTarget::Loopback(49231))); + std::future::ready(true) + }).await; + assert!(called); + assert!(!confirmed); + } } diff --git a/native/host/src/net/webtransport.rs b/native/host/src/net/webtransport.rs index dea974136a..d3ac496309 100644 --- a/native/host/src/net/webtransport.rs +++ b/native/host/src/net/webtransport.rs @@ -1,14 +1,19 @@ //! Private backend for a separately configured HTTPS Serve proxy. //! Provisioning supplies the authority and authenticated daemon identity. //! The release startup path does not construct this listener. -use std::{io, os::unix::fs::MetadataExt, path::Path, sync::Arc}; +use std::{io, net::{Ipv4Addr, SocketAddr}, sync::Arc, time::Duration}; +#[cfg(unix)] +use std::{os::unix::fs::MetadataExt, path::Path}; +#[cfg(unix)] use tokio::net::{UnixListener, UnixStream}; +#[cfg(unix)] pub(crate) struct ProxyIdentity { pub uid: u32, pub pid: i32, } +#[cfg(unix)] impl ProxyIdentity { fn accepts(&self, stream: &UnixStream) -> bool { self.pid > 0 && stream.peer_cred().is_ok_and(|peer| { @@ -17,7 +22,7 @@ impl ProxyIdentity { } } -#[cfg(target_os = "linux")] +#[cfg(unix)] async fn refresh_for_peer( proxy: &mut ProxyIdentity, stream: &UnixStream, @@ -25,7 +30,7 @@ async fn refresh_for_peer( lookup: impl std::future::Future>, ) -> bool { if !stream.peer_cred().is_ok_and(|peer| peer.uid() == proxy.uid) - || last_lookup.is_some_and(|at| at.elapsed() < std::time::Duration::from_secs(1)) { + || last_lookup.is_some_and(|at| at.elapsed() < Duration::from_secs(1)) { return false; } *last_lookup = Some(std::time::Instant::now()); @@ -35,23 +40,25 @@ async fn refresh_for_peer( true } +#[cfg(unix)] pub(crate) struct BrowserListener { listener: UnixListener, authority: String, proxy: ProxyIdentity, } -fn validate_authority(authority: &str) -> io::Result<()> { - let (host, port) = authority.split_once(':').map_or((authority, None), |(h,p)| (h, Some(p))); - if !host.ends_with(".ts.net") || host.split('.').count() < 4 || host.len() > 253 - || host.split('.').any(|label| label.is_empty() || label.len() > 63 || label.starts_with('-') - || label.ends_with('-') || !label.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')) - || port.is_some_and(|p| p.parse::().map_or(true, |n| matches!(n, 0 | 443) || n.to_string() != p)) { - return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid browser proxy configuration")); - } +pub(crate) fn validate_authority(authority: &str) -> io::Result<()> { + let (host, port) = authority.split_once(':').map_or((authority, None), |(h,p)| (h, Some(p))); + if !host.ends_with(".ts.net") || host.split('.').count() < 4 || host.len() > 253 + || host.split('.').any(|label| label.is_empty() || label.len() > 63 || label.starts_with('-') + || label.ends_with('-') || !label.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')) + || port.is_some_and(|p| p.parse::().map_or(true, |n| matches!(n, 0 | 443) || n.to_string() != p)) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid browser proxy configuration")); + } Ok(()) } +#[cfg(unix)] impl BrowserListener { /// Caller owns the private runtime directory and its socket lifecycle. /// An occupied path fails the bind, including after an unclean shutdown. @@ -70,22 +77,20 @@ impl BrowserListener { } pub async fn run(mut self, hub: Arc) -> io::Result<()> { - #[cfg(target_os = "linux")] let mut last_lookup = None; loop { let stream = match self.listener.accept().await { Ok((stream, _)) => stream, Err(e) if matches!(e.kind(), io::ErrorKind::ConnectionAborted | io::ErrorKind::Interrupted) => continue, - Err(e) if matches!(e.raw_os_error(), Some(libc::EMFILE | libc::ENFILE)) => { - tokio::time::sleep(std::time::Duration::from_millis(100)).await; + Err(e) if matches!(e.raw_os_error(), Some(crate::plat::errno::EMFILE | crate::plat::errno::ENFILE)) => { + tokio::time::sleep(Duration::from_millis(100)).await; continue; } Err(e) => return Err(e), }; - let admitted = self.proxy.accepts(&stream); - #[cfg(target_os = "linux")] - let admitted = admitted || refresh_for_peer(&mut self.proxy, &stream, &mut last_lookup, - super::webprovision::system_proxy_identity()).await; + let admitted = self.proxy.accepts(&stream) + || refresh_for_peer(&mut self.proxy, &stream, &mut last_lookup, + super::webprovision::system_proxy_identity()).await; if admitted { let hub = hub.clone(); let authority = self.authority.clone(); @@ -95,11 +100,89 @@ impl BrowserListener { } } +/// Loopback TCP backend used when the OS Tailscale daemon serves via loopback +/// (Windows, and macOS sandboxed App Store Tailscale without a root Unix socket). +/// Retains and returns the bound `TcpListener` on stop so the port cannot be +/// claimed by another local process before Serve teardown completes. +pub(crate) struct LoopbackBrowserListener { + listener: tokio::net::TcpListener, + authority: String, + backend_port: u16, +} + +impl LoopbackBrowserListener { + pub fn from_listener(listener: tokio::net::TcpListener, authority: String) -> io::Result { + validate_authority(&authority)?; + let addr = listener.local_addr()?; + if addr.ip() != Ipv4Addr::LOCALHOST || addr.port() == 0 { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "loopback IPv4 listener required")); + } + Ok(Self { + listener, + authority, + backend_port: addr.port(), + }) + } + + pub async fn bind(authority: String, port: u16) -> io::Result { + validate_authority(&authority)?; + let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))).await?; + Self::from_listener(listener, authority) + } + + pub fn port(&self) -> u16 { + self.backend_port + } + + pub async fn run( + self, + hub: Arc, + stop: tokio::sync::oneshot::Receiver<()>, + ) -> io::Result { + self.run_with(hub, stop, crate::plat::browser_loopback_peer_ok).await + } + + pub(crate) async fn run_with( + self, + hub: Arc, + mut stop: tokio::sync::oneshot::Receiver<()>, + verify: F, + ) -> io::Result + where + F: Fn(&tokio::net::TcpStream) -> bool + Clone + Send + Sync + 'static, + { + loop { + let stream = tokio::select! { + _ = &mut stop => return Ok(self.listener), + accepted = self.listener.accept() => match accepted { + Ok((stream, _)) => stream, + Err(e) if matches!(e.kind(), io::ErrorKind::ConnectionAborted | io::ErrorKind::Interrupted) => continue, + Err(e) if matches!(e.raw_os_error(), Some(crate::plat::errno::EMFILE | crate::plat::errno::ENFILE)) => { + tokio::time::sleep(Duration::from_millis(100)).await; + continue; + } + Err(e) => return Err(e), + } + }; + let verify = verify.clone(); + let lookup = tokio::task::spawn_blocking(move || verify(&stream).then_some(stream)); + if let Ok(Ok(Some(stream))) = tokio::time::timeout(Duration::from_millis(300), lookup).await { + let authority = self.authority.clone(); + let hub = hub.clone(); + let backend_port = self.backend_port; + tokio::spawn(async move { + let _ = super::webingress::serve_loopback(hub, stream, &authority, backend_port).await; + }); + } + } + } +} + #[cfg(test)] mod tests { use super::*; - #[cfg(target_os = "linux")] + #[cfg(unix)] #[tokio::test] async fn restarted_proxy_must_match_fresh_daemon_credentials() { let (stream, _peer) = UnixStream::pair().unwrap(); @@ -118,6 +201,7 @@ mod tests { assert!(cached.accepts(&stream)); } + #[cfg(unix)] #[tokio::test] async fn bind_requires_a_private_directory_and_canonical_authority() { use std::os::unix::fs::{symlink, PermissionsExt}; @@ -145,6 +229,7 @@ mod tests { std::fs::remove_file(dir.join("browser.sock")).unwrap(); } + #[cfg(unix)] #[tokio::test] async fn browser_transport_checks_peer_process_as_well_as_user() { let (stream, _peer) = UnixStream::pair().unwrap(); @@ -153,6 +238,91 @@ mod tests { let other_process = ProxyIdentity { pid: identity.pid + 1, ..identity }; assert!(!other_process.accepts(&stream)); } + + #[test] + fn windows_trusted_tailscale_path_checks() { + use crate::plat::is_trusted_tailscale_windows_path as trusted; + assert!(trusted(r"C:\Program Files\Tailscale\tailscaled.exe", None, None)); + assert!(trusted(r"c:\program files\tailscale\tailscale-ipn.exe", None, None)); + assert!(trusted(r"D:\Apps\Tailscale\tailscale.exe", Some(r"D:\Apps"), None)); + assert!(trusted(r"C:\Program Files (x86)\Tailscale\tailscaled.exe", None, Some(r"C:\Program Files (x86)"))); + assert!(!trusted(r"C:\Users\bob\tailscaled.exe", None, None)); + assert!(!trusted(r"C:\Program Files\Tailscale\sub\tailscaled.exe", None, None)); + assert!(!trusted(r"C:\Program Files\Tailscale\other.exe", None, None)); + } + + #[tokio::test] + async fn loopback_listener_enforces_peer_check_and_retains_port_on_stop() { + use serde_json::json; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let home = crate::plat::tmp::dir("loopback-listener"); + std::fs::write(home.join("token"), "tok").unwrap(); + std::fs::write( + home.join("events.jsonl"), + "{\"$\":\"SettingSet\",\"key\":\"web.enabled\",\"value\":\"1\",\"at\":1}\n", + ) + .unwrap(); + let cfg = crate::hub::Cfg { + home: home.to_path_buf(), + version: "0.16.4".into(), + commit: "test".into(), + listen: "127.0.0.1:0".into(), + os: "windows".into(), + arch: "x64".into(), + }; + let hub = crate::hub::Hub::start(cfg, Arc::new(crate::presenter::Canned { reply: json!({}) })) + .await + .unwrap(); + let authority = "hub.example.ts.net:8443"; + assert!(LoopbackBrowserListener::bind("example.com".into(), 0).await.is_err()); + + // Reject when peer verifier returns false + let listener = LoopbackBrowserListener::bind(authority.into(), 0).await.unwrap(); + let port = listener.port(); + let (stop_tx, stop_rx) = tokio::sync::oneshot::channel(); + let task = tokio::spawn(listener.run_with(hub.clone(), stop_rx, |_| false)); + let mut client = tokio::net::TcpStream::connect((Ipv4Addr::LOCALHOST, port)).await.unwrap(); + client + .write_all( + format!( + "GET /auth/web/info HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\ + X-Forwarded-Host: {authority}\r\nX-Forwarded-Proto: https\r\n\ + Tailscale-User-Login: person@example.com\r\n\r\n" + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut buf = Vec::new(); + let _ = client.read_to_end(&mut buf).await; + assert!(buf.is_empty(), "rejected peer must receive no HTTP response"); + let _ = stop_tx.send(()); + let kept = task.await.unwrap().unwrap(); + assert_eq!(kept.local_addr().unwrap().port(), port); + + // Admit when peer verifier returns true, using retained listener + let listener = LoopbackBrowserListener::from_listener(kept, authority.into()).unwrap(); + let (stop_tx, stop_rx) = tokio::sync::oneshot::channel(); + let task = tokio::spawn(listener.run_with(hub.clone(), stop_rx, |_| true)); + let mut client = tokio::net::TcpStream::connect((Ipv4Addr::LOCALHOST, port)).await.unwrap(); + client + .write_all( + format!( + "GET /auth/web/info HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\ + X-Forwarded-Host: {authority}\r\nX-Forwarded-Proto: https\r\n\ + Tailscale-User-Login: person@example.com\r\n\r\n" + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut buf = Vec::new(); + client.read_to_end(&mut buf).await.unwrap(); + let text = String::from_utf8_lossy(&buf); + assert!(text.starts_with("HTTP/1.1 200 OK"), "{text}"); + let _ = stop_tx.send(()); + let _kept = task.await.unwrap().unwrap(); + } } #[cfg(target_os = "linux")] diff --git a/native/host/src/plat/mod.rs b/native/host/src/plat/mod.rs index 06ce2cf5ab..7b63384f2b 100644 --- a/native/host/src/plat/mod.rs +++ b/native/host/src/plat/mod.rs @@ -9,6 +9,64 @@ pub mod browser_peer; #[cfg(any(target_os = "linux", target_os = "macos"))] pub fn effective_uid() -> u32 { unsafe { libc::geteuid() } } + +pub(crate) fn is_tailscale_windows_exe_name(name: &str) -> bool { + let base = name.rsplit(['\\', '/']).next().unwrap_or(name); + base.eq_ignore_ascii_case("tailscaled.exe") + || base.eq_ignore_ascii_case("tailscale-ipn.exe") + || base.eq_ignore_ascii_case("tailscale.exe") +} + +pub(crate) fn is_trusted_tailscale_windows_path( + path: &str, + program_files: Option<&str>, + program_files_x86: Option<&str>, +) -> bool { + if !is_tailscale_windows_exe_name(path) { + return false; + } + let norm = |s: &str| { + s.trim() + .trim_end_matches(['\\', '/']) + .replace('/', "\\") + .to_ascii_lowercase() + }; + let p = norm(path); + let mut prefixes = vec![r"c:\program files\tailscale".to_string()]; + if let Some(pf) = program_files.filter(|s| !s.trim().is_empty()) { + prefixes.push(format!(r"{}\tailscale", norm(pf))); + } + if let Some(pf86) = program_files_x86.filter(|s| !s.trim().is_empty()) { + prefixes.push(format!(r"{}\tailscale", norm(pf86))); + } + prefixes.into_iter().any(|dir| { + p.strip_prefix(&format!(r"{dir}\")) + .is_some_and(|rest| !rest.is_empty() && !rest.contains('\\')) + }) +} + +/// Verify that an accepted loopback TCP connection belongs to the Tailscale daemon on Windows, +/// or is at least a genuine IPv4 loopback peer on platforms that use loopback fallback. +pub fn browser_loopback_peer_ok(stream: &tokio::net::TcpStream) -> bool { + let (Ok(local), Ok(remote)) = (stream.local_addr(), stream.peer_addr()) else { + return false; + }; + if !local.ip().is_loopback() + || !remote.ip().is_loopback() + || local.ip() != std::net::Ipv4Addr::LOCALHOST + || remote.ip() != std::net::Ipv4Addr::LOCALHOST + { + return false; + } + #[cfg(windows)] + { + return browser_peer::accepts(stream); + } + #[cfg(not(windows))] + { + true + } +} pub mod dirs; #[cfg(test)] pub mod tmp; diff --git a/native/host/src/plat/windows.rs b/native/host/src/plat/windows.rs index 9afc618612..9d336d93a6 100644 --- a/native/host/src/plat/windows.rs +++ b/native/host/src/plat/windows.rs @@ -491,6 +491,167 @@ pub mod net { } } +/// Windows IPv4 loopback peer authentication via GetExtendedTcpTable. +pub mod browser_peer { + use std::net::Ipv4Addr; + use windows_sys::Win32::{ + Foundation::{CloseHandle, ERROR_ACCESS_DENIED, ERROR_INSUFFICIENT_BUFFER, HANDLE, INVALID_HANDLE_VALUE}, + NetworkManagement::IpHelper::{ + GetExtendedTcpTable, MIB_TCPROW_OWNER_PID, MIB_TCPTABLE_OWNER_PID, + MIB_TCP_STATE_ESTAB, TCP_TABLE_OWNER_PID_CONNECTIONS, + }, + Networking::WinSock::AF_INET, + Security::{CreateWellKnownSid, EqualSid, GetTokenInformation, TokenUser, WinLocalSystemSid, PSID, TOKEN_QUERY, TOKEN_USER}, + System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS}, + System::Threading::{OpenProcess, OpenProcessToken, QueryFullProcessImageNameW, PROCESS_QUERY_LIMITED_INFORMATION}, + }; + + struct OwnedHandle(HANDLE); + impl Drop for OwnedHandle { + fn drop(&mut self) { + if !self.0.is_null() && self.0 != INVALID_HANDLE_VALUE { + unsafe { CloseHandle(self.0); } + } + } + } + + fn owning_pid(local_port: u16, remote_port: u16) -> Option { + let lo = u32::from_ne_bytes(Ipv4Addr::LOCALHOST.octets()); + let mut size = 16u32 * 1024; + for _ in 0..4 { + let mut buf = vec![0u64; (size as usize).div_ceil(8)]; + let rc = unsafe { + GetExtendedTcpTable( + buf.as_mut_ptr().cast(), + &mut size, + 0, + AF_INET as u32, + TCP_TABLE_OWNER_PID_CONNECTIONS, + 0, + ) + }; + if rc == ERROR_INSUFFICIENT_BUFFER { + continue; + } + if rc != 0 { + return None; + } + if (size as usize) < std::mem::size_of::() { + return None; + } + let table = unsafe { &*(buf.as_ptr().cast::()) }; + let count = table.dwNumEntries as usize; + let needed = std::mem::size_of::() + count.saturating_mul(std::mem::size_of::()); + if needed > buf.len() * 8 { + return None; + } + let rows = unsafe { std::slice::from_raw_parts(table.table.as_ptr(), count) }; + for row in rows { + if row.dwState == MIB_TCP_STATE_ESTAB as u32 + && row.dwLocalAddr == lo + && row.dwRemoteAddr == lo + && u16::from_be(row.dwLocalPort as u16) == remote_port + && u16::from_be(row.dwRemotePort as u16) == local_port + { + return Some(row.dwOwningPid); + } + } + return None; + } + None + } + + fn is_local_system_token(process: HANDLE) -> bool { + let mut token: HANDLE = std::ptr::null_mut(); + if unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) } == 0 || token.is_null() { + return false; + } + let _token_guard = OwnedHandle(token); + let mut len = 0u32; + unsafe { GetTokenInformation(token, TokenUser, std::ptr::null_mut(), 0, &mut len); } + if len == 0 || len > 4096 { + return false; + } + let mut buf = vec![0u8; len as usize]; + if unsafe { GetTokenInformation(token, TokenUser, buf.as_mut_ptr().cast(), len, &mut len) } == 0 { + return false; + } + let user = unsafe { &*(buf.as_ptr().cast::()) }; + let mut sys_sid = [0u8; 68]; + let mut sid_len = sys_sid.len() as u32; + if unsafe { CreateWellKnownSid(WinLocalSystemSid, std::ptr::null_mut(), sys_sid.as_mut_ptr() as PSID, &mut sid_len) } == 0 { + return false; + } + unsafe { EqualSid(user.User.Sid, sys_sid.as_ptr() as PSID) != 0 } + } + + fn process_image_path(process: HANDLE) -> Option { + let mut buf = vec![0u16; 1024]; + let mut len = buf.len() as u32; + if unsafe { QueryFullProcessImageNameW(process, 0, buf.as_mut_ptr(), &mut len) } == 0 || len == 0 { + return None; + } + Some(String::from_utf16_lossy(&buf[..len as usize])) + } + + fn snapshot_exe_name(pid: u32) -> Option { + let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }; + if snap == INVALID_HANDLE_VALUE || snap.is_null() { + return None; + } + let _snap_guard = OwnedHandle(snap); + let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() }; + entry.dwSize = std::mem::size_of::() as u32; + if unsafe { Process32FirstW(snap, &mut entry) } == 0 { + return None; + } + loop { + if entry.th32ProcessID == pid { + let end = entry.szExeFile.iter().position(|&c| c == 0).unwrap_or(entry.szExeFile.len()); + return Some(String::from_utf16_lossy(&entry.szExeFile[..end])); + } + if unsafe { Process32NextW(snap, &mut entry) } == 0 { + break; + } + } + None + } + + pub fn accepts(stream: &tokio::net::TcpStream) -> bool { + let (Ok(local), Ok(remote)) = (stream.local_addr(), stream.peer_addr()) else { + return false; + }; + if local.ip() != Ipv4Addr::LOCALHOST || remote.ip() != Ipv4Addr::LOCALHOST { + return false; + } + let Some(pid) = owning_pid(local.port(), remote.port()) else { + return false; + }; + if pid == 0 || pid == std::process::id() { + return false; + } + let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) }; + if !handle.is_null() { + let _guard = OwnedHandle(handle); + let Some(path) = process_image_path(handle) else { + return false; + }; + if !crate::plat::is_tailscale_windows_exe_name(&path) { + return false; + } + let pf = std::env::var("ProgramFiles").ok(); + let pf86 = std::env::var("ProgramFiles(x86)").ok(); + return crate::plat::is_trusted_tailscale_windows_path(&path, pf.as_deref(), pf86.as_deref()) + || is_local_system_token(handle); + } + if std::io::Error::last_os_error().raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) { + return snapshot_exe_name(pid) + .is_some_and(|name| name.eq_ignore_ascii_case("tailscaled.exe")); + } + false + } +} + /// The local socket KiCad's API listens on (nng `ipc://`): nng on Windows makes it the named pipe `\\.\pipe\`. pub mod ipc { use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeClient, NamedPipeServer, ServerOptions}; diff --git a/native/host/src/present/settings.rs b/native/host/src/present/settings.rs index 0f3ebd8748..c77c8f82ab 100644 --- a/native/host/src/present/settings.rs +++ b/native/host/src/present/settings.rs @@ -330,16 +330,17 @@ fn web_ui(st: &State, info: &Value) -> Vec { let status: Value = info["web.status"].as_str().and_then(|v| serde_json::from_str(v).ok()).unwrap_or(Value::Null); let enabled = set(st, "web.enabled", "") == "1"; let mut rows = Vec::new(); - let reason = status["reason"].as_str().unwrap_or(if cfg!(target_os = "linux") { "Browser access requires a verified Tailscale HTTPS connection." } else { "This release supports browser access on Linux hubs only." }); + let reason = status["reason"].as_str().unwrap_or("Browser access requires a verified Tailscale HTTPS connection."); let available = status["available"] == true; let buttons = if enabled || available || status["canEnable"] == true { vec![btn(if enabled { "Turn off" } else { "Turn on" }, "device-web-access", if enabled { "0" } else { "1" }, false)] } else { vec![] }; rows.push(row("Browser access", if available { "Pair a browser over HTTPS on your tailnet. A paired browser can use the terminal." } else { reason }, buttons)); if status["operatorRequired"] == true { - let command = r#"sudo tailscale set --operator="$(id -un)""#; + let command = status["operatorCommand"].as_str().unwrap_or(r#"sudo tailscale set --operator="$(id -un)""#); + let note = status["operatorNote"].as_str().unwrap_or("This user can manage Tailscale on this computer without sudo."); rows.push(row("Run once in your terminal", command, vec![btn("Copy", "copy", command, false)])); - rows.push(row("Operator permission", "This user can manage Tailscale on this computer without sudo.", vec![])); + rows.push(row("Operator permission", note, vec![])); } if enabled && !available { if let Some(command) = status["command"].as_str() { @@ -1285,6 +1286,16 @@ mod tests { assert_eq!(grant["buttons"][0]["action"], "copy"); assert_eq!(grant["buttons"][0]["value"], grant["note"]); assert_eq!(by(&rows,"Set up private HTTPS forwarding")["buttons"][0]["value"], "/usr/bin/tailscale serve"); + + let win_status = json!({ + "operatorRequired": true, + "operatorCommand": r#""C:\Program Files\Tailscale\tailscale.exe" serve --bg --https=8443 http://127.0.0.1:49231"#, + "operatorNote": "Run this command once in an Administrator terminal to set up HTTPS forwarding.", + "command": r#""C:\Program Files\Tailscale\tailscale.exe" serve --bg --https=8443 http://127.0.0.1:49231"# + }); + let win_rows = pg_rows("web", &[("web.enabled", "1")], json!({}), json!({"web.status": win_status.to_string()})); + assert_eq!(by(&win_rows, "Run once in your terminal")["note"], win_status["operatorCommand"]); + assert_eq!(by(&win_rows, "Operator permission")["note"], win_status["operatorNote"]); } #[test] fn web_ui_shows_only_the_active_address() { let address = "https://bp.example.ts.net"; @@ -1295,7 +1306,9 @@ mod tests { assert_eq!(link["note"], address); assert_eq!(link["qr"], json!(crate::net::qr::text(address).lines().collect::>())); let unavailable = pg_rows("web", &[], json!({}), json!({})); - assert_eq!(by(&unavailable, "Browser access")["buttons"][0]["value"], "1", "the switch is there whatever the hub knows of its web status"); + let switch = by(&unavailable, "Browser access"); + assert_eq!(switch["buttons"][0]["value"], "1", "the switch is there whatever the hub knows of its web status"); + assert!(!switch["note"].as_str().unwrap_or("").contains("Linux"), "all platforms support browser access"); } #[test] fn devices_an_invitation_shows_the_chosen_address_link_qr_code_and_expiry() { let r = dev_rows(json!({"@invite": invite3(false)}), json!({"devices": [], "invitations": [], "lan": [], "host": "127.0.0.1"})); diff --git a/native/host/src/proc.rs b/native/host/src/proc.rs index 868a367f1d..664dffdc66 100644 --- a/native/host/src/proc.rs +++ b/native/host/src/proc.rs @@ -562,7 +562,7 @@ mod tests { #[test] fn a_test_never_runs_the_real_tailscale() { let tmp = std::path::Path::new(if cfg!(windows) { "C:\\Users\\x\\AppData\\Local\\Temp" } else { "/tmp" }); - for p in ["tailscale", "tailscale.exe", "TailScale.EXE", "/usr/bin/tailscale", "C:\\Program Files\\Tailscale\\tailscale.exe", "C:/Program Files/Tailscale/tailscale.exe", "/tmp-evil/tailscale"] { + for p in ["tailscale", "tailscale.exe", "TailScale.EXE", "/usr/bin/tailscale", "/Applications/Tailscale.app/Contents/MacOS/Tailscale", "C:\\Program Files\\Tailscale\\tailscale.exe", "C:/Program Files/Tailscale/tailscale.exe", "/tmp-evil/tailscale"] { assert!(test_refusal(p, tmp).is_some(), "{p} would run the machine's tailscale"); } let standin = tmp.join("bp-ts-standin").join("tailscale"); let standin = standin.to_str().unwrap(); From 0bde51566677f3d803ddff5b62f90863e4f816df Mon Sep 17 00:00:00 2001 From: i2cjak Date: Tue, 24 Nov 2026 02:26:50 -0500 Subject: [PATCH 2/2] web: address cross-model review security and robustness findings --- native/host/src/net/tailnet.rs | 40 +++---- native/host/src/net/webprobe.rs | 27 +++-- native/host/src/net/webprovision.rs | 117 ++++++++++---------- native/host/src/net/webtransport.rs | 64 ++++++++--- native/host/src/plat/mod.rs | 162 +++++++++++++++++++++++++++- native/host/src/plat/windows.rs | 139 ++++++++++++++++-------- 6 files changed, 394 insertions(+), 155 deletions(-) diff --git a/native/host/src/net/tailnet.rs b/native/host/src/net/tailnet.rs index fe47f8fca9..95037499e4 100644 --- a/native/host/src/net/tailnet.rs +++ b/native/host/src/net/tailnet.rs @@ -185,7 +185,11 @@ pub fn resolve_tailscale_in( candidates.push(join_windows_path(pf86, r"Tailscale\tailscale.exe")); } if let Some(path) = path_env { - for dir in path.split(';').filter(|d| !d.is_empty()) { + for dir in path + .split(';') + .map(|d| d.trim().trim_matches('"')) + .filter(|d| !d.is_empty()) + { candidates.push(join_windows_path(dir, "tailscale.exe")); } } @@ -201,10 +205,10 @@ pub fn resolve_tailscale_in( candidates.into_iter().find(|p| is_executable(p)) } -/// Locate the system curl executable for HTTPS probe verification. +/// Locate the system curl executable for HTTPS probe verification using fixed OS locations only. pub fn resolve_curl_in( os: &str, - path_env: Option<&str>, + _path_env: Option<&str>, system_root: Option<&str>, is_executable: impl Fn(&std::path::Path) -> bool, ) -> Option { @@ -213,39 +217,18 @@ pub fn resolve_curl_in( "linux" => { candidates.push("/usr/bin/curl".into()); candidates.push("/bin/curl".into()); - if let Some(path) = path_env { - for dir in path.split(':').filter(|d| !d.is_empty()) { - candidates.push(std::path::Path::new(dir).join("curl")); - } - } } "macos" => { candidates.push("/usr/bin/curl".into()); - if let Some(path) = path_env { - for dir in path.split(':').filter(|d| !d.is_empty()) { - candidates.push(std::path::Path::new(dir).join("curl")); - } - } } "windows" => { let root = system_root - .map(str::trim) + .map(|s| s.trim().trim_matches('"')) .filter(|s| !s.is_empty()) .unwrap_or(r"C:\Windows"); candidates.push(join_windows_path(root, r"System32\curl.exe")); - if let Some(path) = path_env { - for dir in path.split(';').filter(|d| !d.is_empty()) { - candidates.push(join_windows_path(dir, "curl.exe")); - } - } - } - _ => { - if let Some(path) = path_env { - for dir in std::env::split_paths(path) { - candidates.push(dir.join("curl")); - } - } } + _ => {} } candidates.into_iter().find(|p| is_executable(p)) } @@ -462,7 +445,7 @@ mod tests { Some(Path::new(r"C:\Program Files\Tailscale\tailscale.exe").to_path_buf()) ); assert_eq!( - resolve_tailscale_in("windows", Some(r"C:\Tools"), None, None, None, false, has(&[r"C:\Tools\tailscale.exe"])), + resolve_tailscale_in("windows", Some(r#""C:\Tools";D:\Bin"#), None, None, None, false, has(&[r"C:\Tools\tailscale.exe"])), Some(Path::new(r"C:\Tools\tailscale.exe").to_path_buf()) ); @@ -480,7 +463,8 @@ mod tests { ); assert_eq!( resolve_curl_in("windows", Some(r"C:\Tools"), Some(r"C:\Windows"), has(&[r"C:\Tools\curl.exe"])), - Some(Path::new(r"C:\Tools\curl.exe").to_path_buf()) + None, + "verification must only trust system curl locations, not user PATH" ); } } diff --git a/native/host/src/net/webprobe.rs b/native/host/src/net/webprobe.rs index 90a3c2d9d4..2de3b9a6ad 100644 --- a/native/host/src/net/webprobe.rs +++ b/native/host/src/net/webprobe.rs @@ -9,7 +9,7 @@ use std::{ time::{Duration, Instant}, }; -static PENDING: Mutex> = Mutex::new(Weak::new()); +static PENDING: Mutex>> = Mutex::new(Vec::new()); pub struct Probe { home: PathBuf, authority: String, @@ -26,7 +26,12 @@ impl Probe { expires: Instant::now() + Duration::from_secs(30), consumed: AtomicBool::new(false), }); - *PENDING.lock().unwrap() = Arc::downgrade(&probe); + let mut pending = PENDING.lock().unwrap(); + pending.retain(|w| { + w.upgrade() + .is_some_and(|p| !(p.home == home && p.authority == authority)) + }); + pending.push(Arc::downgrade(&probe)); probe } pub fn header(&self) -> String { @@ -44,11 +49,19 @@ impl Probe { } } pub fn consume(home: &Path, authority: &str, nonce: &str) -> bool { - PENDING - .lock() - .unwrap() - .upgrade() - .is_some_and(|p| p.take(home, authority, nonce, Instant::now())) + let mut pending = PENDING.lock().unwrap(); + let mut matched = false; + pending.retain(|w| { + let Some(p) = w.upgrade() else { + return false; + }; + if p.take(home, authority, nonce, Instant::now()) { + matched = true; + return false; + } + true + }); + matched } #[cfg(test)] mod tests { diff --git a/native/host/src/net/webprovision.rs b/native/host/src/net/webprovision.rs index 1c1cea6092..c018200ac0 100644 --- a/native/host/src/net/webprovision.rs +++ b/native/host/src/net/webprovision.rs @@ -97,6 +97,8 @@ pub fn protected_directory(path: &std::path::Path) -> std::io::Result<()> { Ok(()) } +/// On Windows, directory permissions are governed by NTFS user profile ACLs; +/// verify that the runtime directory is an absolute, non-symlink/non-junction directory. #[cfg(windows)] pub fn protected_directory(path: &std::path::Path) -> std::io::Result<()> { use std::io; @@ -204,19 +206,24 @@ pub async fn https_address_answers(home: &std::path::Path, authority: &str) -> b }; let url = format!("https://{authority}/auth/web/setup"); let probe = super::webprobe::Probe::start(home, authority); - let Ok(mut child) = crate::proc::tokio_cmd(crate::proc::Kind::Net, &curl) + let mut cmd = crate::proc::tokio_cmd(crate::proc::Kind::Net, &curl); + cmd.args([ + "-q", + "--silent", + "--fail", + "--proto", + "=https", + "--noproxy", + "*", + "--max-time", + "5", + "--max-filesize", + "1024", + ]); + #[cfg(windows)] + cmd.arg("--ssl-revoke-best-effort"); + let Ok(mut child) = cmd .args([ - "-q", - "--silent", - "--fail", - "--proto", - "=https", - "--noproxy", - "*", - "--max-time", - "5", - "--max-filesize", - "1024", "--header", "@-", "--write-out", @@ -690,7 +697,7 @@ pub async fn monitor(hub: std::sync::Arc, ts: &dyn super::Tails let mut previous = Value::Null; let mut last_action = std::time::Instant::now(); let mut verification_failed = false; - let mut reserved_listener: Option = None; + let mut reserved_listener: Option> = None; loop { let enabled = hub.setting("web.enabled").await.as_deref() == Some("1"); let mut status_row = serde_json::json!({"canEnable":true}); @@ -728,6 +735,7 @@ pub async fn monitor(hub: std::sync::Arc, ts: &dyn super::Tails #[cfg(not(any(target_os = "linux", target_os = "macos")))] let use_unix = false; let target = if use_unix { + reserved_listener = None; if protected_directory(&canon_dir).is_err() { status_row["reason"] = Value::from("Web UI runtime directory permissions are too permissive."); None @@ -735,11 +743,14 @@ pub async fn monitor(hub: std::sync::Arc, ts: &dyn super::Tails Some(BackendTarget::Unix(canon_dir.join("browser.sock"))) } } else { + // Loopback Serve mappings persist across hub restarts so users do not need + // to re-approve forwarding each time; while running, `reserved_listener` + // keeps the port reserved until `Mapping::Absent` is confirmed on disable. let port = if let Some(ref listener) = reserved_listener { listener.local_addr().ok().map(|a| a.port()) } else if let Some(saved) = read_saved_port(&canon_dir) { if let Ok(tcp) = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, saved)).await { - reserved_listener = Some(tcp); + reserved_listener = Some(std::sync::Arc::new(tcp)); Some(saved) } else if configured_authority_for(&config, &service, node, &BackendTarget::Loopback(saved)).is_some() { Some(saved) @@ -754,7 +765,7 @@ pub async fn monitor(hub: std::sync::Arc, ts: &dyn super::Tails } else if let Ok(tcp) = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).await { let new_port = tcp.local_addr().ok().map(|a| a.port()).unwrap_or(0); if new_port != 0 && write_saved_port(&canon_dir, new_port).is_ok() { - reserved_listener = Some(tcp); + reserved_listener = Some(std::sync::Arc::new(tcp)); Some(BackendTarget::Loopback(new_port)) } else { None @@ -835,56 +846,44 @@ pub async fn monitor(hub: std::sync::Arc, ts: &dyn super::Tails #[cfg(not(unix))] BackendTarget::Unix(_) => {} BackendTarget::Loopback(port) => { - let tcp = match reserved_listener.take() { - Some(l) if l.local_addr().is_ok_and(|a| a.port() == port) => Ok(l), - other => { - drop(other); - tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, port)).await - } - }; - match tcp { - Ok(tcp) => { - if let Ok(listener) = super::webtransport::LoopbackBrowserListener::from_listener(tcp, authority.clone()) { - let (stop_tx, stop_rx) = tokio::sync::oneshot::channel(); - let mut task = tokio::spawn(listener.run(hub.clone(), stop_rx)); - let verified = https_address_answers(&hub.cfg.home, &authority).await; - if verified { - let active = serde_json::json!({"available":true, "address":format!("https://{authority}")}); - publish_status(&hub, &mut previous, active).await; - tokio::select! { - res = &mut task => { - if let Ok(Ok(kept)) = res { - reserved_listener = Some(kept); - } - } - _ = enabled_changed(&hub, &mut changes, true) => { - let _ = stop_tx.send(()); - if let Ok(Ok(Ok(kept))) = tokio::time::timeout(std::time::Duration::from_secs(2), &mut task).await { - reserved_listener = Some(kept); - } else { - task.abort(); - } + if !reserved_listener.as_ref().is_some_and(|l| l.local_addr().is_ok_and(|a| a.port() == port)) { + reserved_listener = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, port)) + .await + .ok() + .map(std::sync::Arc::new); + } + if let Some(ref tcp) = reserved_listener { + if let Ok(listener) = super::webtransport::LoopbackBrowserListener::from_listener(std::sync::Arc::clone(tcp), authority.clone()) { + let (stop_tx, stop_rx) = tokio::sync::oneshot::channel(); + let mut task = tokio::spawn(listener.run(hub.clone(), stop_rx)); + let verified = https_address_answers(&hub.cfg.home, &authority).await; + if verified { + let active = serde_json::json!({"available":true, "address":format!("https://{authority}")}); + publish_status(&hub, &mut previous, active).await; + tokio::select! { + _ = &mut task => (), + _ = enabled_changed(&hub, &mut changes, true) => { + let _ = stop_tx.send(()); + if tokio::time::timeout(std::time::Duration::from_secs(2), &mut task).await.is_err() { + task.abort(); } } - requested = None; - verification_failed = false; - last_action = std::time::Instant::now(); - continue; - } - verification_failed = true; - status_row["reason"] = Value::from("Private HTTPS forwarding could not be verified. Backplane will retry."); - let _ = stop_tx.send(()); - if let Ok(Ok(Ok(kept))) = tokio::time::timeout(std::time::Duration::from_secs(2), &mut task).await { - reserved_listener = Some(kept); - } else { - task.abort(); } + requested = None; + verification_failed = false; + last_action = std::time::Instant::now(); + continue; } - } - Err(_) => { verification_failed = true; - status_row["reason"] = Value::from("Local Web UI port is in use by another process. Turn Browser access off and back on to reset forwarding."); + status_row["reason"] = Value::from("Private HTTPS forwarding could not be verified. Backplane will retry."); + let _ = stop_tx.send(()); + if tokio::time::timeout(std::time::Duration::from_secs(2), &mut task).await.is_err() { + task.abort(); + } } + } else { + verification_failed = true; + status_row["reason"] = Value::from("Local Web UI port is in use by another process. Turn Browser access off and back on to reset forwarding."); } } } diff --git a/native/host/src/net/webtransport.rs b/native/host/src/net/webtransport.rs index d3ac496309..5849be5638 100644 --- a/native/host/src/net/webtransport.rs +++ b/native/host/src/net/webtransport.rs @@ -102,16 +102,16 @@ impl BrowserListener { /// Loopback TCP backend used when the OS Tailscale daemon serves via loopback /// (Windows, and macOS sandboxed App Store Tailscale without a root Unix socket). -/// Retains and returns the bound `TcpListener` on stop so the port cannot be -/// claimed by another local process before Serve teardown completes. +/// Borrows an `Arc` so the provisioning monitor keeps the socket +/// bound even if the accept task exits, aborts, or times out. pub(crate) struct LoopbackBrowserListener { - listener: tokio::net::TcpListener, + listener: Arc, authority: String, backend_port: u16, } impl LoopbackBrowserListener { - pub fn from_listener(listener: tokio::net::TcpListener, authority: String) -> io::Result { + pub fn from_listener(listener: Arc, authority: String) -> io::Result { validate_authority(&authority)?; let addr = listener.local_addr()?; if addr.ip() != Ipv4Addr::LOCALHOST || addr.port() == 0 { @@ -126,7 +126,9 @@ impl LoopbackBrowserListener { pub async fn bind(authority: String, port: u16) -> io::Result { validate_authority(&authority)?; - let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))).await?; + let listener = Arc::new( + tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))).await?, + ); Self::from_listener(listener, authority) } @@ -134,11 +136,16 @@ impl LoopbackBrowserListener { self.backend_port } + #[cfg(test)] + pub fn listener(&self) -> Arc { + Arc::clone(&self.listener) + } + pub async fn run( self, hub: Arc, stop: tokio::sync::oneshot::Receiver<()>, - ) -> io::Result { + ) -> io::Result<()> { self.run_with(hub, stop, crate::plat::browser_loopback_peer_ok).await } @@ -147,13 +154,14 @@ impl LoopbackBrowserListener { hub: Arc, mut stop: tokio::sync::oneshot::Receiver<()>, verify: F, - ) -> io::Result + ) -> io::Result<()> where F: Fn(&tokio::net::TcpStream) -> bool + Clone + Send + Sync + 'static, { + let verify_gate = Arc::new(tokio::sync::Semaphore::new(8)); loop { let stream = tokio::select! { - _ = &mut stop => return Ok(self.listener), + _ = &mut stop => return Ok(()), accepted = self.listener.accept() => match accepted { Ok((stream, _)) => stream, Err(e) if matches!(e.kind(), io::ErrorKind::ConnectionAborted | io::ErrorKind::Interrupted) => continue, @@ -164,8 +172,14 @@ impl LoopbackBrowserListener { Err(e) => return Err(e), } }; + let Ok(permit) = verify_gate.clone().try_acquire_owned() else { + continue; + }; let verify = verify.clone(); - let lookup = tokio::task::spawn_blocking(move || verify(&stream).then_some(stream)); + let lookup = tokio::task::spawn_blocking(move || { + let _permit = permit; + verify(&stream).then_some(stream) + }); if let Ok(Ok(Some(stream))) = tokio::time::timeout(Duration::from_millis(300), lookup).await { let authority = self.authority.clone(); let hub = hub.clone(); @@ -251,6 +265,28 @@ mod tests { assert!(!trusted(r"C:\Program Files\Tailscale\other.exe", None, None)); } + #[test] + fn macos_trusted_tailscale_path_and_netstat_parser() { + use crate::plat::{is_trusted_tailscale_macos_path as trusted, parse_macos_netstat_pid as parse_pid}; + assert!(trusted("/Applications/Tailscale.app/Contents/PlugIns/IPNExtension.appex/Contents/MacOS/IPNExtension", None)); + assert!(trusted("/Users/alex/Applications/Tailscale.app/Contents/MacOS/Tailscale", Some("/Users/alex"))); + assert!(trusted("/Library/SystemExtensions/1234/io.tailscale.ipn.macsys.network-extension.systemextension/Contents/MacOS/io.tailscale.ipn.macsys.network-extension", None)); + assert!(trusted("/opt/homebrew/bin/tailscaled", None)); + assert!(trusted("/opt/homebrew/Cellar/tailscale/1.80.0/bin/tailscaled", None)); + assert!(!trusted("/Applications/Tailscale.app/../Evil.app/MacOS/Evil", None)); + assert!(!trusted("/Users/bob/Downloads/tailscaled", Some("/Users/alex"))); + + let sample = "\ +Active Internet connections (including servers) +Proto Recv-Q Send-Q Local Address Foreign Address (state) rhiwat shiwat pid epid state options +tcp4 0 0 127.0.0.1.54321 127.0.0.1.49231 ESTABLISHED 131072 131072 4242 0 0x0102 0x00000000 +tcp4 0 0 127.0.0.1.49231 *.* LISTEN 131072 131072 999 0 0x0100 0x00000000 +"; + assert_eq!(parse_pid(sample, 49231, 54321), Some(4242)); + assert_eq!(parse_pid(sample, 49231, 55555), None); + assert_eq!(parse_pid(sample, 54321, 49231), None); + } + #[tokio::test] async fn loopback_listener_enforces_peer_check_and_retains_port_on_stop() { use serde_json::json; @@ -279,6 +315,7 @@ mod tests { // Reject when peer verifier returns false let listener = LoopbackBrowserListener::bind(authority.into(), 0).await.unwrap(); let port = listener.port(); + let kept = listener.listener(); let (stop_tx, stop_rx) = tokio::sync::oneshot::channel(); let task = tokio::spawn(listener.run_with(hub.clone(), stop_rx, |_| false)); let mut client = tokio::net::TcpStream::connect((Ipv4Addr::LOCALHOST, port)).await.unwrap(); @@ -297,11 +334,11 @@ mod tests { let _ = client.read_to_end(&mut buf).await; assert!(buf.is_empty(), "rejected peer must receive no HTTP response"); let _ = stop_tx.send(()); - let kept = task.await.unwrap().unwrap(); + task.await.unwrap().unwrap(); assert_eq!(kept.local_addr().unwrap().port(), port); - // Admit when peer verifier returns true, using retained listener - let listener = LoopbackBrowserListener::from_listener(kept, authority.into()).unwrap(); + // Admit when peer verifier returns true, using retained Arc + let listener = LoopbackBrowserListener::from_listener(Arc::clone(&kept), authority.into()).unwrap(); let (stop_tx, stop_rx) = tokio::sync::oneshot::channel(); let task = tokio::spawn(listener.run_with(hub.clone(), stop_rx, |_| true)); let mut client = tokio::net::TcpStream::connect((Ipv4Addr::LOCALHOST, port)).await.unwrap(); @@ -321,7 +358,8 @@ mod tests { let text = String::from_utf8_lossy(&buf); assert!(text.starts_with("HTTP/1.1 200 OK"), "{text}"); let _ = stop_tx.send(()); - let _kept = task.await.unwrap().unwrap(); + task.await.unwrap().unwrap(); + assert_eq!(kept.local_addr().unwrap().port(), port); } } diff --git a/native/host/src/plat/mod.rs b/native/host/src/plat/mod.rs index 7b63384f2b..070d235a39 100644 --- a/native/host/src/plat/mod.rs +++ b/native/host/src/plat/mod.rs @@ -45,8 +45,154 @@ pub(crate) fn is_trusted_tailscale_windows_path( }) } -/// Verify that an accepted loopback TCP connection belongs to the Tailscale daemon on Windows, -/// or is at least a genuine IPv4 loopback peer on platforms that use loopback fallback. +pub(crate) fn is_trusted_tailscale_macos_path(path: &str, home_dir: Option<&str>) -> bool { + let trimmed = path.trim(); + if trimmed.is_empty() || !trimmed.starts_with('/') { + return false; + } + if std::path::Path::new(trimmed) + .components() + .any(|c| matches!(c, std::path::Component::ParentDir)) + { + return false; + } + if trimmed.starts_with("/Applications/Tailscale.app/") { + return true; + } + if let Some(home) = home_dir.map(str::trim).filter(|h| h.starts_with('/')) { + let home = home.trim_end_matches('/'); + if trimmed.starts_with(&format!("{home}/Applications/Tailscale.app/")) { + return true; + } + } + if trimmed.starts_with("/Library/SystemExtensions/") + && trimmed + .split('/') + .any(|seg| seg.starts_with("io.tailscale.ipn.macsys")) + { + return true; + } + if matches!( + trimmed, + "/opt/homebrew/bin/tailscaled" | "/usr/local/bin/tailscaled" + ) { + return true; + } + for prefix in ["/opt/homebrew/Cellar/tailscale/", "/usr/local/Cellar/tailscale/"] { + if let Some(rest) = trimmed.strip_prefix(prefix) { + if let Some((_, tail)) = rest.split_once('/') { + if tail == "bin/tailscaled" { + return true; + } + } + } + } + false +} + +pub(crate) fn parse_macos_netstat_pid( + output: &str, + local_port: u16, + remote_port: u16, +) -> Option { + let want_local = format!("127.0.0.1.{remote_port}"); + let want_foreign = format!("127.0.0.1.{local_port}"); + let mut pid_col: usize = 8; + for line in output.lines() { + let cols: Vec<&str> = line.split_whitespace().collect(); + if let Some(state_idx) = cols.iter().position(|c| *c == "(state)") { + if let Some(pid_idx) = cols.iter().position(|c| *c == "pid") { + if pid_idx > state_idx { + pid_col = 5 + (pid_idx - state_idx); + } + } + continue; + } + if cols.first().copied() == Some("tcp4") + && cols.get(3).copied() == Some(want_local.as_str()) + && cols.get(4).copied() == Some(want_foreign.as_str()) + && cols.get(5).copied() == Some("ESTABLISHED") + { + if let Some(pid) = cols.get(pid_col).and_then(|s| s.parse::().ok()) { + if pid != 0 { + return Some(pid); + } + } + } + } + None +} + +#[cfg(target_os = "macos")] +mod macos_browser_peer { + use super::{effective_uid, is_trusted_tailscale_macos_path, parse_macos_netstat_pid}; + use std::net::Ipv4Addr; + + pub fn accepts(stream: &tokio::net::TcpStream) -> bool { + let (Ok(local), Ok(remote)) = (stream.local_addr(), stream.peer_addr()) else { + return false; + }; + if local.ip() != Ipv4Addr::LOCALHOST || remote.ip() != Ipv4Addr::LOCALHOST { + return false; + } + let Ok(out) = crate::proc::std_cmd(crate::proc::Kind::Local, "/usr/sbin/netstat") + .args(["-anv", "-p", "tcp"]) + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .output() + else { + return false; + }; + if !out.status.success() { + return false; + } + let stdout = String::from_utf8_lossy(&out.stdout); + let Some(pid) = parse_macos_netstat_pid(&stdout, local.port(), remote.port()) else { + return false; + }; + if pid == 0 || pid == std::process::id() { + return false; + } + let mut info: libc::proc_bsdshortinfo = unsafe { std::mem::zeroed() }; + let rc = unsafe { + libc::proc_pidinfo( + pid as libc::c_int, + libc::PROC_PIDT_SHORTBSDINFO, + 0, + (&mut info as *mut libc::proc_bsdshortinfo).cast(), + std::mem::size_of::() as libc::c_int, + ) + }; + if rc != std::mem::size_of::() as libc::c_int { + return false; + } + let uid = effective_uid(); + if info.pbsi_uid != 0 && info.pbsi_uid != uid { + return false; + } + let mut path_buf = vec![0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize]; + let plen = unsafe { + libc::proc_pidpath( + pid as libc::c_int, + path_buf.as_mut_ptr().cast(), + path_buf.len() as u32, + ) + }; + if plen <= 0 || (plen as usize) >= path_buf.len() { + return false; + } + let Ok(path) = std::str::from_utf8(&path_buf[..plen as usize]) else { + return false; + }; + let home = std::env::var("HOME").ok(); + if !is_trusted_tailscale_macos_path(path, home.as_deref()) { + return false; + } + stream.peer_addr().is_ok() + } +} + +/// Verify that an accepted loopback TCP connection belongs to the Tailscale daemon. pub fn browser_loopback_peer_ok(stream: &tokio::net::TcpStream) -> bool { let (Ok(local), Ok(remote)) = (stream.local_addr(), stream.peer_addr()) else { return false; @@ -62,9 +208,17 @@ pub fn browser_loopback_peer_ok(stream: &tokio::net::TcpStream) -> bool { { return browser_peer::accepts(stream); } - #[cfg(not(windows))] + #[cfg(target_os = "linux")] + { + return browser_peer::accepts(stream); + } + #[cfg(target_os = "macos")] + { + return macos_browser_peer::accepts(stream); + } + #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))] { - true + false } } pub mod dirs; diff --git a/native/host/src/plat/windows.rs b/native/host/src/plat/windows.rs index 9d336d93a6..7c4863bc1b 100644 --- a/native/host/src/plat/windows.rs +++ b/native/host/src/plat/windows.rs @@ -491,21 +491,48 @@ pub mod net { } } -/// Windows IPv4 loopback peer authentication via GetExtendedTcpTable. +/// Windows IPv4 loopback peer authentication via GetExtendedTcpTable and SCM/process identity checks. pub mod browser_peer { + use super::wide; use std::net::Ipv4Addr; use windows_sys::Win32::{ - Foundation::{CloseHandle, ERROR_ACCESS_DENIED, ERROR_INSUFFICIENT_BUFFER, HANDLE, INVALID_HANDLE_VALUE}, + Foundation::{CloseHandle, ERROR_INSUFFICIENT_BUFFER, HANDLE, INVALID_HANDLE_VALUE}, NetworkManagement::IpHelper::{ GetExtendedTcpTable, MIB_TCPROW_OWNER_PID, MIB_TCPTABLE_OWNER_PID, MIB_TCP_STATE_ESTAB, TCP_TABLE_OWNER_PID_CONNECTIONS, }, Networking::WinSock::AF_INET, Security::{CreateWellKnownSid, EqualSid, GetTokenInformation, TokenUser, WinLocalSystemSid, PSID, TOKEN_QUERY, TOKEN_USER}, - System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS}, System::Threading::{OpenProcess, OpenProcessToken, QueryFullProcessImageNameW, PROCESS_QUERY_LIMITED_INFORMATION}, }; + #[repr(C)] + struct ServiceStatusProcess { + dw_service_type: u32, + dw_current_state: u32, + dw_controls_accepted: u32, + dw_win32_exit_code: u32, + dw_service_specific_exit_code: u32, + dw_check_point: u32, + dw_wait_hint: u32, + dw_process_id: u32, + dw_service_flags: u32, + } + + #[link(name = "advapi32")] + extern "system" { + fn OpenSCManagerW(machine_name: *const u16, database_name: *const u16, desired_access: u32) -> HANDLE; + fn OpenServiceW(sc_manager: HANDLE, service_name: *const u16, desired_access: u32) -> HANDLE; + fn QueryServiceStatusEx( + service: HANDLE, + info_level: i32, + buffer: *mut u8, + buf_size: u32, + bytes_needed: *mut u32, + ) -> i32; + fn CloseServiceHandle(sc_object: HANDLE) -> i32; + } + struct OwnedHandle(HANDLE); impl Drop for OwnedHandle { fn drop(&mut self) { @@ -515,6 +542,49 @@ pub mod browser_peer { } } + struct OwnedScHandle(HANDLE); + impl Drop for OwnedScHandle { + fn drop(&mut self) { + if !self.0.is_null() { + unsafe { CloseServiceHandle(self.0); } + } + } + } + + fn tailscale_service_pid() -> Option { + const SC_MANAGER_CONNECT: u32 = 0x0001; + const SERVICE_QUERY_STATUS: u32 = 0x0004; + const SC_STATUS_PROCESS_INFO: i32 = 0; + const SERVICE_RUNNING: u32 = 4; + + let scm = unsafe { OpenSCManagerW(std::ptr::null(), std::ptr::null(), SC_MANAGER_CONNECT) }; + if scm.is_null() { + return None; + } + let _scm_guard = OwnedScHandle(scm); + let name = wide("Tailscale"); + let svc = unsafe { OpenServiceW(scm, name.as_ptr(), SERVICE_QUERY_STATUS) }; + if svc.is_null() { + return None; + } + let _svc_guard = OwnedScHandle(svc); + let mut status: ServiceStatusProcess = unsafe { std::mem::zeroed() }; + let mut needed = 0u32; + let ok = unsafe { + QueryServiceStatusEx( + svc, + SC_STATUS_PROCESS_INFO, + (&mut status as *mut ServiceStatusProcess).cast(), + std::mem::size_of::() as u32, + &mut needed, + ) + }; + if ok == 0 || status.dw_current_state != SERVICE_RUNNING || status.dw_process_id == 0 { + return None; + } + Some(status.dw_process_id) + } + fn owning_pid(local_port: u16, remote_port: u16) -> Option { let lo = u32::from_ne_bytes(Ipv4Addr::LOCALHOST.octets()); let mut size = 16u32 * 1024; @@ -594,29 +664,6 @@ pub mod browser_peer { Some(String::from_utf16_lossy(&buf[..len as usize])) } - fn snapshot_exe_name(pid: u32) -> Option { - let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }; - if snap == INVALID_HANDLE_VALUE || snap.is_null() { - return None; - } - let _snap_guard = OwnedHandle(snap); - let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() }; - entry.dwSize = std::mem::size_of::() as u32; - if unsafe { Process32FirstW(snap, &mut entry) } == 0 { - return None; - } - loop { - if entry.th32ProcessID == pid { - let end = entry.szExeFile.iter().position(|&c| c == 0).unwrap_or(entry.szExeFile.len()); - return Some(String::from_utf16_lossy(&entry.szExeFile[..end])); - } - if unsafe { Process32NextW(snap, &mut entry) } == 0 { - break; - } - } - None - } - pub fn accepts(stream: &tokio::net::TcpStream) -> bool { let (Ok(local), Ok(remote)) = (stream.local_addr(), stream.peer_addr()) else { return false; @@ -630,25 +677,29 @@ pub mod browser_peer { if pid == 0 || pid == std::process::id() { return false; } - let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) }; - if !handle.is_null() { - let _guard = OwnedHandle(handle); - let Some(path) = process_image_path(handle) else { - return false; - }; - if !crate::plat::is_tailscale_windows_exe_name(&path) { - return false; + let verified = if tailscale_service_pid() == Some(pid) { + true + } else { + let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) }; + if handle.is_null() { + false + } else { + let _guard = OwnedHandle(handle); + let Some(path) = process_image_path(handle) else { + return false; + }; + if !crate::plat::is_tailscale_windows_exe_name(&path) { + return false; + } + let pf = std::env::var("ProgramFiles").ok(); + let pf86 = std::env::var("ProgramFiles(x86)").ok(); + // A Tailscale binary running under LocalSystem (custom install dir) or inside Program Files is trusted. + crate::plat::is_trusted_tailscale_windows_path(&path, pf.as_deref(), pf86.as_deref()) + || is_local_system_token(handle) } - let pf = std::env::var("ProgramFiles").ok(); - let pf86 = std::env::var("ProgramFiles(x86)").ok(); - return crate::plat::is_trusted_tailscale_windows_path(&path, pf.as_deref(), pf86.as_deref()) - || is_local_system_token(handle); - } - if std::io::Error::last_os_error().raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) { - return snapshot_exe_name(pid) - .is_some_and(|name| name.eq_ignore_ascii_case("tailscaled.exe")); - } - false + }; + // Re-check the established tuple after verification to guard against PID reuse. + verified && owning_pid(local.port(), remote.port()) == Some(pid) } }