From a189d0ad3e74fa530dba4262e415faa0bbf03bad Mon Sep 17 00:00:00 2001 From: Aleksandr Bogomiakov Date: Wed, 25 Nov 2026 03:47:49 +0200 Subject: [PATCH] Preserve mesh transport through an internet exit in 1.0.3-rc1 On macOS a connected socket using the physical source lost its route before PF could see the packet. Fresh sockets could leave via the physical uplink, but Darwin rejected reverse-NAT replies delivered to a utun address there. With two live meshes remote control and data sessions expired within a minute. Install matching interface-scoped uplink routes before capturing the two unscoped defaults. Keep PF state on the physical interface, preserve transport ports and return tagged replies via loopback. Reconcile uplink changes and recover only owned routes using a private journal and kernel markers. On Windows keep existing LAN routes, retain recent verified reconnect paths and refresh the gateway and relay DNS without replacing the split defaults. Exercise two memberships of the same peer, new and established native transport sockets, ordinary application traffic and scoped route cleanup. Run hosted macOS and Windows native regressions on affected changes. Bump the packages to 1.0.3-rc1 and encode Debian prereleases with a tilde so apt can upgrade to the final release. Mesh wire formats and identities are unchanged. Checked workspace formatting, strict Clippy and the full workspace suite on macOS (586 passed, four opt-in tests skipped by default). The privileged macOS kernel test passed separately. A launchd trial of the RC kept master and ch reachable over both meshes and used the external exit past the original timeout. Disabling the exit restored the physical IP and cleared the routes. Linux ARM64 passed four real-agent exit tests and the privileged netns regression. The RC APK passed the dual-subnet UDP/ICMP test on an Android 37 ARM64 emulator. Verified Debian and pacman version ordering. Native Windows execution is covered by the hosted workflow and was not run on this Mac. --- .github/workflows/ci.yml | 4 +- .github/workflows/subnet-source.yml | 22 + Cargo.lock | 20 +- android/app/build.gradle | 2 +- crates/tsunagi-android/Cargo.toml | 4 +- crates/tsunagi-awg/Cargo.toml | 2 +- crates/tsunagi-core/Cargo.toml | 2 +- crates/tsunagi-core/src/agent/network.rs | 113 +++- .../src/overlay/hostrules/macos.rs | 37 +- .../src/overlay/hostrules/macos_exit.rs | 558 +++++++++++++++--- .../overlay/hostrules/macos_exit_kernel.rs | 339 +++++++++++ .../src/overlay/hostrules/macos_scoped.rs | 309 ++++++++++ .../src/overlay/hostrules/windows.rs | 127 +++- .../src/overlay/hostrules/windows_exit.rs | 138 ++++- crates/tsunagi-runtime/Cargo.toml | 12 +- crates/tsunagi-tcp-tls/Cargo.toml | 4 +- crates/tsunagi-tray/Cargo.toml | 4 +- crates/tsunagi-ui/Cargo.toml | 2 +- crates/tsunagi-wg-quic/Cargo.toml | 4 +- crates/tsunagi-wg-quic/tests/exit_node.rs | 80 ++- crates/tsunagi-wireguard/Cargo.toml | 4 +- crates/tsunagi/Cargo.toml | 12 +- crates/tsunagi/src/main.rs | 20 +- dist/deb/build-deb.sh | 4 +- dist/deb/test-deb.sh | 16 + dist/macos/README.md | 6 + docs/exit-node.md | 36 +- nix/package.nix | 2 +- 28 files changed, 1698 insertions(+), 185 deletions(-) create mode 100644 crates/tsunagi-core/src/overlay/hostrules/macos_exit_kernel.rs create mode 100644 crates/tsunagi-core/src/overlay/hostrules/macos_scoped.rs create mode 100644 dist/deb/test-deb.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 52d8f09..109d76d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,7 +2,7 @@ name: CI on: push: - branches: [main] + branches: [master, main] pull_request: workflow_dispatch: @@ -25,6 +25,8 @@ jobs: - uses: Swatinem/rust-cache@v2 - run: cargo fmt --all -- --check - run: cargo clippy --locked --workspace --all-targets -- -D warnings + - name: Check Debian release candidate upgrade ordering + run: bash dist/deb/test-deb.sh test: name: test (${{ matrix.os }}) diff --git a/.github/workflows/subnet-source.yml b/.github/workflows/subnet-source.yml index 7f551e0..b46741b 100644 --- a/.github/workflows/subnet-source.yml +++ b/.github/workflows/subnet-source.yml @@ -5,6 +5,8 @@ on: branches: [master] paths: - '.github/workflows/subnet-source.yml' + - 'crates/tsunagi-core/src/overlay/hostrules/macos*.rs' + - 'crates/tsunagi-core/src/overlay/hostrules/windows*.rs' - 'crates/tsunagi-core/src/overlay/provision/macos.rs' - 'crates/tsunagi-core/src/overlay/provision/windows.rs' - 'crates/tsunagi-core/src/overlay/provision/mod.rs' @@ -55,6 +57,15 @@ jobs: if: runner.os == 'macOS' shell: bash run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture + - name: Verify exit routing and PF translation on two real utuns + if: runner.os == 'macOS' + shell: bash + timeout-minutes: 2 + env: + EXIT_TEST: overlay::hostrules::macos_exit::kernel::exit_preserves_underlay_and_both_meshes + run: | + "$TEST_BINARY" --ignored --exact "$EXIT_TEST" --list | grep -Fx "$EXIT_TEST: test" + sudo -n -- "$TEST_BINARY" --ignored --exact "$EXIT_TEST" --nocapture - name: Verify source selection on a real Wintun adapter if: runner.os == 'Windows' shell: pwsh @@ -70,3 +81,14 @@ jobs: Copy-Item (Join-Path $directory 'wintun/bin/amd64/wintun.dll') (Split-Path -Parent $env:TEST_BINARY) & $env:TEST_BINARY --ignored --exact $env:TEST_NAME --nocapture exit $LASTEXITCODE + - name: Verify one Windows exit bypass route through the physical gateway + if: runner.os == 'Windows' + shell: pwsh + timeout-minutes: 2 + run: | + $test = 'overlay::hostrules::windows_exit::tests::windows_refresh_installs_only_the_external_test_address' + $listing = @(& $env:TEST_BINARY --ignored --exact $test --list) + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if ($listing -notcontains "${test}: test") { throw "Missing ignored test: $test" } + & $env:TEST_BINARY --ignored --exact $test --nocapture + exit $LASTEXITCODE diff --git a/Cargo.lock b/Cargo.lock index 1b06a22..7b793ba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "tsunagi" -version = "1.0.2" +version = "1.0.3-rc1" dependencies = [ "anstream", "anstyle", @@ -6320,7 +6320,7 @@ dependencies = [ [[package]] name = "tsunagi-android" -version = "1.0.2" +version = "1.0.3-rc1" dependencies = [ "bytes", "egui", @@ -6344,7 +6344,7 @@ dependencies = [ [[package]] name = "tsunagi-awg" -version = "1.0.2" +version = "1.0.3-rc1" dependencies = [ "bytes", "iroh", @@ -6359,7 +6359,7 @@ dependencies = [ [[package]] name = "tsunagi-core" -version = "1.0.2" +version = "1.0.3-rc1" dependencies = [ "arc-swap", "bytes", @@ -6402,7 +6402,7 @@ dependencies = [ [[package]] name = "tsunagi-runtime" -version = "1.0.2" +version = "1.0.3-rc1" dependencies = [ "tokio", "tracing", @@ -6415,7 +6415,7 @@ dependencies = [ [[package]] name = "tsunagi-tcp-tls" -version = "1.0.2" +version = "1.0.3-rc1" dependencies = [ "bytes", "caps", @@ -6435,7 +6435,7 @@ dependencies = [ [[package]] name = "tsunagi-tray" -version = "1.0.2" +version = "1.0.3-rc1" dependencies = [ "eframe", "egui-phosphor", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "tsunagi-ui" -version = "1.0.2" +version = "1.0.3-rc1" dependencies = [ "egui", "egui-phosphor", @@ -6461,7 +6461,7 @@ dependencies = [ [[package]] name = "tsunagi-wg-quic" -version = "1.0.2" +version = "1.0.3-rc1" dependencies = [ "boringtun", "bytes", @@ -6488,7 +6488,7 @@ dependencies = [ [[package]] name = "tsunagi-wireguard" -version = "1.0.2" +version = "1.0.3-rc1" dependencies = [ "boringtun", "bytes", diff --git a/android/app/build.gradle b/android/app/build.gradle index 6ffa6d9..891a58c 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -24,7 +24,7 @@ android { targetSdk 35 testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger() - versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.2') + versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.3-rc1') ndk { abiFilters abi } } } diff --git a/crates/tsunagi-android/Cargo.toml b/crates/tsunagi-android/Cargo.toml index 8290e6e..c07f924 100644 --- a/crates/tsunagi-android/Cargo.toml +++ b/crates/tsunagi-android/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-android" -version = "1.0.2" +version = "1.0.3-rc1" description = "Android VPN client and egui views for tsunagi." edition.workspace = true rust-version.workspace = true @@ -16,7 +16,7 @@ name = "vpn_source_probe" crate-type = ["cdylib"] [dependencies] -tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.2" } +tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.3-rc1" } tsunagi-ui = { path = "../tsunagi-ui" } tsunagi-core = { path = "../tsunagi-core" } tsunagi-wg-quic = { path = "../tsunagi-wg-quic" } diff --git a/crates/tsunagi-awg/Cargo.toml b/crates/tsunagi-awg/Cargo.toml index dfc5735..2d2907c 100644 --- a/crates/tsunagi-awg/Cargo.toml +++ b/crates/tsunagi-awg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-awg" -version = "1.0.2" +version = "1.0.3-rc1" description = "Ephemeral pairwise Amnezia transport for Tsunagi." edition.workspace = true rust-version.workspace = true diff --git a/crates/tsunagi-core/Cargo.toml b/crates/tsunagi-core/Cargo.toml index 152af90..8319c15 100644 --- a/crates/tsunagi-core/Cargo.toml +++ b/crates/tsunagi-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-core" -version = "1.0.2" +version = "1.0.3-rc1" description = "Small private mesh networks: persistent agent identity, deterministic network spaces, an iroh control plane, signed state and a local DNS view." readme = "../../README.md" keywords = ["mesh", "p2p", "iroh", "networking"] diff --git a/crates/tsunagi-core/src/agent/network.rs b/crates/tsunagi-core/src/agent/network.rs index 500b288..e4fece7 100644 --- a/crates/tsunagi-core/src/agent/network.rs +++ b/crates/tsunagi-core/src/agent/network.rs @@ -236,6 +236,54 @@ struct DialState { source: CandidateSource, } +/// Keep only paths that this runtime verified, long enough to reconnect when +/// a session goes away while the host sends its default traffic into the mesh. +#[derive(Default)] +struct VerifiedUnderlay { + peers: HashMap)>, +} + +impl VerifiedUnderlay { + fn record( + &mut self, + peer: EndpointId, + paths: impl IntoIterator, + now: Instant, + limit: usize, + ) { + let paths: Vec<_> = paths + .into_iter() + .filter(|p| { + matches!( + p, + PathAddr::Ip(std::net::SocketAddr::V4(_)) | PathAddr::Relay(_) + ) + }) + .take(limit) + .collect(); + if !paths.is_empty() { + self.peers.insert(peer, (now, paths)); + } + } + + fn prune(&mut self, now: Instant, limit: usize, retired: impl Fn(EndpointId) -> bool) { + self.peers.retain(|peer, (seen, _)| { + !retired(*peer) && now.duration_since(*seen) < Duration::from_secs(120) + }); + if self.peers.len() > limit { + let mut oldest: Vec<_> = self + .peers + .iter() + .map(|(peer, (seen, _))| (*seen, *peer)) + .collect(); + oldest.sort_unstable(); + for (_, peer) in oldest.into_iter().take(self.peers.len() - limit) { + self.peers.remove(&peer); + } + } + } +} + impl DialState { fn new(source: CandidateSource) -> Self { Self { @@ -313,6 +361,7 @@ struct Runtime { local_id: EndpointId, shutdown: Shutdown, sessions: HashMap, + verified_underlay: VerifiedUnderlay, dial_states: HashMap, candidate_addrs: HashMap, metrics: NetworkMetrics, @@ -441,6 +490,7 @@ impl Runtime { local_id, shutdown, sessions: HashMap::new(), + verified_underlay: VerifiedUnderlay::default(), dial_states: HashMap::new(), candidate_addrs: HashMap::new(), metrics: NetworkMetrics::default(), @@ -902,7 +952,7 @@ impl Runtime { /// on: the verified direct IPv4 paths of every control connection, and /// the relays in use. Only hosts that cannot exempt the agent from an /// exit node's default route read it. - async fn refresh_underlay(&self) { + async fn refresh_underlay(&mut self) { let Some(interface) = self .params .interface @@ -913,17 +963,38 @@ impl Runtime { }; let mut addresses = Vec::new(); let mut hosts = Vec::new(); - for session in self.sessions.values() { - for path in snapshot_connection(&session.conn).paths { - match path.remote { - PathAddr::Ip(std::net::SocketAddr::V4(socket)) => addresses.push(*socket.ip()), - PathAddr::Relay(url) => hosts.extend(relay_host(&url)), - _ => {} - } + let now = Instant::now(); + for (peer, session) in &self.sessions { + let mut paths = snapshot_connection(&session.conn).paths; + paths.sort_by_key(|path| !path.is_selected); + self.verified_underlay.record( + *peer, + paths.into_iter().map(|p| p.remote), + now, + self.params.limits.max_hints_per_peer, + ); + } + self.verified_underlay + .prune(now, self.params.limits.max_sessions_per_network, |peer| { + self.state.is_retired(&peer) + }); + for path in self + .verified_underlay + .peers + .values() + .flat_map(|(_, paths)| paths) + { + match path { + PathAddr::Ip(std::net::SocketAddr::V4(socket)) => addresses.push(*socket.ip()), + PathAddr::Relay(url) => hosts.extend(relay_host(url)), + _ => {} } } - for url in self.params.adapter.snapshot().relay_urls { - hosts.extend(relay_host(&url)); + // The endpoint stops advertising a disconnected relay, but still + // attempts to reconnect to it through the physical network. + use iroh::Watcher; + for relay in self.params.adapter.endpoint().home_relay_status().get() { + hosts.extend(relay_host(relay.url().as_str())); } interface .set_underlay(self.network_id, addresses, hosts) @@ -3434,6 +3505,28 @@ mod tests { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use super::*; + #[test] + fn verified_reconnect_paths_expire_and_are_replaced_without_admitting_candidates() { + let peer = crate::identity::DeviceIdentity::generate().endpoint_id(); + let addr = |last| PathAddr::Ip(([192, 0, 2, last], 7777).into()); + let now = Instant::now(); + let mut paths = VerifiedUnderlay::default(); + paths.record(peer, [addr(1), addr(2)], now, 1); + assert_eq!(paths.peers[&peer].1, [addr(1)]); + paths.record(peer, [addr(3)], now, 1); + paths.prune(now + Duration::from_secs(30), 1, |_| false); + assert_eq!(paths.peers[&peer].1, [addr(3)]); + let other = crate::identity::DeviceIdentity::generate().endpoint_id(); + paths.record(other, [addr(4)], now + Duration::from_secs(31), 1); + paths.prune(now + Duration::from_secs(32), 1, |_| false); + assert!(!paths.peers.contains_key(&peer)); + paths.prune(now + Duration::from_secs(32), 1, |p| p == other); + assert!(paths.peers.is_empty()); + paths.record(peer, [addr(5)], now, 1); + paths.prune(now + Duration::from_secs(121), 1, |_| false); + assert!(paths.peers.is_empty()); + } + #[test] fn underlay_hints_exclude_overlay_subnets_but_preserve_lan_and_relay_candidates() { let peer = crate::identity::DeviceIdentity::generate().endpoint_id(); diff --git a/crates/tsunagi-core/src/overlay/hostrules/macos.rs b/crates/tsunagi-core/src/overlay/hostrules/macos.rs index 3d3e4bd..21f7101 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/macos.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/macos.rs @@ -19,10 +19,10 @@ use crate::BoxFuture; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules}; -use super::macos_exit::{apply_plan, clear_all, run_tool}; +use super::macos_exit::{HostState, apply_plan, clear_all, refresh_client, run_tool}; use super::{BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, RuleOutcome}; /// The limited-broadcast destination routed through the overlay interface. @@ -68,17 +68,25 @@ fn firewall_todo(plan: &BroadcastRulesPlan) -> String { /// `pf` plus `route` for exit nodes (see [`super::macos_exit`]). #[derive(Debug, Default)] pub struct MacosHostRules { - /// The reference `pfctl -E` handed out, held while exit-node rules need - /// `pf` on and released when they are removed. - pub(super) pf_token: Arc>>, + /// The PF reference and the physical routes owned by this agent. + state: Arc, } impl MacosHostRules { - /// Creates the host rules. + /// Creates host rules with process-lifetime ownership. System services + /// use [`Self::with_state_dir`] for recovery after abrupt termination. pub fn new() -> Self { Self::default() } + /// Tie crash recovery to this agent's state directory, even when macOS + /// assigns its utun a different number on the next run. + pub fn with_state_dir(dir: &std::path::Path) -> Self { + Self { + state: Arc::new(HostState::with_state_dir(dir)), + } + } + /// Installs the route, replacing one this agent added earlier so the call /// can be repeated. The delete is best effort: a route that is not there /// is the state the add then reaches anyway. @@ -95,7 +103,7 @@ impl ExitHostRules for MacosHostRules { fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> { Box::pin(async move { let job_plan = plan.clone(); - let token = Arc::clone(&self.pf_token); + let token = Arc::clone(&self.state); tokio::task::spawn_blocking(move || apply_plan(&run_tool, &token, &job_plan)) .await .unwrap_or_else(|err| { @@ -113,10 +121,23 @@ impl ExitHostRules for MacosHostRules { }) } + fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option> { + Box::pin(async move { + if !plan.client { + return None; + } + let state = Arc::clone(&self.state); + let plan = plan.clone(); + tokio::task::spawn_blocking(move || refresh_client(&run_tool, &state, &plan)) + .await + .unwrap_or_else(|err| Some(RuleOutcome::Failed(err.to_string()))) + }) + } + fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> { Box::pin(async move { let name = interface.to_string(); - let token = Arc::clone(&self.pf_token); + let token = Arc::clone(&self.state); let _ = tokio::task::spawn_blocking(move || clear_all(&run_tool, &token, &name)).await; }) } diff --git a/crates/tsunagi-core/src/overlay/hostrules/macos_exit.rs b/crates/tsunagi-core/src/overlay/hostrules/macos_exit.rs index bf969fa..75249bd 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/macos_exit.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/macos_exit.rs @@ -16,9 +16,8 @@ //! evaluates `nat-anchor "com.apple/*"` and `anchor "com.apple/*"`, so the //! rules take effect without editing the user's ruleset. `pf` cannot say //! "every interface but one" in a translation address, so the egress is the -//! interface of the default route **when the rules are applied**; after the -//! default route moves (Wi-Fi to Ethernet) the rules are re-applied by -//! switching the exit node off and on, or restarting the agent. +//! interface of the physical default route. An active exit client refreshes +//! the rules when this egress changes. //! //! The kernel's `net.inet.ip.forwarding` is only read, never written: it //! changes how the whole host behaves, which is the owner's decision. @@ -29,21 +28,32 @@ //! Linux scheme does not carry over. Instead: //! //! ```text +//! route add -net 0.0.0.0/1 -ifscope +//! route add -net 128.0.0.0/1 -ifscope //! route add -net 0.0.0.0/1 -interface -ifa //! route add -net 128.0.0.0/1 -interface -ifa //! pass out quick on route-to ( ) inet proto { tcp udp } -//! from any to ! user -//! nat on inet from () to any -> () +//! from any to ! user tag no state +//! nat on inet from () to any tagged -> () static-port +//! pass out quick on reply-to (lo0 127.0.0.1) inet proto { tcp udp } +//! from any to any flags any tagged keep state (if-bound) //! ``` //! -//! The two halves outrank the default route without replacing it, and every -//! more specific route (LAN, another VPN) keeps working. The `route-to` rule +//! The scoped routes preserve the physical path for sockets that already +//! use its source address. The unscoped halves capture ordinary internet +//! traffic. More specific routes (LAN and active meshes) keep working. The `route-to` rule //! sends the *agent's own* traffic — QUIC, relay, DHT, which would otherwise //! loop into the tunnel it carries — back out the physical interface, and the //! translation gives it that interface's address, since an unbound socket -//! picked the overlay address when the route pointed at the overlay. Like the -//! Linux exemption this is by user id, so anything else running as root also -//! bypasses the tunnel. +//! picked the overlay address when the route pointed at the overlay. The +//! first pass is stateless: a floating `route-to` state would match again +//! on physical egress before PF could apply the translation. Only the egress +//! pass tracks the connection and reverses NAT on replies there. Once NAT +//! restores the socket's utun address, macOS's default hybrid end-system +//! model would discard the reply arriving over the physical interface. +//! `reply-to` delivers that state's replies locally through loopback. Like +//! the Linux exemption this is by user id, so anything else running as root +//! also bypasses the tunnel. //! //! IPv6 is blocked while an exit node is in use, as on Linux: `::/1` and //! `8000::/1` are rejecting routes, so applications fall back to IPv4 at once @@ -60,6 +70,13 @@ use crate::state::Ipv4Range; use super::RuleOutcome; use super::exit::{ExitHostPlan, ExitHostReport}; +#[cfg(all(test, target_os = "macos", feature = "tun-device"))] +#[path = "macos_exit_kernel.rs"] +mod kernel; +#[path = "macos_scoped.rs"] +mod scoped; +use scoped::ScopedRoutes; + /// The programs this module runs, always by absolute path. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum Tool { @@ -163,12 +180,27 @@ fn anchor_name(interface: &str) -> Result { } /// The default route as `route -n get default` reports it. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub(super) struct DefaultRoute { pub interface: String, pub gateway: Option, } +#[derive(Debug, Default)] +pub(super) struct HostState { + token: Mutex>, + routes: Mutex, +} + +impl HostState { + pub(super) fn with_state_dir(dir: &std::path::Path) -> Self { + Self { + routes: Mutex::new(ScopedRoutes::with_journal(dir.join("macos-exit-routes"))), + ..Self::default() + } + } +} + /// Reads `interface:` and `gateway:` out of `route -n get default`. fn parse_default_route(text: &str) -> Option { let field = |name: &str| { @@ -277,16 +309,11 @@ fn pf_rules( let out = &egress.interface; let mut nat = Vec::new(); let mut filter = Vec::new(); - for range in offer { - nat.push(format!("nat on {out} inet from {range} to any -> ({out})")); - filter.push(format!( - "pass in quick on {interface} inet from {range} to ! {range}" - )); - } let mut tables = Vec::new(); if let Some(client) = client { + let tag = format!("tsng_underlay_{interface}"); nat.push(format!( - "nat on {out} inet from ({interface}) to any -> ({out})" + "nat on {out} inet from ({interface}) to any tagged {tag} -> ({out}) static-port" )); let target = if client.overlay.is_empty() { "any".to_string() @@ -306,9 +333,23 @@ fn pf_rules( }; filter.push(format!( "pass out quick on {interface} route-to {via} inet proto {{ tcp udp }} \ - from any to {target} user {}", + from any to {target} user {} tag {tag} no state", client.uid )); + // A relay TCP stream may already be established when exit routing changes. + // Only responses to tagged underlay traffic get local loopback delivery. + filter.push(format!( + "pass out quick on {out} reply-to (lo0 127.0.0.1) inet proto {{ tcp udp }} \ + from any to any flags any tagged {tag} keep state (if-bound)" + )); + } + for range in offer { + // PF takes the first matching NAT rule. Preserve the transport's source + // port even when its overlay source falls inside one of our own offers. + nat.push(format!("nat on {out} inet from {range} to any -> ({out})")); + filter.push(format!( + "pass in quick on {interface} inet from {range} to ! {range}" + )); } tables .into_iter() @@ -368,10 +409,6 @@ fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { } } -fn flush_args(anchor: &str) -> Vec { - owned(&["-q", "-a", anchor, "-F", "all"]) -} - fn load_args(anchor: &str) -> Vec { owned(&["-q", "-a", anchor, "-f", "-"]) } @@ -381,6 +418,22 @@ const HALVES: [&str; 2] = ["0.0.0.0/1", "128.0.0.0/1"]; /// The IPv6 halves, made unreachable. const HALVES_V6: [&str; 2] = ["::/1", "8000::/1"]; +/// A scoped route is available to sockets already using this egress. It +/// coexists with the unscoped route for ordinary applications. +fn scoped_args(action: &str, prefix: &str, egress: &DefaultRoute) -> Vec { + let mut args = owned(&["-q", "-n", action, "-net", prefix]); + if let Some(gateway) = egress.gateway { + args.push(gateway.to_string()); + } else { + args.extend(owned(&["-interface", &egress.interface])); + } + args.extend(owned(&["-ifscope", &egress.interface])); + if action != "delete" { + args.push("-proto2".into()); + } + args +} + fn route_set_args( action: &str, half: &str, @@ -406,15 +459,56 @@ fn route_del_v6_args(half: &str) -> Vec { owned(&["-q", "-n", "delete", "-inet6", "-net", half, "::1"]) } +fn captures_half(run: Run<'_>, half: &str, interface: &str) -> bool { + run_ok(run, Tool::Route, &owned(&["-n", "get", "-net", half]), None).is_ok_and(|text| { + scoped::field(&text, "mask") == Some("128.0.0.0") + && scoped::field(&text, "interface") == Some(interface) + && !scoped::flag(&text, "IFSCOPE") + }) +} + /// Takes away the overlay default routes. Best effort: what is not there is /// the state wanted. fn clear_routes(run: Run<'_>, interface: &str) { for half in HALVES { - let _ = run(Tool::Route, &route_del_args(half, interface), None); + if captures_half(run, half, interface) { + let _ = run(Tool::Route, &route_del_args(half, interface), None); + } } +} + +fn ipv6_reject(run: Run<'_>, half: &str) -> Result, String> { + let args = owned(&["-n", "get", "-inet6", "-net", half]); + match run_ok(run, Tool::Route, &args, None) { + Ok(text) + if scoped::flag(&text, "REJECT") && scoped::field(&text, "gateway") == Some("::1") => + { + Ok(Some(text)) + } + Ok(_) => Ok(None), + Err(why) + if why.contains("not in table") + || why.contains("No such process") + || why.contains("Address family not supported") => + { + Ok(None) + } + Err(why) => Err(why), + } +} + +fn clear_v6(run: Run<'_>, scoped: &mut ScopedRoutes) -> Result<(), String> { + let Some(marker) = scoped.ipv6_marker() else { + return Ok(()); + }; for half in HALVES_V6 { - let _ = run(Tool::Route, &route_del_v6_args(half), None); + if ipv6_reject(run, half)?.is_some_and(|text| { + scoped::flag(&text, "PROTO2") && scoped::marker(&text) == Some(marker) + }) { + run_ok(run, Tool::Route, &route_del_v6_args(half), None)?; + } } + scoped.record_ipv6(false).map(|_| ()) } /// Installs a split default, or changes its source in place when the route @@ -431,17 +525,12 @@ fn set_half( &route_set_args("add", half, interface, source), None, ) { - Ok(_) => Ok(true), + Ok(_) if captures_half(run, half, interface) => Ok(true), + Ok(_) => Err(format!( + "the unscoped route for {half} does not use {interface}" + )), Err(why) if why.contains("File exists") => { - let lookup = run_ok(run, Tool::Route, &owned(&["-n", "get", "-net", half]), None) - .map_err(|inspect| format!("{why}; {inspect}"))?; - let field = |key: &str| { - lookup - .lines() - .filter_map(|line| line.trim().split_once(':')) - .find_map(|(name, value)| (name == key).then(|| value.trim())) - }; - if field("mask") != Some("128.0.0.0") || field("interface") != Some(interface) { + if !captures_half(run, half, interface) { return Err(why); } run_ok( @@ -456,7 +545,14 @@ fn set_half( } } -fn set_routes(run: Run<'_>, interface: &str, source: Option) -> Result<(), String> { +fn set_routes( + run: Run<'_>, + interface: &str, + source: Option, + scoped: &mut ScopedRoutes, +) -> Result<(), String> { + let already_using_v6 = scoped.ipv6_marker().is_some(); + let marker = scoped.record_ipv6(true)?; let mut added = Vec::new(); for half in HALVES { match set_half(run, half, interface, source) { @@ -466,31 +562,43 @@ fn set_routes(run: Run<'_>, interface: &str, source: Option) -> Result for half in added { let _ = run(Tool::Route, &route_del_args(half, interface), None); } + if !already_using_v6 { + scoped.record_ipv6(false)?; + } return Err(why); } } } for half in HALVES_V6 { - // A host without IPv6 has nothing to block; not a failure. - if let Err(why) = run_ok(run, Tool::Route, &route_add_v6_args(half), None) { - tracing::debug!(%why, "cannot block IPv6 for the exit node"); + let mut args = route_add_v6_args(half); + args.extend(["-proto2".into(), "-hopcount".into(), marker.to_string()]); + if let Err(why) = run_ok(run, Tool::Route, &args, None) { + if why.contains("Address family not supported") + || (why.contains("File exists") + && ipv6_reject(run, half).is_ok_and(|route| route.is_some())) + { + continue; + } + for half in added { + let _ = run(Tool::Route, &route_del_args(half, interface), None); + } + if !already_using_v6 { + clear_v6(run, scoped)?; + } + return Err(why); } } Ok(()) } /// Makes the host match the plan. -pub(super) fn apply_plan( - run: Run<'_>, - token: &Mutex>, - plan: &ExitHostPlan, -) -> ExitHostReport { +pub(super) fn apply_plan(run: Run<'_>, state: &HostState, plan: &ExitHostPlan) -> ExitHostReport { let forwarding = if plan.offer.is_empty() { None } else { forwarding_state(run) }; - let outcome = apply_rules(run, token, plan); + let outcome = apply_rules(run, state, plan, None); let verdict = |ok: bool, why: &str| { if ok { RuleOutcome::Applied @@ -522,12 +630,16 @@ pub(super) fn apply_plan( fn apply_rules( run: Run<'_>, - token: &Mutex>, + state: &HostState, plan: &ExitHostPlan, + checked_egress: Option, ) -> Result<(), String> { let interface = plan.interface.as_str(); let anchor = anchor_name(interface)?; - let egress = default_route(run, interface)?; + let egress = match checked_egress { + Some(egress) => egress, + None => default_route(run, interface)?, + }; let uid = if plan.client { Some(agent_uid(run)?) } else { @@ -539,30 +651,99 @@ fn apply_rules( }); let rules = pf_rules(interface, &egress, &plan.offer, client.as_ref()); - acquire_pf(run, token)?; + let mut scoped = lock(&state.routes); + scoped.load()?; + acquire_pf(run, &state.token)?; run_ok(run, Tool::Pfctl, &load_args(&anchor), Some(&rules)) .map_err(|why| format!("cannot load the pf rules: {why}"))?; // The routes come after the rules that keep the agent's own traffic off // them: the other order would loop for as long as it takes. if plan.client { - set_routes(run, interface, plan.client_source)?; + let previous = scoped.previous(); + let wanted = ScopedRoutes::desired(&egress); + let result = scoped + .ensure(run, &wanted) + .and_then(|()| set_routes(run, interface, plan.client_source, &mut scoped)); + if let Err(reason) = result { + // A same-interface gateway change may already have updated one + // scoped route. Restore the former gateway before dropping new adds. + if let Err(cleanup) = scoped + .ensure(run, &previous) + .and_then(|()| scoped.retain(run, &previous)) + { + return Err(format!( + "{reason}; restoring prior scoped routes failed: {cleanup}" + )); + } + return Err(reason); + } + scoped.retain(run, &wanted)?; + scoped.active = Some(egress); } else { clear_routes(run, interface); + clear_v6(run, &mut scoped)?; + scoped.retain(run, &[])?; + scoped.active = None; } Ok(()) } /// Removes everything this agent put there for the interface. -pub(super) fn clear_all(run: Run<'_>, token: &Mutex>, interface: &str) { +pub(super) fn clear_all(run: Run<'_>, state: &HostState, interface: &str) { + let mut scoped = lock(&state.routes); clear_routes(run, interface); + if let Err(why) = scoped + .load() + .and_then(|()| clear_v6(run, &mut scoped)) + .and_then(|()| scoped.retain(run, &[])) + { + tracing::warn!(%why, "cannot remove scoped exit routes"); + } + scoped.active = None; if let Ok(anchor) = anchor_name(interface) { // Flushing an anchor nothing was ever loaded into is not an error // worth reporting. - if let Err(why) = run_ok(run, Tool::Pfctl, &flush_args(&anchor), None) { + if let Err(why) = run_ok(run, Tool::Pfctl, &load_args(&anchor), Some("")) { tracing::debug!(%why, "cannot flush the exit node pf anchor"); } } - release_pf(run, token); + release_pf(run, &state.token); +} + +/// The logical plan can be unchanged while Wi-Fi changes gateway or moves +/// to Ethernet. Rebuild both PF and physical scope against that new egress. +pub(super) fn refresh_client( + run: Run<'_>, + state: &HostState, + plan: &ExitHostPlan, +) -> Option { + if !plan.client || !lock(&state.routes).check_due(std::time::Instant::now()) { + return None; + } + let egress = match default_route(run, &plan.interface) { + Ok(egress) => egress, + Err(reason) => return Some(RuleOutcome::Failed(reason)), + }; + { + let mut routes = lock(&state.routes); + if routes.active.as_ref() == Some(&egress) { + // A physical link may reconnect with the same name and gateway + // after the kernel has discarded that interface's scoped routes. + if let Err(reason) = routes.ensure(run, &ScopedRoutes::desired(&egress)) { + return Some(RuleOutcome::Failed(reason)); + } + if HALVES + .iter() + .all(|half| captures_half(run, half, &plan.interface)) + { + return None; + } + } + } + Some(match apply_rules(run, state, plan, Some(egress)) { + Ok(()) => RuleOutcome::Applied, + Err(reason) => RuleOutcome::Failed(reason), + }) } #[cfg(test)] @@ -601,6 +782,9 @@ destination: default\n\ pf_load_fails: bool, route_add_fails: bool, half_interface: Option<&'static str>, + v6: RefCell>, + capture: RefCell>, + scoped: RefCell>, pf_enable_output: &'static str, } @@ -615,6 +799,9 @@ destination: default\n\ pf_load_fails: false, route_add_fails: false, half_interface: None, + v6: RefCell::default(), + capture: RefCell::default(), + scoped: RefCell::default(), pf_enable_output: "pf enabled\nToken : 4242\n", } } @@ -638,11 +825,64 @@ destination: default\n\ match tool { Tool::Id => ok("0\n", ""), Tool::Sysctl => ok(self.forwarding, ""), + Tool::Route if args.iter().any(|a| a == "-inet6") => { + let half = args[args.iter().position(|a| a == "-net").unwrap() + 1].clone(); + let mut table = self.v6.borrow_mut(); + if args.iter().any(|a| a == "get") { + return table.get(&half).map_or_else(|| fail("not in table"),|marker| + ok(&format!("gateway: ::1\nflags: \nhopcount mtu\n{marker} 16384\n"),"")); + } + if args.iter().any(|a| a == "delete") { + table.remove(&half); + } else if let std::collections::btree_map::Entry::Vacant(entry) = + table.entry(half) + { + entry.insert(args.last().unwrap().parse().unwrap()); + } else { + return fail("File exists"); + } + ok("", "") + } + Tool::Route if args.iter().any(|a| a == "-ifscope") => { + let after = |name: &str| { + args.iter() + .position(|a| a == name) + .map(|i| args[i + 1].clone()) + }; + let scope = after("-ifscope").unwrap(); + let prefix = after("-net").unwrap(); + let key = (scope.clone(), prefix.clone()); + let mut table = self.scoped.borrow_mut(); + if args.iter().any(|a| a == "get") { + return table + .get(&key) + .map_or_else(|| fail("not in table"), |text| ok(text, "")); + } + if args.iter().any(|a| a == "delete") { + table.remove(&key); + } else { + let gateway = args + .iter() + .find(|a| a.parse::().is_ok()) + .cloned() + .unwrap_or_default(); + let marker = after("-hopcount").unwrap(); + table.insert(key, format!("destination: {}\nmask: 128.0.0.0\ninterface: {scope}\ngateway: {gateway}\nflags: \nhopcount mtu\n{marker} 1500\n", prefix.split('/').next().unwrap())); + } + ok("", "") + } Tool::Route if args.iter().any(|arg| arg == "get") && args.iter().any(|arg| arg == "-net") => { - match self.half_interface { + let half = args.last().unwrap(); + match self + .capture + .borrow() + .get(half) + .map(String::as_str) + .or(self.half_interface) + { Some(name) => ok(&format!("mask: 128.0.0.0\ninterface: {name}\n"), ""), None => fail("not in table"), } @@ -656,12 +896,31 @@ destination: default\n\ Tool::Route if args.contains(&"add".to_string()) && ((self.route_add_fails && args.iter().any(|a| a == HALVES[1])) + || args.iter().any(|a| self.capture.borrow().contains_key(a)) || (self.half_interface.is_some() && HALVES.iter().any(|half| args.iter().any(|a| a == half)))) => { // Darwin route can return success after a routing-socket write failed. ok("", "route: writing to routing socket: File exists") } + Tool::Route if args.iter().any(|a| a == "-interface") => { + let half = args + .iter() + .position(|a| a == "-net") + .map(|i| args[i + 1].clone()) + .unwrap(); + let iface = args + .iter() + .position(|a| a == "-interface") + .map(|i| args[i + 1].clone()) + .unwrap(); + if args.iter().any(|a| a == "delete") { + self.capture.borrow_mut().remove(&half); + } else { + self.capture.borrow_mut().insert(half, iface); + } + ok("", "") + } Tool::Route => ok("", ""), Tool::Pfctl if self.pf_missing => Ran::Missing, Tool::Pfctl if args == ["-E"] => ok("", self.pf_enable_output), @@ -741,7 +1000,27 @@ destination: default\n\ } #[test] - fn using_sends_the_agents_own_traffic_back_out_the_physical_interface() { + fn the_agents_tagged_nat_precedes_any_general_masquerade_for_offered_ranges() { + let ranges = [range()]; + let client = ClientRules { + uid: 0, + overlay: &ranges, + }; + let text = pf_rules("utun5", &egress(), &ranges, Some(&client)); + let mut nat = text.lines().filter(|line| line.starts_with("nat ")); + assert!( + nat.next() + .unwrap() + .ends_with("tagged tsng_underlay_utun5 -> (en0) static-port") + ); + assert_eq!( + nat.next(), + Some("nat on en0 inet from 10.13.37.0/24 to any -> (en0)") + ); + } + + #[test] + fn using_keeps_the_reroute_and_the_physical_nat_in_separate_pf_passes() { let other: Ipv4Range = "10.99.0.0/16".parse().unwrap(); let overlay = [range(), other]; let client = ClientRules { @@ -755,19 +1034,17 @@ destination: default\n\ ), "{text}" ); - assert!( - text.contains("nat on en0 inet from (utun5) to any -> (en0)\n"), - "{text}" - ); - assert!( - text.contains( + let rules: Vec<_> = text.lines().skip(1).collect(); + assert_eq!( + rules, + [ + "nat on en0 inet from (utun5) to any tagged tsng_underlay_utun5 -> (en0) static-port", "pass out quick on utun5 route-to (en0 192.168.1.1) inet proto { tcp udp } \ - from any to ! user 0\n" - ), - "{text}" + from any to ! user 0 tag tsng_underlay_utun5 no state", + "pass out quick on en0 reply-to (lo0 127.0.0.1) inet proto { tcp udp } from any to any flags any \ + tagged tsng_underlay_utun5 keep state (if-bound)", + ] ); - // Only the agent's user, and only what is not the overlay. - assert!(!text.contains("from any to any")); let direct = DefaultRoute { interface: "ppp0".into(), @@ -789,6 +1066,10 @@ destination: default\n\ #[test] fn the_overlay_default_routes_are_halves_and_ipv6_is_rejected() { + assert_eq!( + scoped_args("add", "128.0.0.0/1", &egress()).join(" "), + "-q -n add -net 128.0.0.0/1 192.168.1.1 -ifscope en0 -proto2" + ); assert_eq!( route_set_args("add", "0.0.0.0/1", "utun5", None).join(" "), "-q -n add -net 0.0.0.0/1 -interface utun5" @@ -818,7 +1099,7 @@ destination: default\n\ #[test] fn offering_loads_the_anchor_and_reads_but_never_writes_forwarding() { let fake = Fake::new(); - let token = Mutex::new(None); + let token = HostState::default(); let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false)); assert_eq!(report.offer, vec![(range(), RuleOutcome::Applied)]); assert_eq!(report.forwarding, Some(true)); @@ -845,14 +1126,14 @@ destination: default\n\ ); // No client routes were added for an offer alone. assert_eq!(fake.count(" add "), 0); - assert_eq!(token.lock().unwrap().as_deref(), Some("4242")); + assert_eq!(token.token.lock().unwrap().as_deref(), Some("4242")); } #[test] fn forwarding_off_is_reported_and_unreadable_is_none() { let mut fake = Fake::new(); fake.forwarding = "0\n"; - let token = Mutex::new(None); + let token = HostState::default(); let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false)); assert_eq!(report.forwarding, Some(false)); fake.forwarding = "junk"; @@ -863,12 +1144,18 @@ destination: default\n\ #[test] fn the_client_rules_are_loaded_before_the_routes_that_need_them() { let fake = Fake::new(); - let token = Mutex::new(None); + let token = HostState::default(); let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(false, true)); assert_eq!(report.client, Some(RuleOutcome::Applied)); assert!(report.offer.is_empty()); let load = fake.position("-f -").unwrap(); - let add = fake.position(" add -net 0.0.0.0/1").unwrap(); + let scoped = fake + .position(" add -net 128.0.0.0/1 192.168.1.1 -ifscope en0") + .unwrap(); + let add = fake + .position(" add -net 0.0.0.0/1 -interface utun5") + .unwrap(); + assert!(load < scoped && scoped < add); assert!(load < add, "{:?}", fake.calls()); assert!(fake.position("add -net 128.0.0.0/1").is_some()); assert!(fake.position("-inet6 -net ::/1 ::1 -reject").is_some()); @@ -880,17 +1167,19 @@ destination: default\n\ #[test] fn both_exit_halves_use_the_selected_networks_address_on_a_shared_utun() { let fake = Fake::new(); - let token = Mutex::new(None); + let token = HostState::default(); let mut selected = plan(false, true); selected.overlay.push("10.99.0.0/24".parse().unwrap()); - for source in ["10.99.0.17", "10.13.37.34"] { + for (action, source) in [("add", "10.99.0.17"), ("change", "10.13.37.34")] { selected.client_source = Some(source.parse().unwrap()); let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &selected); assert_eq!(report.client, Some(RuleOutcome::Applied)); for half in HALVES { assert!( - fake.position(&format!("add -net {half} -interface utun5 -ifa {source}")) - .is_some() + fake.position(&format!( + "{action} -net {half} -interface utun5 -ifa {source}" + )) + .is_some() ); } } @@ -902,7 +1191,11 @@ destination: default\n\ selected.client_source = Some("10.99.0.17".parse().unwrap()); let mut fake = Fake::new(); fake.half_interface = Some("utun5"); - let report = apply_plan(&|t, a, s| fake.run(t, a, s), &Mutex::new(None), &selected); + let report = apply_plan( + &|t, a, s| fake.run(t, a, s), + &HostState::default(), + &selected, + ); assert_eq!(report.client, Some(RuleOutcome::Applied)); for half in HALVES { assert!( @@ -918,19 +1211,104 @@ destination: default\n\ foreign.half_interface = Some("utun9"); let report = apply_plan( &|t, a, s| foreign.run(t, a, s), - &Mutex::new(None), + &HostState::default(), &selected, ); assert!(matches!(report.client, Some(RuleOutcome::Failed(_)))); assert_eq!(foreign.count(" change "), 0); - assert_eq!(foreign.count(" delete "), 0); + assert!( + foreign.scoped.borrow().is_empty(), + "new scoped routes were rolled back" + ); + assert_eq!(foreign.count("delete -net 0.0.0.0/1 -interface utun9"), 0); + } + + #[test] + fn restart_cleans_scoped_routes_by_journal_and_kernel_marker_even_on_a_new_utun() { + let fake = Fake::new(); + let dir = tempfile::tempdir().unwrap(); + let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s); + let state = HostState::with_state_dir(dir.path()); + assert_eq!( + apply_plan(&run, &state, &plan(false, true)).client, + Some(RuleOutcome::Applied) + ); + assert_eq!(fake.scoped.borrow().len(), 2); + // An administrator replaces one of the two routes before we restart. + for ((_, half), listing) in fake.scoped.borrow_mut().iter_mut() { + if half == HALVES[0] { + *listing = listing.replace("PROTO2", "STATIC"); + } + } + drop(state); + clear_all(&run, &HostState::with_state_dir(dir.path()), "utun9"); + assert_eq!(fake.scoped.borrow().len(), 1); + assert!( + fake.scoped + .borrow() + .contains_key(&("en0".into(), HALVES[0].into())) + ); + assert!(!dir.path().join("macos-exit-routes").exists()); + } + + #[test] + fn cleanup_preserves_an_ipv6_reject_installed_by_another_owner() { + let fake = Fake::new(); + fake.v6.borrow_mut().insert("::/1".into(), 0); + let dir = tempfile::tempdir().unwrap(); + let state = HostState::with_state_dir(dir.path()); + let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s); + assert_eq!( + apply_plan(&run, &state, &plan(false, true)).client, + Some(RuleOutcome::Applied) + ); + assert_eq!(fake.v6.borrow().len(), 2); + clear_all(&run, &HostState::with_state_dir(dir.path()), "utun9"); + assert_eq!( + fake.v6.borrow().keys().cloned().collect::>(), + ["::/1"] + ); + } + + #[test] + fn refreshing_a_changed_gateway_updates_pf_and_replaces_only_our_previous_scope() { + let mut fake = Fake::new(); + let state = HostState::default(); + let plan = plan(false, true); + assert_eq!( + apply_plan(&|t, a, s| fake.run(t, a, s), &state, &plan).client, + Some(RuleOutcome::Applied) + ); + fake.default_route = Some( + DEFAULT_ROUTE + .replace("en0", "en1") + .replace("192.168.1.1", "10.0.0.1"), + ); + assert_eq!( + refresh_client(&|t, a, s| fake.run(t, a, s), &state, &plan), + Some(RuleOutcome::Applied) + ); + assert_eq!(fake.scoped.borrow().len(), 2); + assert!( + fake.scoped + .borrow() + .keys() + .all(|(interface, _)| interface == "en1") + ); + assert!( + fake.stdins + .borrow() + .last() + .unwrap() + .contains("route-to (en1 10.0.0.1)") + ); } #[test] fn no_routes_are_added_when_the_rules_did_not_load() { let mut fake = Fake::new(); fake.pf_load_fails = true; - let token = Mutex::new(None); + let token = HostState::default(); let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, true)); let Some(RuleOutcome::Failed(why)) = report.client else { panic!("{report:?}"); @@ -947,7 +1325,7 @@ destination: default\n\ fn a_failing_route_is_a_failure_and_leaves_nothing_behind() { let mut fake = Fake::new(); fake.route_add_fails = true; - let token = Mutex::new(None); + let token = HostState::default(); let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(false, true)); let Some(RuleOutcome::Failed(why)) = report.client else { panic!("{report:?}"); @@ -970,7 +1348,7 @@ destination: default\n\ fn a_missing_pfctl_or_default_route_says_what_is_wrong() { let mut fake = Fake::new(); fake.pf_missing = true; - let token = Mutex::new(None); + let token = HostState::default(); let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false)); let RuleOutcome::Failed(why) = &report.offer[0].1 else { panic!("{report:?}"); @@ -991,7 +1369,7 @@ destination: default\n\ fn a_default_route_through_the_overlay_is_refused() { let mut fake = Fake::new(); fake.default_route = Some("gateway: 10.13.37.1\ninterface: utun5\n".into()); - let token = Mutex::new(None); + let token = HostState::default(); let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false)); let RuleOutcome::Failed(why) = &report.offer[0].1 else { panic!("{report:?}"); @@ -1002,7 +1380,7 @@ destination: default\n\ #[test] fn pf_is_enabled_once_and_released_once_on_clear() { let fake = Fake::new(); - let token = Mutex::new(None); + let token = HostState::default(); let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s); apply_plan(&run, &token, &plan(true, false)); apply_plan(&run, &token, &plan(true, true)); @@ -1010,15 +1388,12 @@ destination: default\n\ clear_all(&run, &token, "utun5"); assert_eq!(fake.count("Pfctl -X 4242"), 1); - assert!( - fake.position("-a com.apple/tsunagi-exit-utun5 -F all") - .is_some() - ); + assert_eq!(fake.stdins.borrow().last().map(String::as_str), Some("")); assert!( fake.position("delete -net 0.0.0.0/1 -interface utun5") .is_some() ); - assert_eq!(*token.lock().unwrap(), None); + assert_eq!(*token.token.lock().unwrap(), None); // A second clear has nothing to release and still succeeds. clear_all(&run, &token, "utun5"); assert_eq!(fake.count("Pfctl -X"), 1); @@ -1027,10 +1402,15 @@ destination: default\n\ #[test] fn dropping_the_client_removes_its_routes() { let fake = Fake::new(); - let token = Mutex::new(None); + let token = HostState::default(); let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s); + assert_eq!( + apply_plan(&run, &token, &plan(false, true)).client, + Some(RuleOutcome::Applied) + ); + let adds = fake.count(" add "); apply_plan(&run, &token, &plan(true, false)); assert!(fake.position("delete -net 0.0.0.0/1").is_some()); - assert_eq!(fake.count(" add "), 0); + assert_eq!(fake.count(" add "), adds); } } diff --git a/crates/tsunagi-core/src/overlay/hostrules/macos_exit_kernel.rs b/crates/tsunagi-core/src/overlay/hostrules/macos_exit_kernel.rs new file mode 100644 index 0000000..c11c1ef --- /dev/null +++ b/crates/tsunagi-core/src/overlay/hostrules/macos_exit_kernel.rs @@ -0,0 +1,339 @@ +//! Privileged macOS regression. Both ends are throwaway utuns; only a /30 +//! inside the simulated uplink is captured when switching the exit on. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::net::Ipv4Addr; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use bytes::Bytes; +use smoltcp::wire::{IpProtocol, Ipv4Packet, Ipv4Repr, TcpPacket, TcpSeqNumber, UdpPacket}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpStream, UdpSocket}; +use tokio::time::timeout; + +use super::*; +use crate::overlay::Cidr; +use crate::overlay::provision::{InterfacePlan, InterfaceProvisioner, UtunProvisioner}; +use crate::overlay::tun::TunDevice; + +const UPLINK: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 1); +const REMOTE: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 6); +const CAPTURE: &str = "192.0.2.4/30"; +const FIRST: Ipv4Addr = Ipv4Addr::new(198, 18, 222, 1); +const SECOND: Ipv4Addr = Ipv4Addr::new(198, 19, 222, 1); +const WAIT: Duration = Duration::from_secs(5); + +async fn utun(addresses: &[Ipv4Addr]) -> Arc { + let cidrs = addresses + .iter() + .map(|ip| Cidr::new((*ip).into(), 28).unwrap()) + .collect(); + UtunProvisioner::new() + .unwrap() + .reconcile(&InterfacePlan::new("test", 1280, cidrs)) + .await + .unwrap() + .device + .unwrap() +} + +struct Capture<'a> { + overlay: &'a str, + uplink: DefaultRoute, + anchor: String, + token: Mutex>, + added_route: bool, + added_scoped: bool, +} + +impl Drop for Capture<'_> { + fn drop(&mut self) { + if self.added_route { + let _ = run_tool(Tool::Route, &route_del_args(CAPTURE, self.overlay), None); + } + if self.added_scoped { + let _ = run_tool( + Tool::Route, + &scoped_args("delete", CAPTURE, &self.uplink), + None, + ); + } + // Loading an empty ruleset removes just this temporary anchor's rules. + let _ = run_tool(Tool::Pfctl, &load_args(&self.anchor), Some("")); + release_pf(&run_tool, &self.token); + } +} + +impl Capture<'_> { + fn enable(&mut self) { + let ranges = [FIRST, SECOND] + .map(|ip| Ipv4Range::new(Ipv4Addr::from(u32::from(ip) & !0xf), 28).unwrap()); + let rules = pf_rules( + self.overlay, + &self.uplink, + &[], + Some(&ClientRules { + uid: 0, + overlay: &ranges, + }), + ); + acquire_pf(&run_tool, &self.token).unwrap(); + run_ok( + &run_tool, + Tool::Pfctl, + &load_args(&self.anchor), + Some(&rules), + ) + .unwrap(); + run_ok( + &run_tool, + Tool::Route, + &scoped::marked_args("add", CAPTURE, &self.uplink, 114275), + None, + ) + .unwrap(); + self.added_scoped = true; + run_ok( + &run_tool, + Tool::Route, + &route_set_args("add", CAPTURE, self.overlay, Some(SECOND)), + None, + ) + .unwrap(); + self.added_route = true; + } +} + +/// Ignore interface housekeeping and pure TCP ACKs while waiting for our packet. +async fn packet( + device: &dyn TunDevice, + destination: Ipv4Addr, + protocol: IpProtocol, + port: u16, + payload: &[u8], +) -> Bytes { + timeout(WAIT, async { + loop { + let raw = device.recv().await.expect("utun closed"); + let Ok(ip) = Ipv4Packet::new_checked(&raw[..]) else { + continue; + }; + if ip.version() != 4 || ip.dst_addr() != destination || ip.next_header() != protocol { + continue; + } + let matches = match protocol { + IpProtocol::Udp => UdpPacket::new_checked(ip.payload()) + .is_ok_and(|udp| udp.dst_port() == port && udp.payload() == payload), + IpProtocol::Tcp => TcpPacket::new_checked(ip.payload()).is_ok_and(|tcp| { + tcp.dst_port() == port + && tcp.payload() == payload + && (tcp.syn() || !payload.is_empty()) + }), + _ => false, + }; + if matches { + return raw; + } + } + }) + .await + .unwrap_or_else(|_| { + panic!( + "no {protocol} packet for {destination}:{port} on {}", + device.name() + ) + }) +} + +fn reply(request: &[u8]) -> Bytes { + let ip = Ipv4Packet::new_checked(request).unwrap(); + let tcp_request = (ip.next_header() == IpProtocol::Tcp) + .then(|| TcpPacket::new_checked(ip.payload()).unwrap()); + // Acknowledge TCP SYNs and echo data so the test observes return traffic + // on the very socket that originated each flow. + let reply_ip = Ipv4Repr { + src_addr: ip.dst_addr(), + dst_addr: ip.src_addr(), + next_header: ip.next_header(), + payload_len: tcp_request + .as_ref() + .map_or(ip.payload().len(), |tcp| 20 + tcp.payload().len()), + hop_limit: 64, + }; + let mut bytes = vec![0; reply_ip.buffer_len() + reply_ip.payload_len]; + let mut out = Ipv4Packet::new_unchecked(&mut bytes[..]); + reply_ip.emit(&mut out, &Default::default()); + let src = reply_ip.src_addr.into(); + let dst = reply_ip.dst_addr.into(); + if let Some(incoming) = tcp_request { + let mut tcp = TcpPacket::new_unchecked(out.payload_mut()); + tcp.set_header_len(20); + tcp.set_src_port(incoming.dst_port()); + tcp.set_dst_port(incoming.src_port()); + tcp.set_syn(incoming.syn()); + tcp.set_ack(true); + tcp.set_seq_number(if incoming.syn() { + TcpSeqNumber(100) + } else { + incoming.ack_number() + }); + tcp.set_ack_number(incoming.seq_number() + incoming.segment_len()); + tcp.set_window_len(8192); + tcp.payload_mut().copy_from_slice(incoming.payload()); + tcp.fill_checksum(&src, &dst); + } else { + out.payload_mut().copy_from_slice(ip.payload()); + let mut udp = UdpPacket::new_unchecked(out.payload_mut()); + let (src_port, dst_port) = (udp.dst_port(), udp.src_port()); + udp.set_src_port(src_port); + udp.set_dst_port(dst_port); + udp.fill_checksum(&src, &dst); + } + bytes.into() +} + +async fn open_tcp(uplink: &dyn TunDevice, port: u16) -> TcpStream { + let connect = TcpStream::connect((REMOTE, port)); + let peer = async { + let syn = packet(uplink, REMOTE, IpProtocol::Tcp, port, &[]).await; + assert_eq!( + Ipv4Packet::new_checked(&syn[..]).unwrap().src_addr(), + UPLINK + ); + uplink.send(reply(&syn)).await.unwrap(); + }; + let (stream, ()) = tokio::join!(timeout(WAIT, connect), peer); + stream.expect("SYN-ACK did not reach socket").unwrap() +} + +fn check_capture_routes(overlay: &str, uplink: &str) { + for (scope, expected) in [(vec![], overlay), (owned(&["-ifscope", uplink]), uplink)] { + let mut args = owned(&["-n", "get"]); + args.extend(scope); + args.extend(owned(&["-net", CAPTURE])); + let output = run_ok(&run_tool, Tool::Route, &args, None).unwrap(); + eprintln!("route {}:\n{output}", args.join(" ")); + let actual = output + .lines() + .find_map(|line| line.trim().strip_prefix("interface: ")); + assert_eq!(actual, Some(expected)); + assert_eq!(output.contains("PROTO2"), expected == uplink); + assert_eq!(output.contains("IFSCOPE"), expected == uplink); + assert_eq!( + output.split_whitespace().any(|s| s == "114275"), + expected == uplink + ); + } +} + +async fn udp_round_trip(uplink: &dyn TunDevice, socket: &UdpSocket, stage: &str) { + let port = socket.peer_addr().unwrap().port(); + eprintln!("{stage}: UDP {}", socket.local_addr().unwrap()); + socket + .send(b"QUIC path") + .await + .unwrap_or_else(|e| panic!("{stage}: sending UDP: {e}")); + let raw = packet(uplink, REMOTE, IpProtocol::Udp, port, b"QUIC path").await; + let ip = Ipv4Packet::new_checked(&raw[..]).unwrap(); + assert_eq!(ip.src_addr(), UPLINK); + assert_eq!( + UdpPacket::new_checked(ip.payload()).unwrap().src_port(), + socket.local_addr().unwrap().port() + ); + uplink.send(reply(&raw)).await.unwrap(); + let mut buf = [0; 64]; + let len = timeout(WAIT, socket.recv(&mut buf)) + .await + .expect("UDP reply did not reach socket") + .unwrap(); + assert_eq!(&buf[..len], b"QUIC path"); +} + +#[tokio::test] +#[ignore = "requires root, the stock Apple PF anchor, and a disposable macOS runner"] +async fn exit_preserves_underlay_and_both_meshes() { + assert_eq!(agent_uid(&run_tool).unwrap(), 0); + let uplink = utun(&[UPLINK]).await; + let overlay = utun(&[FIRST, SECOND]).await; + + let mut relay = open_tcp(&*uplink, 8001).await; + let existing_quic = UdpSocket::bind((UPLINK, 0)).await.unwrap(); + existing_quic.connect((REMOTE, 8006)).await.unwrap(); + udp_round_trip(&*uplink, &existing_quic, "before exit").await; + let mut capture = Capture { + overlay: overlay.name(), + uplink: DefaultRoute { + interface: uplink.name().to_owned(), + gateway: Some(Ipv4Addr::new(192, 0, 2, 2)), + }, + anchor: anchor_name(overlay.name()).unwrap(), + token: Mutex::new(None), + added_route: false, + added_scoped: false, + }; + capture.enable(); + check_capture_routes(overlay.name(), uplink.name()); + udp_round_trip(&*uplink, &existing_quic, "existing socket after exit").await; + + // An already established relay must preserve its address and port. + relay.write_all(b"established relay").await.unwrap(); + let established = packet( + &*uplink, + REMOTE, + IpProtocol::Tcp, + 8001, + b"established relay", + ) + .await; + let ip = Ipv4Packet::new_checked(&established[..]).unwrap(); + let tcp = TcpPacket::new_checked(ip.payload()).unwrap(); + assert_eq!(ip.src_addr(), UPLINK); + assert_eq!(tcp.src_port(), relay.local_addr().unwrap().port()); + uplink.send(reply(&established)).await.unwrap(); + let mut echo = [0; b"established relay".len()]; + timeout(WAIT, relay.read_exact(&mut echo)) + .await + .expect("established TCP reply did not reach socket") + .unwrap(); + assert_eq!(&echo, b"established relay"); + + // The kernel selects the overlay source on new wildcard sockets. Real + // replies to the translated address must reach those same sockets. + let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap(); + socket.connect((REMOTE, 8002)).await.unwrap(); + assert_eq!(socket.local_addr().unwrap().ip(), SECOND); + udp_round_trip(&*uplink, &socket, "new socket after exit").await; + let new_relay = open_tcp(&*uplink, 8003).await; + assert_eq!(new_relay.local_addr().unwrap().ip(), SECOND); + + // Same destination, ordinary UID: external traffic must enter the exit. + let program = "import socket, sys\nsocket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(b'ordinary', (sys.argv[1], 8004))"; + let mut child = tokio::process::Command::new("/usr/bin/python3"); + child + .uid(65534) + .gid(65534) + .args(["-I", "-c", program, &REMOTE.to_string()]) + .kill_on_drop(true); + assert!( + timeout(WAIT, child.status()) + .await + .unwrap() + .unwrap() + .success() + ); + let ordinary = packet(&*overlay, REMOTE, IpProtocol::Udp, 8004, b"ordinary").await; + assert_eq!( + Ipv4Packet::new_checked(&ordinary[..]).unwrap().src_addr(), + SECOND + ); + + // Root traffic to either mesh also stays on the overlay with its own alias. + let mesh = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap(); + for local in [FIRST, SECOND] { + let peer = Ipv4Addr::from(u32::from(local) + 1); + mesh.send_to(b"mesh", (peer, 8005)).await.unwrap(); + let raw = packet(&*overlay, peer, IpProtocol::Udp, 8005, b"mesh").await; + assert_eq!(Ipv4Packet::new_checked(&raw[..]).unwrap().src_addr(), local); + } +} diff --git a/crates/tsunagi-core/src/overlay/hostrules/macos_scoped.rs b/crates/tsunagi-core/src/overlay/hostrules/macos_scoped.rs new file mode 100644 index 0000000..9d1baee --- /dev/null +++ b/crates/tsunagi-core/src/overlay/hostrules/macos_scoped.rs @@ -0,0 +1,309 @@ +//! Route ownership survives the process that installed the scoped physical +//! routes. A pre-existing compatible route may be used, never adopted. +use super::*; +use std::fs; +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub(super) struct ScopedHalf { + half: u8, + egress: DefaultRoute, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +struct Journal { + marker: u32, + routes: Vec, + ipv6: bool, +} + +#[derive(Debug)] +pub(super) struct ScopedRoutes { + journal: Option, + loaded: bool, + owned: Journal, + pub(super) active: Option, + checked: Option, +} + +impl Default for ScopedRoutes { + fn default() -> Self { + Self { + journal: None, + loaded: false, + owned: Journal { + marker: rand::random_range(1..i32::MAX as u32), + routes: Vec::new(), + ipv6: false, + }, + active: None, + checked: None, + } + } +} + +pub(super) fn marked_args( + action: &str, + prefix: &str, + egress: &DefaultRoute, + marker: u32, +) -> Vec { + let mut args = scoped_args(action, prefix, egress); + // Darwin exposes this otherwise unused route metric through RTM_GET. + // The nonce separates routes made by independent agents on the same uplink. + args.extend(["-hopcount".into(), marker.to_string()]); + args +} + +pub(super) fn field<'a>(text: &'a str, key: &str) -> Option<&'a str> { + text.lines() + .filter_map(|l| l.trim().split_once(':')) + .find_map(|(k, v)| (k == key).then(|| v.trim())) +} + +pub(super) fn flag(text: &str, name: &str) -> bool { + field(text, "flags").is_some_and(|v| v.trim_matches(['<', '>']).split(',').any(|f| f == name)) +} + +pub(super) fn marker(text: &str) -> Option { + let mut lines = text.lines(); + while let Some(line) = lines.next() { + if let Some(i) = line.split_whitespace().position(|v| v == "hopcount") { + return lines.next()?.split_whitespace().nth(i)?.parse().ok(); + } + } + None +} + +/// A scoped lookup can return an unscoped LAN route or a default. Only an +/// exact scoped /1 on the requested interface can be ours. +fn inspect( + run: Run<'_>, + route: &ScopedHalf, +) -> Result)>, String> { + let args = owned(&[ + "-n", + "get", + "-ifscope", + &route.egress.interface, + "-net", + HALVES[route.half as usize], + ]); + let text = match run_ok(run, Tool::Route, &args, None) { + Ok(text) => text, + Err(err) + if err.contains("not in table") + || err.contains("No such process") + || err.contains("bad interface name") => + { + return Ok(None); + } + Err(err) => return Err(err), + }; + let destination = field(&text, "destination"); + let correct_half = match route.half { + 0 => matches!(destination, Some("default" | "0.0.0.0")), + _ => destination == Some("128.0.0.0"), + }; + if !correct_half || field(&text, "mask") != Some("128.0.0.0") || !flag(&text, "IFSCOPE") { + return Ok(None); + } + let actual = parse_default_route(&text).ok_or("could not read scoped route interface")?; + if actual.interface != route.egress.interface { + return Ok(None); + } + let mark = flag(&text, "PROTO2").then(|| marker(&text)).flatten(); + Ok(Some((actual, mark))) +} + +impl ScopedRoutes { + pub(super) fn with_journal(path: PathBuf) -> Self { + Self { + journal: Some(path), + ..Self::default() + } + } + + pub(super) fn load(&mut self) -> Result<(), String> { + if self.loaded { + return Ok(()); + } + if let Some(path) = &self.journal { + match fs::File::open(path) { + Ok(file) => { + let mut bytes = Vec::new(); + file.take(4097) + .read_to_end(&mut bytes) + .map_err(|e| e.to_string())?; + if bytes.len() > 4096 { + return Err("oversized macOS exit route journal".into()); + } + let data: Journal = postcard::from_bytes(&bytes) + .map_err(|e| format!("invalid macOS exit route journal: {e}"))?; + if data.marker == 0 + || data.routes.len() > 8 + || data + .routes + .iter() + .any(|r| r.half > 1 || !safe_name(&r.egress.interface)) + { + return Err("invalid macOS exit route ownership".into()); + } + self.owned = data; + } + Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} + Err(err) => return Err(err.to_string()), + } + } + self.loaded = true; + Ok(()) + } + + fn save(&self) -> Result<(), String> { + let Some(path) = &self.journal else { + return Ok(()); + }; + if self.owned.routes.is_empty() && !self.owned.ipv6 { + return match fs::remove_file(path) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.to_string()), + }; + } + let tmp = path.with_extension(format!("{}.tmp", rand::random::())); + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let bytes = postcard::to_allocvec(&self.owned).map_err(|err| err.to_string())?; + let mut file = options.open(&tmp).map_err(|err| err.to_string())?; + let result = file.write_all(&bytes).and_then(|()| fs::rename(&tmp, path)); + if result.is_err() { + let _ = fs::remove_file(tmp); + } + result.map_err(|e| e.to_string()) + } + + pub(super) fn previous(&self) -> Vec { + self.owned.routes.clone() + } + + pub(super) fn ipv6_marker(&self) -> Option { + self.owned.ipv6.then_some(self.owned.marker) + } + + pub(super) fn record_ipv6(&mut self, active: bool) -> Result { + if self.owned.ipv6 != active { + self.owned.ipv6 = active; + if let Err(why) = self.save() { + self.owned.ipv6 = !active; + return Err(why); + } + } + Ok(self.owned.marker) + } + + pub(super) fn desired(egress: &DefaultRoute) -> Vec { + [0, 1] + .map(|half| ScopedHalf { + half, + egress: egress.clone(), + }) + .into() + } + + pub(super) fn check_due(&mut self, now: Instant) -> bool { + if self + .checked + .is_some_and(|last| now.duration_since(last) < Duration::from_secs(15)) + { + return false; + } + self.checked = Some(now); + true + } + + pub(super) fn ensure(&mut self, run: Run<'_>, wanted: &[ScopedHalf]) -> Result<(), String> { + for route in wanted { + let current = inspect(run, route)?; + let action = match current { + Some((actual, tag)) + if actual == route.egress + && (tag.is_none() + || tag == Some(self.owned.marker) + && self.owned.routes.contains(route)) => + { + continue; + } + Some((actual, Some(tag))) + if tag == self.owned.marker + && self.owned.routes.contains(&ScopedHalf { + half: route.half, + egress: actual.clone(), + }) => + { + "change" + } + Some(_) => { + return Err(format!( + "scoped route {} on {} already belongs to another route owner", + HALVES[route.half as usize], route.egress.interface + )); + } + None => "add", + }; + if !self.owned.routes.contains(route) { + if self.owned.routes.len() >= 8 { + return Err("too many unreconciled scoped exit routes".into()); + } + self.owned.routes.push(route.clone()); + if let Err(reason) = self.save() { + self.owned.routes.pop(); + return Err(reason); + } + } + run_ok( + run, + Tool::Route, + &marked_args( + action, + HALVES[route.half as usize], + &route.egress, + self.owned.marker, + ), + None, + )?; + if inspect(run, route)? != Some((route.egress.clone(), Some(self.owned.marker))) { + return Err(format!( + "the scoped route for {} on {} failed ownership verification", + HALVES[route.half as usize], route.egress.interface + )); + } + } + Ok(()) + } + + pub(super) fn retain(&mut self, run: Run<'_>, keep: &[ScopedHalf]) -> Result<(), String> { + for route in self.previous() { + if keep.contains(&route) { + continue; + } + if inspect(run, &route)? == Some((route.egress.clone(), Some(self.owned.marker))) { + run_ok( + run, + Tool::Route, + &scoped_args("delete", HALVES[route.half as usize], &route.egress), + None, + )?; + } + self.owned.routes.retain(|r| r != &route); + if let Err(reason) = self.save() { + self.owned.routes.push(route); + return Err(reason); + } + } + Ok(()) + } +} diff --git a/crates/tsunagi-core/src/overlay/hostrules/windows.rs b/crates/tsunagi-core/src/overlay/hostrules/windows.rs index e9b5fb9..e02aace 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/windows.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/windows.rs @@ -28,6 +28,10 @@ #![cfg_attr(not(target_os = "windows"), allow(dead_code))] use crate::BoxFuture; +use std::collections::{BTreeMap, HashMap}; +use std::net::Ipv4Addr; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules}; use super::windows_exit; @@ -119,7 +123,7 @@ fn run_powershell(script: &str) -> Result<(), String> { } /// Runs a script and returns what it printed, or what it said on failure. -fn run_powershell_output(script: &str) -> Result { +pub(super) fn run_powershell_output(script: &str) -> Result { let output = std::process::Command::new(powershell_path()) .args([ "-NoProfile", @@ -153,12 +157,61 @@ async fn step(what: &'static str, script: String) -> RuleOutcome { /// The Windows implementation, through PowerShell. #[derive(Debug, Default)] -pub struct WindowsHostRules; +pub struct WindowsHostRules { + relay_cache: Arc>, +} impl WindowsHostRules { /// Creates it. Nothing is run until [`BroadcastHostRules::apply`]. pub fn new() -> Self { - Self + Self::default() + } +} + +const REFRESH_INTERVAL: Duration = Duration::from_secs(30); +const DNS_GRACE: Duration = Duration::from_secs(120); +const MAX_RELAY_ADDRESSES: usize = 16; + +/// DNS may rotate while the old relay connection is still carrying packets. +/// Keep recent answers for the relays still in use, with a fixed expiry and cap. +#[derive(Debug, Default)] +struct RelayCache { + hosts: HashMap>, + last_refresh: Option, +} + +impl RelayCache { + fn lookup( + &mut self, + hosts: &[String], + now: Instant, + resolve: windows_exit::Resolve<'_>, + ) -> HashMap> { + self.hosts.retain(|host, _| hosts.contains(host)); + let due = self + .last_refresh + .is_none_or(|last| now.duration_since(last) >= REFRESH_INTERVAL); + for host in hosts { + let known = self.hosts.entry(host.clone()).or_default(); + known.retain(|_, seen| now.duration_since(*seen) < DNS_GRACE); + if due || known.is_empty() { + for address in resolve(host).into_iter().take(MAX_RELAY_ADDRESSES) { + known.insert(address, now); + } + while known.len() > MAX_RELAY_ADDRESSES { + if let Some((&oldest, _)) = known.iter().min_by_key(|(_, seen)| **seen) { + known.remove(&oldest); + } + } + } + } + if due { + self.last_refresh = Some(now); + } + self.hosts + .iter() + .map(|(host, addresses)| (host.clone(), addresses.keys().copied().collect())) + .collect() } } @@ -173,6 +226,7 @@ fn resolve_host(host: &str) -> Vec { IpAddr::V4(ip) => Some(ip), IpAddr::V6(_) => None, }) + .take(MAX_RELAY_ADDRESSES) .collect() }) .unwrap_or_default() @@ -186,10 +240,16 @@ impl ExitHostRules for WindowsHostRules { fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> { Box::pin(async move { let job = plan.clone(); + let cache = Arc::clone(&self.relay_cache); tokio::task::spawn_blocking(move || { + let hosts = cache.lock().unwrap_or_else(|p| p.into_inner()).lookup( + &job.bypass_hosts, + Instant::now(), + &resolve_host, + ); windows_exit::apply_plan( &|script| run_powershell_output(script), - &resolve_host, + &|host| hosts.get(host).cloned().unwrap_or_default(), &job, ) }) @@ -209,10 +269,46 @@ impl ExitHostRules for WindowsHostRules { }) } + fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option> { + Box::pin(async move { + if !plan.client { + return None; + } + let job = plan.clone(); + let cache = Arc::clone(&self.relay_cache); + tokio::task::spawn_blocking(move || { + let now = Instant::now(); + let mut cache = cache.lock().unwrap_or_else(|p| p.into_inner()); + if cache + .last_refresh + .is_some_and(|last| now.duration_since(last) < REFRESH_INTERVAL) + { + return None; + } + let hosts = cache.lookup(&job.bypass_hosts, now, &resolve_host); + drop(cache); + Some( + match windows_exit::refresh_bypass( + &run_powershell_output, + &|host| hosts.get(host).cloned().unwrap_or_default(), + &job, + ) { + Ok(()) => RuleOutcome::Applied, + Err(reason) => RuleOutcome::Failed(reason), + }, + ) + }) + .await + .unwrap_or_else(|err| Some(RuleOutcome::Failed(format!("the task failed: {err}")))) + }) + } + fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> { Box::pin(async move { let name = interface.to_string(); + let cache = Arc::clone(&self.relay_cache); let _ = tokio::task::spawn_blocking(move || { + *cache.lock().unwrap_or_else(|p| p.into_inner()) = RelayCache::default(); windows_exit::clear_all(&|script| run_powershell_output(script), &name) }) .await; @@ -258,6 +354,29 @@ mod tests { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use super::*; + + #[test] + fn relay_dns_survives_a_transient_failure_and_retires_rotated_addresses() { + use std::time::{Duration, Instant}; + let mut cache = RelayCache::default(); + let hosts = vec!["relay.example".into()]; + let old = [192, 0, 2, 1].into(); + let new = [192, 0, 2, 2].into(); + let now = Instant::now(); + assert_eq!(cache.lookup(&hosts, now, &|_| vec![old])[&hosts[0]], [old]); + let later = |secs| now + Duration::from_secs(secs); + assert_eq!( + cache.lookup(&hosts, later(32), &|_| Vec::new())[&hosts[0]], + [old] + ); + let rotated = cache.lookup(&hosts, later(64), &|_| vec![new]); + assert!(rotated[&hosts[0]].contains(&old) && rotated[&hosts[0]].contains(&new)); + assert_eq!( + cache.lookup(&hosts, later(121), &|_| vec![new])[&hosts[0]], + [new] + ); + assert!(cache.lookup(&[], later(122), &|_| Vec::new()).is_empty()); + } use std::net::Ipv4Addr; fn plan() -> BroadcastRulesPlan { diff --git a/crates/tsunagi-core/src/overlay/hostrules/windows_exit.rs b/crates/tsunagi-core/src/overlay/hostrules/windows_exit.rs index bb2b718..0cec553 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/windows_exit.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/windows_exit.rs @@ -108,8 +108,8 @@ fn forwarding_script(interface: &str) -> String { ) } -/// Prints ` ` of the best default route that is -/// not through the overlay interface. +/// Prints the physical default and the more specific routes that already +/// outrank the split defaults. Ignore our own host routes when refreshing. fn gateway_script(interface: &str) -> String { let alias = ps_literal(interface); format!( @@ -121,7 +121,11 @@ fn gateway_script(interface: &str) -> String { (Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }} | \ Select-Object -First 1\n\ if (-not $best) {{ throw 'the host has no default gateway outside the overlay' }}\n\ - \"$($best.InterfaceIndex) $($best.NextHop)\"\n" + \"$($best.InterfaceIndex) $($best.NextHop)\"\n\ + Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore | Where-Object {{ \ + $_.InterfaceAlias -ne $alias -and $_.State -ne 'Dead' -and \ + -not ($_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32')) }} | \ + Select-Object -ExpandProperty DestinationPrefix\n" ) } @@ -220,17 +224,42 @@ fn bypass_addresses( .collect() } -fn apply_client( +pub(super) fn refresh_bypass( run: RunScript<'_>, resolve: Resolve<'_>, plan: &ExitHostPlan, ) -> Result<(), String> { let interface = plan.interface.as_str(); let gateway = run(&gateway_script(interface))?; - let (index, hop) = parse_gateway(&gateway) - .ok_or_else(|| format!("cannot read the default gateway from `{}`", gateway.trim()))?; - let addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts, &plan.overlay); - run(&bypass_script(index, hop, &addresses))?; + let mut lines = gateway.lines(); + let first = lines.next().unwrap_or_default(); + let (index, hop) = parse_gateway(first) + .ok_or_else(|| format!("cannot read the default gateway from `{first}`"))?; + let mut addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts, &plan.overlay); + for line in lines { + let prefix = line.trim(); + let (network, bits) = prefix + .split_once('/') + .and_then(|(address, bits)| { + Some((address.parse::().ok()?, bits.parse::().ok()?)) + }) + .filter(|(_, bits)| *bits <= 32) + .ok_or_else(|| format!("cannot read physical route prefix `{prefix}`"))?; + if bits > 1 { + let mask = u32::MAX << (32 - bits); + addresses.retain(|addr| u32::from(*addr) & mask != u32::from(network) & mask); + } + } + run(&bypass_script(index, hop, &addresses)).map(|_| ()) +} + +fn apply_client( + run: RunScript<'_>, + resolve: Resolve<'_>, + plan: &ExitHostPlan, +) -> Result<(), String> { + refresh_bypass(run, resolve, plan)?; + let interface = &plan.interface; if let Err(why) = run(&halves_script(interface)) { // Do not leave a half-installed set: bypass routes alone are harmless // but the next apply starts clean. @@ -412,6 +441,58 @@ mod tests { Vec::new() } + /// Run the real refresh against the Windows ActiveStore. The fixture + /// only permits its TEST-NET /32 and refuses to prune pre-existing routes. + #[cfg(windows)] + #[test] + #[ignore = "requires an elevated disposable Windows runner with a physical default gateway"] + fn windows_refresh_installs_only_the_external_test_address() { + use super::super::windows::run_powershell_output; + + let target = Ipv4Addr::new(198, 51, 100, 207); + let inventory = run_powershell_output(&gateway_script("tsng-native-test")).unwrap(); + let (index, gateway) = parse_gateway(inventory.lines().next().unwrap()).unwrap(); + let plan = ExitHostPlan { + interface: "tsng-native-test".into(), + bypass: vec![gateway, target], + client: true, + ..Default::default() + }; + let run = |script: &str| { + if script == gateway_script(&plan.interface) { + return Ok(inventory.clone()); + } + // Catch a failure to recognize the gateway's connected LAN before + // executing a script which might create a route to the gateway. + assert!(script.contains(&format!("$keep = @(@('{target}') |"))); + let guarded = format!( + r#"$ErrorActionPreference = 'Stop' +$prefix = '{target}/32' +$before = @(Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore | Where-Object {{ + $_.DestinationPrefix -eq $prefix -or ($_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32')) +}}) +if ($before.Count) {{ throw 'fixture requires an unused test prefix and no pre-existing bypass routes' }} +try {{ + {script} + $actual = @(Get-NetRoute -DestinationPrefix $prefix -PolicyStore ActiveStore -ErrorAction Stop) + if ($actual.Count -ne 1 -or $actual[0].InterfaceIndex -ne {index} -or + $actual[0].NextHop -ne '{gateway}' -or $actual[0].RouteMetric -ne {BYPASS_METRIC}) {{ + throw 'unexpected physical bypass route' + }} +}} finally {{ + Get-NetRoute -DestinationPrefix $prefix -InterfaceIndex {index} -NextHop '{gateway}' -PolicyStore ActiveStore -ErrorAction SilentlyContinue | + Where-Object {{ $_.RouteMetric -eq {BYPASS_METRIC} }} | Remove-NetRoute -Confirm:$false +}} +if (Get-NetRoute -DestinationPrefix $prefix -PolicyStore ActiveStore -ErrorAction SilentlyContinue) {{ + throw 'test route still present after cleanup' +}} +exit 0"# + ); + run_powershell_output(&guarded) + }; + refresh_bypass(&run, &no_names, &plan).unwrap(); + } + fn client_plan() -> ExitHostPlan { ExitHostPlan { interface: "tsun0".into(), @@ -549,6 +630,47 @@ mod tests { assert!(!bypass.contains("'10.13.37.4'") && !bypass.contains("'10.99.0.6'")); } + #[test] + fn a_connected_lan_and_an_existing_host_route_stay_on_their_own_paths() { + let mut plan = client_plan(); + for addr in ["192.168.1.11", "198.51.100.7", "198.51.100.9"] { + plan.bypass.push(addr.parse().unwrap()); + } + let calls = RefCell::new(Vec::new()); + let run = |script: &str| { + calls.borrow_mut().push(script.to_string()); + Ok("12 192.168.1.1\n192.168.1.0/24\n198.51.100.7/32\n".into()) + }; + apply_client(&run, &no_names, &plan).unwrap(); + let calls = calls.borrow(); + let bypass = calls.iter().find(|s| s.contains("New-NetRoute")).unwrap(); + assert!(!bypass.contains("'192.168.1.11'")); + assert!(!bypass.contains("'198.51.100.7'")); + assert!(bypass.contains("'198.51.100.9'")); + } + + #[test] + fn refreshing_uses_the_new_physical_gateway_without_touching_the_exit_routes() { + let plan = client_plan(); + let routes = RefCell::new(Vec::new()); + for gateway in ["12 192.168.1.1", "17 10.0.0.1"] { + let run = |script: &str| { + if script.contains("Select-Object -First 1") { + Ok(gateway.into()) + } else { + routes.borrow_mut().push(script.to_owned()); + Ok(String::new()) + } + }; + refresh_bypass(&run, &no_names, &plan).unwrap(); + } + let routes = routes.into_inner(); + assert_eq!(routes.len(), 2); + assert!(routes[0].contains("-InterfaceIndex 12 -NextHop '192.168.1.1'")); + assert!(routes[1].contains("-InterfaceIndex 17 -NextHop '10.0.0.1'")); + assert!(routes.iter().all(|s| !s.contains("'0.0.0.0/1'"))); + } + #[test] fn nothing_goes_through_the_overlay_when_the_bypass_cannot_be_written() { let run = |script: &str| -> Result { diff --git a/crates/tsunagi-runtime/Cargo.toml b/crates/tsunagi-runtime/Cargo.toml index 0a0f3df..12a589f 100644 --- a/crates/tsunagi-runtime/Cargo.toml +++ b/crates/tsunagi-runtime/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-runtime" -version = "1.0.2" +version = "1.0.3-rc1" description = "Built-in mesh transports and status reporting for native tsunagi agents." edition.workspace = true rust-version.workspace = true @@ -8,11 +8,11 @@ license.workspace = true repository.workspace = true [dependencies] -tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" } -tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.2" } -tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.2" } -tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.2" } -tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.2" } +tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" } +tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.3-rc1" } +tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.3-rc1" } +tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.3-rc1" } +tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.3-rc1" } tokio.workspace = true tracing.workspace = true diff --git a/crates/tsunagi-tcp-tls/Cargo.toml b/crates/tsunagi-tcp-tls/Cargo.toml index da88bca..f934ad9 100644 --- a/crates/tsunagi-tcp-tls/Cargo.toml +++ b/crates/tsunagi-tcp-tls/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-tcp-tls" -version = "1.0.2" +version = "1.0.3-rc1" description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic." edition.workspace = true rust-version.workspace = true @@ -8,7 +8,7 @@ license.workspace = true repository.workspace = true [dependencies] -tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" } +tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" } iroh.workspace = true tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] } rustls = "0.23" diff --git a/crates/tsunagi-tray/Cargo.toml b/crates/tsunagi-tray/Cargo.toml index a2d5dc0..6686b69 100644 --- a/crates/tsunagi-tray/Cargo.toml +++ b/crates/tsunagi-tray/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-tray" -version = "1.0.2" +version = "1.0.3-rc1" description = "Tray application to manage a running tsunagi agent." edition.workspace = true rust-version.workspace = true @@ -16,7 +16,7 @@ tsunagi-ui = { path = "../tsunagi-ui" } # The agent control client and the report types: the GUI is a thin client over # the same local control interface the CLI uses, so it reuses these directly # and never re-implements the protocol. -tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" } +tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" } # Native, lightweight GUI — no web engine. eframe re-exports egui. eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] } # Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI). diff --git a/crates/tsunagi-ui/Cargo.toml b/crates/tsunagi-ui/Cargo.toml index 1432c66..30e9031 100644 --- a/crates/tsunagi-ui/Cargo.toml +++ b/crates/tsunagi-ui/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-ui" -version = "1.0.2" +version = "1.0.3-rc1" description = "Shared egui widgets for the tray and Android clients." edition.workspace = true rust-version.workspace = true diff --git a/crates/tsunagi-wg-quic/Cargo.toml b/crates/tsunagi-wg-quic/Cargo.toml index e492789..a040c79 100644 --- a/crates/tsunagi-wg-quic/Cargo.toml +++ b/crates/tsunagi-wg-quic/Cargo.toml @@ -3,7 +3,7 @@ name = "tsunagi-wg-quic" # Its own version, and deliberately separate from the wire version it # negotiates: a release here does not stop it talking to a peer on an older # build, because what peers compare is `ANNOUNCEMENT_VERSION`. -version = "1.0.2" +version = "1.0.3-rc1" description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers." edition.workspace = true rust-version.workspace = true @@ -11,7 +11,7 @@ license.workspace = true repository.workspace = true [dependencies] -tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" } +tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" } iroh.workspace = true tokio.workspace = true serde.workspace = true diff --git a/crates/tsunagi-wg-quic/tests/exit_node.rs b/crates/tsunagi-wg-quic/tests/exit_node.rs index 5a69db5..5168b67 100644 --- a/crates/tsunagi-wg-quic/tests/exit_node.rs +++ b/crates/tsunagi-wg-quic/tests/exit_node.rs @@ -18,11 +18,11 @@ use iroh::EndpointId; use tempfile::TempDir; use tsunagi::dataplane::IpPlugin; use tsunagi::discovery::SharedMemoryDiscovery; -use tsunagi::identity::NetworkId; +use tsunagi::identity::{NetworkId, NetworkName, NetworkSecret}; use tsunagi::overlay::{MemoryTun, MemoryTunFactory, MockHostRules}; use tsunagi::state::{DEFAULT_IPV4_RANGE, Ipv4Range}; use tsunagi::testing::{network, wait_until}; -use tsunagi::{Agent, NetworkStatus}; +use tsunagi::{Agent, AgentConfig, NetworkStatus}; use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin}; const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34); @@ -52,6 +52,12 @@ impl Node { tag: &str, range: Option, ) -> Self { + let config = + tsunagi::testing::config_with(dir.path(), discovery).with_overlay_ipv4_range(range); + Self::start(dir, tag, config).await + } + + async fn start(dir: TempDir, tag: &str, config: AgentConfig) -> Self { let tuns = MemoryTunFactory::new(); let rules = MockHostRules::new(); let plugin = WireguardPlugin::open( @@ -61,8 +67,7 @@ impl Node { .await .unwrap(); let agent = Agent::spawn( - tsunagi::testing::config_with(dir.path(), discovery) - .with_overlay_ipv4_range(range) + config .with_interface( Arc::new(tuns.clone().with_host_rules(Arc::new(rules.clone()))), tag, @@ -164,10 +169,15 @@ struct ExitNetwork<'a> { } impl<'a> ExitNetwork<'a> { - async fn join(client: &Node, peer: &'a Node, name: &str, range: Ipv4Range) -> Self { - let (name, secret) = network(name); + async fn join( + client: &Node, + peer: &'a Node, + credentials: (NetworkName, NetworkSecret), + ) -> Self { + let (name, secret) = credentials; let id = peer.agent.join_network(&name, &secret).await.unwrap(); peer.overlay(id).await; + let range = peer.status(id).await.range.unwrap(); peer.agent.set_exit_offer(id, true).await.unwrap(); client.agent.join_network(&name, &secret).await.unwrap(); client.wait_for_tunnels(id, 1).await; @@ -219,8 +229,8 @@ async fn switching_the_exit_between_networks_keeps_both_overlays_reachable() { Some(right_range), ) .await; - let alpha = ExitNetwork::join(&client, &left, "exit-left", DEFAULT_IPV4_RANGE).await; - let beta = ExitNetwork::join(&client, &right, "exit-right", right_range).await; + let alpha = ExitNetwork::join(&client, &left, network("exit-left")).await; + let beta = ExitNetwork::join(&client, &right, network("exit-right")).await; let tun = client.tun().await; for exit in [&alpha, &beta] { @@ -300,6 +310,60 @@ async fn switching_the_exit_between_networks_keeps_both_overlays_reachable() { live.peer.agent.shutdown().await; } +#[tokio::test] +async fn selecting_a_shared_peer_uses_only_the_chosen_membership_for_exit() { + let discovery = SharedMemoryDiscovery::new(); + let client = Node::open(TempDir::new().unwrap(), &discovery, "client", None).await; + let dir = TempDir::new().unwrap(); + let config = tsunagi::testing::config_with(dir.path(), &discovery); + let peer = Node::start(dir, "shared", config).await; + // Fixed credentials keep the two automatically derived /24s distinct. + let mut meshes = Vec::new(); + for (name, secret) in [("shared-left", [1; 32]), ("shared-right", [2; 32])] { + let credentials = ( + NetworkName::new(name).unwrap(), + NetworkSecret::from_bytes(secret).unwrap(), + ); + meshes.push(ExitNetwork::join(&client, &peer, credentials).await); + } + let tun = client.tun().await; + for (chosen, other) in [(&meshes[0], &meshes[1]), (&meshes[1], &meshes[0])] { + client + .agent + .set_exit_via(chosen.id, Some(peer.id())) + .await + .unwrap(); + assert_eq!(client.selected_exits().await, [(chosen.id, peer.id())]); + assert_eq!( + client.rules.exit().installed().unwrap().client_source, + Some(chosen.client_addr) + ); + chosen.check_mesh(&tun).await; + other.check_mesh(&tun).await; + let request = ipv4_packet(chosen.client_addr, INTERNET, b"external"); + tun.push_from_os(request.clone()); + assert_eq!(next(&chosen.peer_tun).await, request); + // Both memberships authenticate the same device key. A reply through + // its other tunnel still lacks the external-source exception. + let wrong_source = client.agent.overlay().unwrap().counters.wrong_source; + chosen + .peer_tun + .push_from_os(ipv4_packet(INTERNET, other.client_addr, b"wrong mesh")); + wait_until( + "external reply on unselected membership is rejected", + || async { + (client.agent.overlay()?.counters.wrong_source > wrong_source).then_some(()) + }, + ) + .await; + let reply = ipv4_packet(INTERNET, chosen.client_addr, b"reply"); + chosen.peer_tun.push_from_os(reply.clone()); + assert_eq!(next(&tun).await, reply); + } + peer.agent.shutdown().await; + client.agent.shutdown().await; +} + #[tokio::test] async fn a_member_sends_its_internet_traffic_through_an_exit_node_and_gets_the_answers() { let discovery = SharedMemoryDiscovery::new(); diff --git a/crates/tsunagi-wireguard/Cargo.toml b/crates/tsunagi-wireguard/Cargo.toml index 40358d2..7995db0 100644 --- a/crates/tsunagi-wireguard/Cargo.toml +++ b/crates/tsunagi-wireguard/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-wireguard" -version = "1.0.2" +version = "1.0.3-rc1" description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi." edition.workspace = true rust-version.workspace = true @@ -8,7 +8,7 @@ license = "WTFPL AND Apache-2.0" repository.workspace = true [dependencies] -tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" } +tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" } iroh.workspace = true tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] } serde.workspace = true diff --git a/crates/tsunagi/Cargo.toml b/crates/tsunagi/Cargo.toml index 7a84a1a..3a4115b 100644 --- a/crates/tsunagi/Cargo.toml +++ b/crates/tsunagi/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi" -version = "1.0.2" +version = "1.0.3-rc1" description = "The tsunagi command line agent." edition.workspace = true rust-version.workspace = true @@ -12,11 +12,11 @@ name = "tsng" path = "src/main.rs" [dependencies] -tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.2" } -tsunagi-core = { path = "../tsunagi-core", version = "1.0.2", features = ["tun-device", "dns-publish"] } -tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.2" } -tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.2" } -tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.2" } +tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.3-rc1" } +tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1", features = ["tun-device", "dns-publish"] } +tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.3-rc1" } +tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.3-rc1" } +tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.3-rc1" } iroh.workspace = true tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] } tracing.workspace = true diff --git a/crates/tsunagi/src/main.rs b/crates/tsunagi/src/main.rs index 2154374..3f7a556 100644 --- a/crates/tsunagi/src/main.rs +++ b/crates/tsunagi/src/main.rs @@ -4658,7 +4658,7 @@ async fn up(args: UpArgs) -> Result<(), Box> { let tun_factory: Arc = if args.no_tun { Arc::new(MemoryTunFactory::new()) } else { - system_tun_factory()? + system_tun_factory(&paths.state_dir)? }; let mtu = args.mtu.unwrap_or(tsunagi_wg_quic::DEFAULT_MTU); config = config.with_interface(tun_factory, args.interface.clone(), mtu); @@ -4955,7 +4955,9 @@ async fn stop_signal() -> &'static str { /// an open file descriptor and goes away with the agent, however the agent /// goes away. #[cfg(target_os = "linux")] -fn system_tun_factory() -> Result, Box> { +fn system_tun_factory( + _state_dir: &std::path::Path, +) -> Result, Box> { use tsunagi::overlay::{ManagedTunFactory, NetlinkProvisioner}; let provisioner = NetlinkProvisioner::new()?; let rules = Arc::new(provisioner.host_rules()); @@ -4967,7 +4969,9 @@ fn system_tun_factory() -> Result, Box Result, Box> { +fn system_tun_factory( + _state_dir: &std::path::Path, +) -> Result, Box> { use tsunagi::overlay::{ManagedTunFactory, WindowsHostRules, WintunProvisioner}; let provisioner = WintunProvisioner::new()?; Ok(Arc::new( @@ -4980,12 +4984,14 @@ fn system_tun_factory() -> Result, Box Result, Box> { +fn system_tun_factory( + state_dir: &std::path::Path, +) -> Result, Box> { use tsunagi::overlay::{MacosHostRules, ManagedTunFactory, UtunProvisioner}; let provisioner = UtunProvisioner::new()?; Ok(Arc::new( ManagedTunFactory::new(Arc::new(provisioner)) - .with_host_rules(Arc::new(MacosHostRules::new())), + .with_host_rules(Arc::new(MacosHostRules::with_state_dir(state_dir))), )) } @@ -4994,7 +5000,9 @@ fn system_tun_factory() -> Result, Box Result, Box> { +fn system_tun_factory( + _state_dir: &std::path::Path, +) -> Result, Box> { Err(format!( "managing the overlay interface is not implemented on {} yet. \ Run with `--no-tun` to keep the tunnels off the operating system.", diff --git a/dist/deb/build-deb.sh b/dist/deb/build-deb.sh index fdfb8b0..5ea1069 100755 --- a/dist/deb/build-deb.sh +++ b/dist/deb/build-deb.sh @@ -14,7 +14,9 @@ set -euo pipefail binary="$1" arch="$2" -version="$3" +# Debian treats a hyphen as a packaging revision. A tilde orders an upstream +# prerelease before the corresponding final version (1.0.3~rc1 < 1.0.3). +version=$(printf '%s' "$3" | sed 's/-/~/') output="$4" tray="${5:-}" diff --git a/dist/deb/test-deb.sh b/dist/deb/test-deb.sh new file mode 100644 index 0000000..00f720f --- /dev/null +++ b/dist/deb/test-deb.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Build RC and stable packages and verify apt's upgrade order. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +for version in 1.0.3-rc1 1.0.3-rc2 1.0.3; do + bash "$here/build-deb.sh" /usr/bin/true amd64 "$version" "$work/$version.deb" +done + +version_of() { dpkg-deb -f "$work/$1.deb" Version; } +test "$(version_of 1.0.3)" = '1.0.3' +dpkg --compare-versions "$(version_of 1.0.3-rc1)" gt 1.0.2 +dpkg --compare-versions "$(version_of 1.0.3-rc1)" lt "$(version_of 1.0.3-rc2)" +dpkg --compare-versions "$(version_of 1.0.3-rc2)" lt "$(version_of 1.0.3)" diff --git a/dist/macos/README.md b/dist/macos/README.md index e751da9..e1417c3 100644 --- a/dist/macos/README.md +++ b/dist/macos/README.md @@ -41,6 +41,12 @@ The cask starts the service for you. The agent runs as root, and its control socket is open to the `admin` group, so the CLI and the tray work without `sudo` for an administrator. +After upgrading the CLI, run `sudo brew services restart tsunagi` to load the +new binary into the system daemon. Running `brew services start tsunagi` in +a user shell creates a separate launch agent. If that happened, remove the +user service with `brew services stop tsunagi`, then check the system daemon +with `sudo brew services info tsunagi`. + ### Publishing Homebrew packages After a stable `vMAJOR.MINOR.PATCH` GitHub release uploads its assets, the diff --git a/docs/exit-node.md b/docs/exit-node.md index c0b8bb3..e5a01f4 100644 --- a/docs/exit-node.md +++ b/docs/exit-node.md @@ -101,14 +101,20 @@ is built from `pf` and `route`. The agent runs as root there. macOS forgets at reboot. The egress is the default route's interface **at the time the rules are applied**; after it changes (Wi-Fi to Ethernet) switch the offer off and on. -- **Using:** `0.0.0.0/1` and `128.0.0.0/1` routes through the overlay interface - with the local address of the exit network as their source, - and a `pf` `route-to` rule that sends the agent's own traffic (matched by its - user id, root) back out the physical interface, with translation to that - interface's address. Anything else you run as root also bypasses the tunnel. - IPv6 is blocked with rejecting `::/1` and `8000::/1` routes. -- Not verified on a live host when this was written: run `tsng exit-node` and - check `sudo pfctl -a com.apple/tsunagi-exit-utunN -s rules -s nat`. +- When **using** an exit, ordinary IPv4 internet connections take the two + split-default routes through the utun, with the local address of the selected + network. More specific routes continue to reach their own networks. +- Sockets already using the physical address need matching routes scoped to + the uplink. Without them, macOS can reject a send before the packet reaches + PF. For new TCP and UDP sockets, PF sends the agent's traffic out the uplink + and preserves its source port. Replies to these tagged connections return + through loopback after reverse NAT so macOS can deliver them to a socket + whose local address belongs to the utun. This exemption matches the + daemon's user ID, so it also applies to other processes running as root. + IPv6 internet traffic is blocked with rejecting `::/1` and `8000::/1` routes. +- To inspect an active exit, run `tsng exit-node` and + `sudo pfctl -a com.apple/tsunagi-exit-utunN -vvsr`, using the daemon's utun + number. The physical interface and the utun should both see transport packets. ## Windows @@ -123,11 +129,15 @@ is built from `pf` and `route`. The agent runs as root there. off the tunnel *by destination*. `0.0.0.0/1` and `128.0.0.0/1` go through the overlay interface; a `/32` route with metric 7373 (the marker for "ours") through the physical default gateway is added for every address the agent - talks to directly: verified direct paths of its connections, plus the relays - it uses, resolved when the rules are applied. The set follows path changes. A - newly authenticated connection supplies its direct paths immediately and the - discovery tick refreshes them. Physical bypass routes exclude every active - mesh subnet. Wintun can choose any local alias for the default route. For + talks to directly, including verified connection paths and current relay + servers. Existing LAN and other more specific routes keep their next hop. + A newly authenticated connection supplies its direct paths immediately. + After a disconnect, the agent keeps its last verified paths for up to two + minutes to allow reconnection. It checks the physical gateway and relay + DNS every 30 seconds while the exit is active. Recent DNS answers remain + usable for up to two minutes after rotation or a failed lookup. + Physical bypass routes exclude every active mesh subnet. Wintun can choose + any local alias for the default route. For TCP, UDP and ICMP echo, the agent uses the exit network's address on the tunnel and restores replies to the address the Windows socket used. IPv6 is blackholed with `::/1` and `8000::/1` on the overlay interface, diff --git a/nix/package.nix b/nix/package.nix index 379164c..96502bb 100644 --- a/nix/package.nix +++ b/nix/package.nix @@ -34,7 +34,7 @@ let in rustPlatform.buildRustPackage { pname = if withTray then "tsunagi" else "tsunagi-cli"; - version = "1.0.2"; + version = "1.0.3-rc1"; src = lib.cleanSource ../.; cargoLock.lockFile = ../Cargo.lock;