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.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-25 03:47:49 +02:00
1 parent 32aa73721a
commit a189d0ad3e
28 files changed
+1698 -185

No files matched your search

+3 -1
View File
@@ -2,7 +2,7 @@ name: CI
on: on:
push: push:
branches: [main] branches: [master, main]
pull_request: pull_request:
workflow_dispatch: workflow_dispatch:
@@ -25,6 +25,8 @@ jobs:
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
- run: cargo fmt --all -- --check - run: cargo fmt --all -- --check
- run: cargo clippy --locked --workspace --all-targets -- -D warnings - run: cargo clippy --locked --workspace --all-targets -- -D warnings
- name: Check Debian release candidate upgrade ordering
run: bash dist/deb/test-deb.sh
test: test:
name: test (${{ matrix.os }}) name: test (${{ matrix.os }})
+22
View File
@@ -5,6 +5,8 @@ on:
branches: [master] branches: [master]
paths: paths:
- '.github/workflows/subnet-source.yml' - '.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/macos.rs'
- 'crates/tsunagi-core/src/overlay/provision/windows.rs' - 'crates/tsunagi-core/src/overlay/provision/windows.rs'
- 'crates/tsunagi-core/src/overlay/provision/mod.rs' - 'crates/tsunagi-core/src/overlay/provision/mod.rs'
@@ -55,6 +57,15 @@ jobs:
if: runner.os == 'macOS' if: runner.os == 'macOS'
shell: bash shell: bash
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture 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 - name: Verify source selection on a real Wintun adapter
if: runner.os == 'Windows' if: runner.os == 'Windows'
shell: pwsh shell: pwsh
@@ -70,3 +81,14 @@ jobs:
Copy-Item (Join-Path $directory 'wintun/bin/amd64/wintun.dll') (Split-Path -Parent $env:TEST_BINARY) 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 & $env:TEST_BINARY --ignored --exact $env:TEST_NAME --nocapture
exit $LASTEXITCODE 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
Generated
+10 -10
View File
@@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]] [[package]]
name = "tsunagi" name = "tsunagi"
version = "1.0.2" version = "1.0.3-rc1"
dependencies = [ dependencies = [
"anstream", "anstream",
"anstyle", "anstyle",
@@ -6320,7 +6320,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-android" name = "tsunagi-android"
version = "1.0.2" version = "1.0.3-rc1"
dependencies = [ dependencies = [
"bytes", "bytes",
"egui", "egui",
@@ -6344,7 +6344,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-awg" name = "tsunagi-awg"
version = "1.0.2" version = "1.0.3-rc1"
dependencies = [ dependencies = [
"bytes", "bytes",
"iroh", "iroh",
@@ -6359,7 +6359,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-core" name = "tsunagi-core"
version = "1.0.2" version = "1.0.3-rc1"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"bytes", "bytes",
@@ -6402,7 +6402,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-runtime" name = "tsunagi-runtime"
version = "1.0.2" version = "1.0.3-rc1"
dependencies = [ dependencies = [
"tokio", "tokio",
"tracing", "tracing",
@@ -6415,7 +6415,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-tcp-tls" name = "tsunagi-tcp-tls"
version = "1.0.2" version = "1.0.3-rc1"
dependencies = [ dependencies = [
"bytes", "bytes",
"caps", "caps",
@@ -6435,7 +6435,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-tray" name = "tsunagi-tray"
version = "1.0.2" version = "1.0.3-rc1"
dependencies = [ dependencies = [
"eframe", "eframe",
"egui-phosphor", "egui-phosphor",
@@ -6451,7 +6451,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-ui" name = "tsunagi-ui"
version = "1.0.2" version = "1.0.3-rc1"
dependencies = [ dependencies = [
"egui", "egui",
"egui-phosphor", "egui-phosphor",
@@ -6461,7 +6461,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-wg-quic" name = "tsunagi-wg-quic"
version = "1.0.2" version = "1.0.3-rc1"
dependencies = [ dependencies = [
"boringtun", "boringtun",
"bytes", "bytes",
@@ -6488,7 +6488,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-wireguard" name = "tsunagi-wireguard"
version = "1.0.2" version = "1.0.3-rc1"
dependencies = [ dependencies = [
"boringtun", "boringtun",
"bytes", "bytes",
+1 -1
View File
@@ -24,7 +24,7 @@ android {
targetSdk 35 targetSdk 35
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger() 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 } ndk { abiFilters abi }
} }
} }
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-android" name = "tsunagi-android"
version = "1.0.2" version = "1.0.3-rc1"
description = "Android VPN client and egui views for tsunagi." description = "Android VPN client and egui views for tsunagi."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -16,7 +16,7 @@ name = "vpn_source_probe"
crate-type = ["cdylib"] crate-type = ["cdylib"]
[dependencies] [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-ui = { path = "../tsunagi-ui" }
tsunagi-core = { path = "../tsunagi-core" } tsunagi-core = { path = "../tsunagi-core" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" } tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-awg" name = "tsunagi-awg"
version = "1.0.2" version = "1.0.3-rc1"
description = "Ephemeral pairwise Amnezia transport for Tsunagi." description = "Ephemeral pairwise Amnezia transport for Tsunagi."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-core" 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." 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" readme = "../../README.md"
keywords = ["mesh", "p2p", "iroh", "networking"] keywords = ["mesh", "p2p", "iroh", "networking"]
+103 -10
View File
@@ -236,6 +236,54 @@ struct DialState {
source: CandidateSource, 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<EndpointId, (Instant, Vec<PathAddr>)>,
}
impl VerifiedUnderlay {
fn record(
&mut self,
peer: EndpointId,
paths: impl IntoIterator<Item = PathAddr>,
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 { impl DialState {
fn new(source: CandidateSource) -> Self { fn new(source: CandidateSource) -> Self {
Self { Self {
@@ -313,6 +361,7 @@ struct Runtime {
local_id: EndpointId, local_id: EndpointId,
shutdown: Shutdown, shutdown: Shutdown,
sessions: HashMap<EndpointId, Session>, sessions: HashMap<EndpointId, Session>,
verified_underlay: VerifiedUnderlay,
dial_states: HashMap<EndpointId, DialState>, dial_states: HashMap<EndpointId, DialState>,
candidate_addrs: HashMap<EndpointId, iroh::EndpointAddr>, candidate_addrs: HashMap<EndpointId, iroh::EndpointAddr>,
metrics: NetworkMetrics, metrics: NetworkMetrics,
@@ -441,6 +490,7 @@ impl Runtime {
local_id, local_id,
shutdown, shutdown,
sessions: HashMap::new(), sessions: HashMap::new(),
verified_underlay: VerifiedUnderlay::default(),
dial_states: HashMap::new(), dial_states: HashMap::new(),
candidate_addrs: HashMap::new(), candidate_addrs: HashMap::new(),
metrics: NetworkMetrics::default(), metrics: NetworkMetrics::default(),
@@ -902,7 +952,7 @@ impl Runtime {
/// on: the verified direct IPv4 paths of every control connection, and /// on: the verified direct IPv4 paths of every control connection, and
/// the relays in use. Only hosts that cannot exempt the agent from an /// the relays in use. Only hosts that cannot exempt the agent from an
/// exit node's default route read it. /// exit node's default route read it.
async fn refresh_underlay(&self) { async fn refresh_underlay(&mut self) {
let Some(interface) = self let Some(interface) = self
.params .params
.interface .interface
@@ -913,17 +963,38 @@ impl Runtime {
}; };
let mut addresses = Vec::new(); let mut addresses = Vec::new();
let mut hosts = Vec::new(); let mut hosts = Vec::new();
for session in self.sessions.values() { let now = Instant::now();
for path in snapshot_connection(&session.conn).paths { for (peer, session) in &self.sessions {
match path.remote { let mut paths = snapshot_connection(&session.conn).paths;
PathAddr::Ip(std::net::SocketAddr::V4(socket)) => addresses.push(*socket.ip()), paths.sort_by_key(|path| !path.is_selected);
PathAddr::Relay(url) => hosts.extend(relay_host(&url)), 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 { // The endpoint stops advertising a disconnected relay, but still
hosts.extend(relay_host(&url)); // 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 interface
.set_underlay(self.network_id, addresses, hosts) .set_underlay(self.network_id, addresses, hosts)
@@ -3434,6 +3505,28 @@ mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*; 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] #[test]
fn underlay_hints_exclude_overlay_subnets_but_preserve_lan_and_relay_candidates() { fn underlay_hints_exclude_overlay_subnets_but_preserve_lan_and_relay_candidates() {
let peer = crate::identity::DeviceIdentity::generate().endpoint_id(); let peer = crate::identity::DeviceIdentity::generate().endpoint_id();
@@ -19,10 +19,10 @@
use crate::BoxFuture; use crate::BoxFuture;
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules}; 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}; use super::{BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, RuleOutcome};
/// The limited-broadcast destination routed through the overlay interface. /// 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`]). /// `pf` plus `route` for exit nodes (see [`super::macos_exit`]).
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct MacosHostRules { pub struct MacosHostRules {
/// The reference `pfctl -E` handed out, held while exit-node rules need /// The PF reference and the physical routes owned by this agent.
/// `pf` on and released when they are removed. state: Arc<HostState>,
pub(super) pf_token: Arc<Mutex<Option<String>>>,
} }
impl MacosHostRules { 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 { pub fn new() -> Self {
Self::default() 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 /// 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 /// can be repeated. The delete is best effort: a route that is not there
/// is the state the add then reaches anyway. /// 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> { fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
Box::pin(async move { Box::pin(async move {
let job_plan = plan.clone(); 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)) tokio::task::spawn_blocking(move || apply_plan(&run_tool, &token, &job_plan))
.await .await
.unwrap_or_else(|err| { .unwrap_or_else(|err| {
@@ -113,10 +121,23 @@ impl ExitHostRules for MacosHostRules {
}) })
} }
fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
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, ()> { fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
Box::pin(async move { Box::pin(async move {
let name = interface.to_string(); 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; let _ = tokio::task::spawn_blocking(move || clear_all(&run_tool, &token, &name)).await;
}) })
} }
@@ -16,9 +16,8 @@
//! evaluates `nat-anchor "com.apple/*"` and `anchor "com.apple/*"`, so the //! evaluates `nat-anchor "com.apple/*"` and `anchor "com.apple/*"`, so the
//! rules take effect without editing the user's ruleset. `pf` cannot say //! 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 //! "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 //! interface of the physical default route. An active exit client refreshes
//! default route moves (Wi-Fi to Ethernet) the rules are re-applied by //! the rules when this egress changes.
//! switching the exit node off and on, or restarting the agent.
//! //!
//! The kernel's `net.inet.ip.forwarding` is only read, never written: it //! 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. //! changes how the whole host behaves, which is the owner's decision.
@@ -29,21 +28,32 @@
//! Linux scheme does not carry over. Instead: //! Linux scheme does not carry over. Instead:
//! //!
//! ```text //! ```text
//! route add -net 0.0.0.0/1 <gateway> -ifscope <egress>
//! route add -net 128.0.0.0/1 <gateway> -ifscope <egress>
//! route add -net 0.0.0.0/1 -interface <if> -ifa <selected overlay address> //! route add -net 0.0.0.0/1 -interface <if> -ifa <selected overlay address>
//! route add -net 128.0.0.0/1 -interface <if> -ifa <selected overlay address> //! route add -net 128.0.0.0/1 -interface <if> -ifa <selected overlay address>
//! pass out quick on <if> route-to (<egress> <gateway>) inet proto { tcp udp } //! pass out quick on <if> route-to (<egress> <gateway>) inet proto { tcp udp }
//! from any to ! <overlay ranges> user <agent uid> //! from any to ! <overlay ranges> user <agent uid> tag <underlay> no state
//! nat on <egress> inet from (<if>) to any -> (<egress>) //! nat on <egress> inet from (<if>) to any tagged <underlay> -> (<egress>) static-port
//! pass out quick on <egress> reply-to (lo0 127.0.0.1) inet proto { tcp udp }
//! from any to any flags any tagged <underlay> keep state (if-bound)
//! ``` //! ```
//! //!
//! The two halves outrank the default route without replacing it, and every //! The scoped routes preserve the physical path for sockets that already
//! more specific route (LAN, another VPN) keeps working. The `route-to` rule //! 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 //! 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 //! loop into the tunnel it carries — back out the physical interface, and the
//! translation gives it that interface's address, since an unbound socket //! translation gives it that interface's address, since an unbound socket
//! picked the overlay address when the route pointed at the overlay. Like the //! picked the overlay address when the route pointed at the overlay. The
//! Linux exemption this is by user id, so anything else running as root also //! first pass is stateless: a floating `route-to` state would match again
//! bypasses the tunnel. //! 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 //! 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 //! `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::RuleOutcome;
use super::exit::{ExitHostPlan, ExitHostReport}; 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. /// The programs this module runs, always by absolute path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Tool { pub(super) enum Tool {
@@ -163,12 +180,27 @@ fn anchor_name(interface: &str) -> Result<String, String> {
} }
/// The default route as `route -n get default` reports it. /// 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(super) struct DefaultRoute {
pub interface: String, pub interface: String,
pub gateway: Option<Ipv4Addr>, pub gateway: Option<Ipv4Addr>,
} }
#[derive(Debug, Default)]
pub(super) struct HostState {
token: Mutex<Option<String>>,
routes: Mutex<ScopedRoutes>,
}
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`. /// Reads `interface:` and `gateway:` out of `route -n get default`.
fn parse_default_route(text: &str) -> Option<DefaultRoute> { fn parse_default_route(text: &str) -> Option<DefaultRoute> {
let field = |name: &str| { let field = |name: &str| {
@@ -277,16 +309,11 @@ fn pf_rules(
let out = &egress.interface; let out = &egress.interface;
let mut nat = Vec::new(); let mut nat = Vec::new();
let mut filter = 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(); let mut tables = Vec::new();
if let Some(client) = client { if let Some(client) = client {
let tag = format!("tsng_underlay_{interface}");
nat.push(format!( 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() { let target = if client.overlay.is_empty() {
"any".to_string() "any".to_string()
@@ -306,9 +333,23 @@ fn pf_rules(
}; };
filter.push(format!( filter.push(format!(
"pass out quick on {interface} route-to {via} inet proto {{ tcp udp }} \ "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 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 tables
.into_iter() .into_iter()
@@ -368,10 +409,6 @@ fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
} }
} }
fn flush_args(anchor: &str) -> Vec<String> {
owned(&["-q", "-a", anchor, "-F", "all"])
}
fn load_args(anchor: &str) -> Vec<String> { fn load_args(anchor: &str) -> Vec<String> {
owned(&["-q", "-a", anchor, "-f", "-"]) 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. /// The IPv6 halves, made unreachable.
const HALVES_V6: [&str; 2] = ["::/1", "8000::/1"]; 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<String> {
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( fn route_set_args(
action: &str, action: &str,
half: &str, half: &str,
@@ -406,15 +459,56 @@ fn route_del_v6_args(half: &str) -> Vec<String> {
owned(&["-q", "-n", "delete", "-inet6", "-net", half, "::1"]) 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 /// Takes away the overlay default routes. Best effort: what is not there is
/// the state wanted. /// the state wanted.
fn clear_routes(run: Run<'_>, interface: &str) { fn clear_routes(run: Run<'_>, interface: &str) {
for half in HALVES { 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<Option<String>, 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 { 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 /// 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), &route_set_args("add", half, interface, source),
None, 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") => { Err(why) if why.contains("File exists") => {
let lookup = run_ok(run, Tool::Route, &owned(&["-n", "get", "-net", half]), None) if !captures_half(run, half, interface) {
.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) {
return Err(why); return Err(why);
} }
run_ok( run_ok(
@@ -456,7 +545,14 @@ fn set_half(
} }
} }
fn set_routes(run: Run<'_>, interface: &str, source: Option<Ipv4Addr>) -> Result<(), String> { fn set_routes(
run: Run<'_>,
interface: &str,
source: Option<Ipv4Addr>,
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(); let mut added = Vec::new();
for half in HALVES { for half in HALVES {
match set_half(run, half, interface, source) { match set_half(run, half, interface, source) {
@@ -466,31 +562,43 @@ fn set_routes(run: Run<'_>, interface: &str, source: Option<Ipv4Addr>) -> Result
for half in added { for half in added {
let _ = run(Tool::Route, &route_del_args(half, interface), None); let _ = run(Tool::Route, &route_del_args(half, interface), None);
} }
if !already_using_v6 {
scoped.record_ipv6(false)?;
}
return Err(why); return Err(why);
} }
} }
} }
for half in HALVES_V6 { for half in HALVES_V6 {
// A host without IPv6 has nothing to block; not a failure. let mut args = route_add_v6_args(half);
if let Err(why) = run_ok(run, Tool::Route, &route_add_v6_args(half), None) { args.extend(["-proto2".into(), "-hopcount".into(), marker.to_string()]);
tracing::debug!(%why, "cannot block IPv6 for the exit node"); 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(()) Ok(())
} }
/// Makes the host match the plan. /// Makes the host match the plan.
pub(super) fn apply_plan( pub(super) fn apply_plan(run: Run<'_>, state: &HostState, plan: &ExitHostPlan) -> ExitHostReport {
run: Run<'_>,
token: &Mutex<Option<String>>,
plan: &ExitHostPlan,
) -> ExitHostReport {
let forwarding = if plan.offer.is_empty() { let forwarding = if plan.offer.is_empty() {
None None
} else { } else {
forwarding_state(run) forwarding_state(run)
}; };
let outcome = apply_rules(run, token, plan); let outcome = apply_rules(run, state, plan, None);
let verdict = |ok: bool, why: &str| { let verdict = |ok: bool, why: &str| {
if ok { if ok {
RuleOutcome::Applied RuleOutcome::Applied
@@ -522,12 +630,16 @@ pub(super) fn apply_plan(
fn apply_rules( fn apply_rules(
run: Run<'_>, run: Run<'_>,
token: &Mutex<Option<String>>, state: &HostState,
plan: &ExitHostPlan, plan: &ExitHostPlan,
checked_egress: Option<DefaultRoute>,
) -> Result<(), String> { ) -> Result<(), String> {
let interface = plan.interface.as_str(); let interface = plan.interface.as_str();
let anchor = anchor_name(interface)?; 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 { let uid = if plan.client {
Some(agent_uid(run)?) Some(agent_uid(run)?)
} else { } else {
@@ -539,30 +651,99 @@ fn apply_rules(
}); });
let rules = pf_rules(interface, &egress, &plan.offer, client.as_ref()); 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)) run_ok(run, Tool::Pfctl, &load_args(&anchor), Some(&rules))
.map_err(|why| format!("cannot load the pf rules: {why}"))?; .map_err(|why| format!("cannot load the pf rules: {why}"))?;
// The routes come after the rules that keep the agent's own traffic off // 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. // them: the other order would loop for as long as it takes.
if plan.client { 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 { } else {
clear_routes(run, interface); clear_routes(run, interface);
clear_v6(run, &mut scoped)?;
scoped.retain(run, &[])?;
scoped.active = None;
} }
Ok(()) Ok(())
} }
/// Removes everything this agent put there for the interface. /// Removes everything this agent put there for the interface.
pub(super) fn clear_all(run: Run<'_>, token: &Mutex<Option<String>>, interface: &str) { pub(super) fn clear_all(run: Run<'_>, state: &HostState, interface: &str) {
let mut scoped = lock(&state.routes);
clear_routes(run, interface); 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) { if let Ok(anchor) = anchor_name(interface) {
// Flushing an anchor nothing was ever loaded into is not an error // Flushing an anchor nothing was ever loaded into is not an error
// worth reporting. // 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"); 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<RuleOutcome> {
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)] #[cfg(test)]
@@ -601,6 +782,9 @@ destination: default\n\
pf_load_fails: bool, pf_load_fails: bool,
route_add_fails: bool, route_add_fails: bool,
half_interface: Option<&'static str>, half_interface: Option<&'static str>,
v6: RefCell<std::collections::BTreeMap<String, u32>>,
capture: RefCell<std::collections::BTreeMap<String, String>>,
scoped: RefCell<std::collections::BTreeMap<(String, String), String>>,
pf_enable_output: &'static str, pf_enable_output: &'static str,
} }
@@ -615,6 +799,9 @@ destination: default\n\
pf_load_fails: false, pf_load_fails: false,
route_add_fails: false, route_add_fails: false,
half_interface: None, half_interface: None,
v6: RefCell::default(),
capture: RefCell::default(),
scoped: RefCell::default(),
pf_enable_output: "pf enabled\nToken : 4242\n", pf_enable_output: "pf enabled\nToken : 4242\n",
} }
} }
@@ -638,11 +825,64 @@ destination: default\n\
match tool { match tool {
Tool::Id => ok("0\n", ""), Tool::Id => ok("0\n", ""),
Tool::Sysctl => ok(self.forwarding, ""), 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: <UP,REJECT,PROTO2>\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::<Ipv4Addr>().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: <UP,PROTO2,IFSCOPE>\nhopcount mtu\n{marker} 1500\n", prefix.split('/').next().unwrap()));
}
ok("", "")
}
Tool::Route Tool::Route
if args.iter().any(|arg| arg == "get") if args.iter().any(|arg| arg == "get")
&& args.iter().any(|arg| arg == "-net") => && 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"), ""), Some(name) => ok(&format!("mask: 128.0.0.0\ninterface: {name}\n"), ""),
None => fail("not in table"), None => fail("not in table"),
} }
@@ -656,12 +896,31 @@ destination: default\n\
Tool::Route Tool::Route
if args.contains(&"add".to_string()) if args.contains(&"add".to_string())
&& ((self.route_add_fails && args.iter().any(|a| a == HALVES[1])) && ((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() || (self.half_interface.is_some()
&& HALVES.iter().any(|half| args.iter().any(|a| a == half)))) => && HALVES.iter().any(|half| args.iter().any(|a| a == half)))) =>
{ {
// Darwin route can return success after a routing-socket write failed. // Darwin route can return success after a routing-socket write failed.
ok("", "route: writing to routing socket: File exists") 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::Route => ok("", ""),
Tool::Pfctl if self.pf_missing => Ran::Missing, Tool::Pfctl if self.pf_missing => Ran::Missing,
Tool::Pfctl if args == ["-E"] => ok("", self.pf_enable_output), Tool::Pfctl if args == ["-E"] => ok("", self.pf_enable_output),
@@ -741,7 +1000,27 @@ destination: default\n\
} }
#[test] #[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 other: Ipv4Range = "10.99.0.0/16".parse().unwrap();
let overlay = [range(), other]; let overlay = [range(), other];
let client = ClientRules { let client = ClientRules {
@@ -755,19 +1034,17 @@ destination: default\n\
), ),
"{text}" "{text}"
); );
assert!( let rules: Vec<_> = text.lines().skip(1).collect();
text.contains("nat on en0 inet from (utun5) to any -> (en0)\n"), assert_eq!(
"{text}" rules,
); [
assert!( "nat on en0 inet from (utun5) to any tagged tsng_underlay_utun5 -> (en0) static-port",
text.contains(
"pass out quick on utun5 route-to (en0 192.168.1.1) inet proto { tcp udp } \ "pass out quick on utun5 route-to (en0 192.168.1.1) inet proto { tcp udp } \
from any to ! <tsunagi_overlay_utun5> user 0\n" from any to ! <tsunagi_overlay_utun5> 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 \
"{text}" 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 { let direct = DefaultRoute {
interface: "ppp0".into(), interface: "ppp0".into(),
@@ -789,6 +1066,10 @@ destination: default\n\
#[test] #[test]
fn the_overlay_default_routes_are_halves_and_ipv6_is_rejected() { 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!( assert_eq!(
route_set_args("add", "0.0.0.0/1", "utun5", None).join(" "), route_set_args("add", "0.0.0.0/1", "utun5", None).join(" "),
"-q -n add -net 0.0.0.0/1 -interface utun5" "-q -n add -net 0.0.0.0/1 -interface utun5"
@@ -818,7 +1099,7 @@ destination: default\n\
#[test] #[test]
fn offering_loads_the_anchor_and_reads_but_never_writes_forwarding() { fn offering_loads_the_anchor_and_reads_but_never_writes_forwarding() {
let fake = Fake::new(); 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)); 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.offer, vec![(range(), RuleOutcome::Applied)]);
assert_eq!(report.forwarding, Some(true)); assert_eq!(report.forwarding, Some(true));
@@ -845,14 +1126,14 @@ destination: default\n\
); );
// No client routes were added for an offer alone. // No client routes were added for an offer alone.
assert_eq!(fake.count(" add "), 0); 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] #[test]
fn forwarding_off_is_reported_and_unreadable_is_none() { fn forwarding_off_is_reported_and_unreadable_is_none() {
let mut fake = Fake::new(); let mut fake = Fake::new();
fake.forwarding = "0\n"; 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)); let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
assert_eq!(report.forwarding, Some(false)); assert_eq!(report.forwarding, Some(false));
fake.forwarding = "junk"; fake.forwarding = "junk";
@@ -863,12 +1144,18 @@ destination: default\n\
#[test] #[test]
fn the_client_rules_are_loaded_before_the_routes_that_need_them() { fn the_client_rules_are_loaded_before_the_routes_that_need_them() {
let fake = Fake::new(); 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)); let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(false, true));
assert_eq!(report.client, Some(RuleOutcome::Applied)); assert_eq!(report.client, Some(RuleOutcome::Applied));
assert!(report.offer.is_empty()); assert!(report.offer.is_empty());
let load = fake.position("-f -").unwrap(); 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!(load < add, "{:?}", fake.calls());
assert!(fake.position("add -net 128.0.0.0/1").is_some()); assert!(fake.position("add -net 128.0.0.0/1").is_some());
assert!(fake.position("-inet6 -net ::/1 ::1 -reject").is_some()); assert!(fake.position("-inet6 -net ::/1 ::1 -reject").is_some());
@@ -880,17 +1167,19 @@ destination: default\n\
#[test] #[test]
fn both_exit_halves_use_the_selected_networks_address_on_a_shared_utun() { fn both_exit_halves_use_the_selected_networks_address_on_a_shared_utun() {
let fake = Fake::new(); let fake = Fake::new();
let token = Mutex::new(None); let token = HostState::default();
let mut selected = plan(false, true); let mut selected = plan(false, true);
selected.overlay.push("10.99.0.0/24".parse().unwrap()); 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()); selected.client_source = Some(source.parse().unwrap());
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &selected); let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &selected);
assert_eq!(report.client, Some(RuleOutcome::Applied)); assert_eq!(report.client, Some(RuleOutcome::Applied));
for half in HALVES { for half in HALVES {
assert!( assert!(
fake.position(&format!("add -net {half} -interface utun5 -ifa {source}")) fake.position(&format!(
.is_some() "{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()); selected.client_source = Some("10.99.0.17".parse().unwrap());
let mut fake = Fake::new(); let mut fake = Fake::new();
fake.half_interface = Some("utun5"); 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)); assert_eq!(report.client, Some(RuleOutcome::Applied));
for half in HALVES { for half in HALVES {
assert!( assert!(
@@ -918,19 +1211,104 @@ destination: default\n\
foreign.half_interface = Some("utun9"); foreign.half_interface = Some("utun9");
let report = apply_plan( let report = apply_plan(
&|t, a, s| foreign.run(t, a, s), &|t, a, s| foreign.run(t, a, s),
&Mutex::new(None), &HostState::default(),
&selected, &selected,
); );
assert!(matches!(report.client, Some(RuleOutcome::Failed(_)))); assert!(matches!(report.client, Some(RuleOutcome::Failed(_))));
assert_eq!(foreign.count(" change "), 0); 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::<Vec<_>>(),
["::/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] #[test]
fn no_routes_are_added_when_the_rules_did_not_load() { fn no_routes_are_added_when_the_rules_did_not_load() {
let mut fake = Fake::new(); let mut fake = Fake::new();
fake.pf_load_fails = true; 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 report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, true));
let Some(RuleOutcome::Failed(why)) = report.client else { let Some(RuleOutcome::Failed(why)) = report.client else {
panic!("{report:?}"); panic!("{report:?}");
@@ -947,7 +1325,7 @@ destination: default\n\
fn a_failing_route_is_a_failure_and_leaves_nothing_behind() { fn a_failing_route_is_a_failure_and_leaves_nothing_behind() {
let mut fake = Fake::new(); let mut fake = Fake::new();
fake.route_add_fails = true; 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 report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(false, true));
let Some(RuleOutcome::Failed(why)) = report.client else { let Some(RuleOutcome::Failed(why)) = report.client else {
panic!("{report:?}"); panic!("{report:?}");
@@ -970,7 +1348,7 @@ destination: default\n\
fn a_missing_pfctl_or_default_route_says_what_is_wrong() { fn a_missing_pfctl_or_default_route_says_what_is_wrong() {
let mut fake = Fake::new(); let mut fake = Fake::new();
fake.pf_missing = true; 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 report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
let RuleOutcome::Failed(why) = &report.offer[0].1 else { let RuleOutcome::Failed(why) = &report.offer[0].1 else {
panic!("{report:?}"); panic!("{report:?}");
@@ -991,7 +1369,7 @@ destination: default\n\
fn a_default_route_through_the_overlay_is_refused() { fn a_default_route_through_the_overlay_is_refused() {
let mut fake = Fake::new(); let mut fake = Fake::new();
fake.default_route = Some("gateway: 10.13.37.1\ninterface: utun5\n".into()); 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 report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
let RuleOutcome::Failed(why) = &report.offer[0].1 else { let RuleOutcome::Failed(why) = &report.offer[0].1 else {
panic!("{report:?}"); panic!("{report:?}");
@@ -1002,7 +1380,7 @@ destination: default\n\
#[test] #[test]
fn pf_is_enabled_once_and_released_once_on_clear() { fn pf_is_enabled_once_and_released_once_on_clear() {
let fake = Fake::new(); 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); 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, false));
apply_plan(&run, &token, &plan(true, true)); apply_plan(&run, &token, &plan(true, true));
@@ -1010,15 +1388,12 @@ destination: default\n\
clear_all(&run, &token, "utun5"); clear_all(&run, &token, "utun5");
assert_eq!(fake.count("Pfctl -X 4242"), 1); assert_eq!(fake.count("Pfctl -X 4242"), 1);
assert!( assert_eq!(fake.stdins.borrow().last().map(String::as_str), Some(""));
fake.position("-a com.apple/tsunagi-exit-utun5 -F all")
.is_some()
);
assert!( assert!(
fake.position("delete -net 0.0.0.0/1 -interface utun5") fake.position("delete -net 0.0.0.0/1 -interface utun5")
.is_some() .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. // A second clear has nothing to release and still succeeds.
clear_all(&run, &token, "utun5"); clear_all(&run, &token, "utun5");
assert_eq!(fake.count("Pfctl -X"), 1); assert_eq!(fake.count("Pfctl -X"), 1);
@@ -1027,10 +1402,15 @@ destination: default\n\
#[test] #[test]
fn dropping_the_client_removes_its_routes() { fn dropping_the_client_removes_its_routes() {
let fake = Fake::new(); 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); 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)); apply_plan(&run, &token, &plan(true, false));
assert!(fake.position("delete -net 0.0.0.0/1").is_some()); assert!(fake.position("delete -net 0.0.0.0/1").is_some());
assert_eq!(fake.count(" add "), 0); assert_eq!(fake.count(" add "), adds);
} }
} }
@@ -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<dyn TunDevice> {
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<Option<String>>,
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);
}
}
@@ -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<ScopedHalf>,
ipv6: bool,
}
#[derive(Debug)]
pub(super) struct ScopedRoutes {
journal: Option<PathBuf>,
loaded: bool,
owned: Journal,
pub(super) active: Option<DefaultRoute>,
checked: Option<Instant>,
}
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<String> {
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<u32> {
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<Option<(DefaultRoute, Option<u32>)>, 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::<u64>()));
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<ScopedHalf> {
self.owned.routes.clone()
}
pub(super) fn ipv6_marker(&self) -> Option<u32> {
self.owned.ipv6.then_some(self.owned.marker)
}
pub(super) fn record_ipv6(&mut self, active: bool) -> Result<u32, String> {
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<ScopedHalf> {
[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(())
}
}
@@ -28,6 +28,10 @@
#![cfg_attr(not(target_os = "windows"), allow(dead_code))] #![cfg_attr(not(target_os = "windows"), allow(dead_code))]
use crate::BoxFuture; 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::exit::{ExitHostPlan, ExitHostReport, ExitHostRules};
use super::windows_exit; 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. /// Runs a script and returns what it printed, or what it said on failure.
fn run_powershell_output(script: &str) -> Result<String, String> { pub(super) fn run_powershell_output(script: &str) -> Result<String, String> {
let output = std::process::Command::new(powershell_path()) let output = std::process::Command::new(powershell_path())
.args([ .args([
"-NoProfile", "-NoProfile",
@@ -153,12 +157,61 @@ async fn step(what: &'static str, script: String) -> RuleOutcome {
/// The Windows implementation, through PowerShell. /// The Windows implementation, through PowerShell.
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct WindowsHostRules; pub struct WindowsHostRules {
relay_cache: Arc<Mutex<RelayCache>>,
}
impl WindowsHostRules { impl WindowsHostRules {
/// Creates it. Nothing is run until [`BroadcastHostRules::apply`]. /// Creates it. Nothing is run until [`BroadcastHostRules::apply`].
pub fn new() -> Self { 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<String, BTreeMap<Ipv4Addr, Instant>>,
last_refresh: Option<Instant>,
}
impl RelayCache {
fn lookup(
&mut self,
hosts: &[String],
now: Instant,
resolve: windows_exit::Resolve<'_>,
) -> HashMap<String, Vec<Ipv4Addr>> {
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<std::net::Ipv4Addr> {
IpAddr::V4(ip) => Some(ip), IpAddr::V4(ip) => Some(ip),
IpAddr::V6(_) => None, IpAddr::V6(_) => None,
}) })
.take(MAX_RELAY_ADDRESSES)
.collect() .collect()
}) })
.unwrap_or_default() .unwrap_or_default()
@@ -186,10 +240,16 @@ impl ExitHostRules for WindowsHostRules {
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> { fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
Box::pin(async move { Box::pin(async move {
let job = plan.clone(); let job = plan.clone();
let cache = Arc::clone(&self.relay_cache);
tokio::task::spawn_blocking(move || { 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( windows_exit::apply_plan(
&|script| run_powershell_output(script), &|script| run_powershell_output(script),
&resolve_host, &|host| hosts.get(host).cloned().unwrap_or_default(),
&job, &job,
) )
}) })
@@ -209,10 +269,46 @@ impl ExitHostRules for WindowsHostRules {
}) })
} }
fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
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, ()> { fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
Box::pin(async move { Box::pin(async move {
let name = interface.to_string(); let name = interface.to_string();
let cache = Arc::clone(&self.relay_cache);
let _ = tokio::task::spawn_blocking(move || { 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) windows_exit::clear_all(&|script| run_powershell_output(script), &name)
}) })
.await; .await;
@@ -258,6 +354,29 @@ mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*; 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; use std::net::Ipv4Addr;
fn plan() -> BroadcastRulesPlan { fn plan() -> BroadcastRulesPlan {
@@ -108,8 +108,8 @@ fn forwarding_script(interface: &str) -> String {
) )
} }
/// Prints `<interface index> <next hop>` of the best default route that is /// Prints the physical default and the more specific routes that already
/// not through the overlay interface. /// outrank the split defaults. Ignore our own host routes when refreshing.
fn gateway_script(interface: &str) -> String { fn gateway_script(interface: &str) -> String {
let alias = ps_literal(interface); let alias = ps_literal(interface);
format!( format!(
@@ -121,7 +121,11 @@ fn gateway_script(interface: &str) -> String {
(Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }} | \ (Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }} | \
Select-Object -First 1\n\ Select-Object -First 1\n\
if (-not $best) {{ throw 'the host has no default gateway outside the overlay' }}\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() .collect()
} }
fn apply_client( pub(super) fn refresh_bypass(
run: RunScript<'_>, run: RunScript<'_>,
resolve: Resolve<'_>, resolve: Resolve<'_>,
plan: &ExitHostPlan, plan: &ExitHostPlan,
) -> Result<(), String> { ) -> Result<(), String> {
let interface = plan.interface.as_str(); let interface = plan.interface.as_str();
let gateway = run(&gateway_script(interface))?; let gateway = run(&gateway_script(interface))?;
let (index, hop) = parse_gateway(&gateway) let mut lines = gateway.lines();
.ok_or_else(|| format!("cannot read the default gateway from `{}`", gateway.trim()))?; let first = lines.next().unwrap_or_default();
let addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts, &plan.overlay); let (index, hop) = parse_gateway(first)
run(&bypass_script(index, hop, &addresses))?; .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::<Ipv4Addr>().ok()?, bits.parse::<u8>().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)) { if let Err(why) = run(&halves_script(interface)) {
// Do not leave a half-installed set: bypass routes alone are harmless // Do not leave a half-installed set: bypass routes alone are harmless
// but the next apply starts clean. // but the next apply starts clean.
@@ -412,6 +441,58 @@ mod tests {
Vec::new() 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 { fn client_plan() -> ExitHostPlan {
ExitHostPlan { ExitHostPlan {
interface: "tsun0".into(), interface: "tsun0".into(),
@@ -549,6 +630,47 @@ mod tests {
assert!(!bypass.contains("'10.13.37.4'") && !bypass.contains("'10.99.0.6'")); 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] #[test]
fn nothing_goes_through_the_overlay_when_the_bypass_cannot_be_written() { fn nothing_goes_through_the_overlay_when_the_bypass_cannot_be_written() {
let run = |script: &str| -> Result<String, String> { let run = |script: &str| -> Result<String, String> {
+6 -6
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-runtime" name = "tsunagi-runtime"
version = "1.0.2" version = "1.0.3-rc1"
description = "Built-in mesh transports and status reporting for native tsunagi agents." description = "Built-in mesh transports and status reporting for native tsunagi agents."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -8,11 +8,11 @@ license.workspace = true
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.2" } tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.3-rc1" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.2" } tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.3-rc1" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.2" } tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.3-rc1" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.2" } tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.3-rc1" }
tokio.workspace = true tokio.workspace = true
tracing.workspace = true tracing.workspace = true
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-tcp-tls" name = "tsunagi-tcp-tls"
version = "1.0.2" version = "1.0.3-rc1"
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic." description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -8,7 +8,7 @@ license.workspace = true
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" }
iroh.workspace = true iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] } tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
rustls = "0.23" rustls = "0.23"
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-tray" name = "tsunagi-tray"
version = "1.0.2" version = "1.0.3-rc1"
description = "Tray application to manage a running tsunagi agent." description = "Tray application to manage a running tsunagi agent."
edition.workspace = true edition.workspace = true
rust-version.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 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 # the same local control interface the CLI uses, so it reuses these directly
# and never re-implements the protocol. # 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. # Native, lightweight GUI — no web engine. eframe re-exports egui.
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] } 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). # Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI).
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-ui" name = "tsunagi-ui"
version = "1.0.2" version = "1.0.3-rc1"
description = "Shared egui widgets for the tray and Android clients." description = "Shared egui widgets for the tray and Android clients."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
+2 -2
View File
@@ -3,7 +3,7 @@ name = "tsunagi-wg-quic"
# Its own version, and deliberately separate from the wire version it # 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 # negotiates: a release here does not stop it talking to a peer on an older
# build, because what peers compare is `ANNOUNCEMENT_VERSION`. # 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." description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -11,7 +11,7 @@ license.workspace = true
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" }
iroh.workspace = true iroh.workspace = true
tokio.workspace = true tokio.workspace = true
serde.workspace = true serde.workspace = true
+72 -8
View File
@@ -18,11 +18,11 @@ use iroh::EndpointId;
use tempfile::TempDir; use tempfile::TempDir;
use tsunagi::dataplane::IpPlugin; use tsunagi::dataplane::IpPlugin;
use tsunagi::discovery::SharedMemoryDiscovery; use tsunagi::discovery::SharedMemoryDiscovery;
use tsunagi::identity::NetworkId; use tsunagi::identity::{NetworkId, NetworkName, NetworkSecret};
use tsunagi::overlay::{MemoryTun, MemoryTunFactory, MockHostRules}; use tsunagi::overlay::{MemoryTun, MemoryTunFactory, MockHostRules};
use tsunagi::state::{DEFAULT_IPV4_RANGE, Ipv4Range}; use tsunagi::state::{DEFAULT_IPV4_RANGE, Ipv4Range};
use tsunagi::testing::{network, wait_until}; use tsunagi::testing::{network, wait_until};
use tsunagi::{Agent, NetworkStatus}; use tsunagi::{Agent, AgentConfig, NetworkStatus};
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin}; use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34); const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34);
@@ -52,6 +52,12 @@ impl Node {
tag: &str, tag: &str,
range: Option<Ipv4Range>, range: Option<Ipv4Range>,
) -> Self { ) -> 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 tuns = MemoryTunFactory::new();
let rules = MockHostRules::new(); let rules = MockHostRules::new();
let plugin = WireguardPlugin::open( let plugin = WireguardPlugin::open(
@@ -61,8 +67,7 @@ impl Node {
.await .await
.unwrap(); .unwrap();
let agent = Agent::spawn( let agent = Agent::spawn(
tsunagi::testing::config_with(dir.path(), discovery) config
.with_overlay_ipv4_range(range)
.with_interface( .with_interface(
Arc::new(tuns.clone().with_host_rules(Arc::new(rules.clone()))), Arc::new(tuns.clone().with_host_rules(Arc::new(rules.clone()))),
tag, tag,
@@ -164,10 +169,15 @@ struct ExitNetwork<'a> {
} }
impl<'a> ExitNetwork<'a> { impl<'a> ExitNetwork<'a> {
async fn join(client: &Node, peer: &'a Node, name: &str, range: Ipv4Range) -> Self { async fn join(
let (name, secret) = network(name); client: &Node,
peer: &'a Node,
credentials: (NetworkName, NetworkSecret),
) -> Self {
let (name, secret) = credentials;
let id = peer.agent.join_network(&name, &secret).await.unwrap(); let id = peer.agent.join_network(&name, &secret).await.unwrap();
peer.overlay(id).await; peer.overlay(id).await;
let range = peer.status(id).await.range.unwrap();
peer.agent.set_exit_offer(id, true).await.unwrap(); peer.agent.set_exit_offer(id, true).await.unwrap();
client.agent.join_network(&name, &secret).await.unwrap(); client.agent.join_network(&name, &secret).await.unwrap();
client.wait_for_tunnels(id, 1).await; 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), Some(right_range),
) )
.await; .await;
let alpha = ExitNetwork::join(&client, &left, "exit-left", DEFAULT_IPV4_RANGE).await; let alpha = ExitNetwork::join(&client, &left, network("exit-left")).await;
let beta = ExitNetwork::join(&client, &right, "exit-right", right_range).await; let beta = ExitNetwork::join(&client, &right, network("exit-right")).await;
let tun = client.tun().await; let tun = client.tun().await;
for exit in [&alpha, &beta] { 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; 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] #[tokio::test]
async fn a_member_sends_its_internet_traffic_through_an_exit_node_and_gets_the_answers() { async fn a_member_sends_its_internet_traffic_through_an_exit_node_and_gets_the_answers() {
let discovery = SharedMemoryDiscovery::new(); let discovery = SharedMemoryDiscovery::new();
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-wireguard" name = "tsunagi-wireguard"
version = "1.0.2" version = "1.0.3-rc1"
description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi." description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -8,7 +8,7 @@ license = "WTFPL AND Apache-2.0"
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" }
iroh.workspace = true iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] } tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
serde.workspace = true serde.workspace = true
+6 -6
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi" name = "tsunagi"
version = "1.0.2" version = "1.0.3-rc1"
description = "The tsunagi command line agent." description = "The tsunagi command line agent."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -12,11 +12,11 @@ name = "tsng"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.2" } tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.3-rc1" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.2", features = ["tun-device", "dns-publish"] } tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.2" } tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.3-rc1" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.2" } tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.3-rc1" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.2" } tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.3-rc1" }
iroh.workspace = true iroh.workspace = true
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] } tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
tracing.workspace = true tracing.workspace = true
+14 -6
View File
@@ -4658,7 +4658,7 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
let tun_factory: Arc<dyn TunFactory> = if args.no_tun { let tun_factory: Arc<dyn TunFactory> = if args.no_tun {
Arc::new(MemoryTunFactory::new()) Arc::new(MemoryTunFactory::new())
} else { } else {
system_tun_factory()? system_tun_factory(&paths.state_dir)?
}; };
let mtu = args.mtu.unwrap_or(tsunagi_wg_quic::DEFAULT_MTU); let mtu = args.mtu.unwrap_or(tsunagi_wg_quic::DEFAULT_MTU);
config = config.with_interface(tun_factory, args.interface.clone(), 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 /// an open file descriptor and goes away with the agent, however the agent
/// goes away. /// goes away.
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> { fn system_tun_factory(
_state_dir: &std::path::Path,
) -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
use tsunagi::overlay::{ManagedTunFactory, NetlinkProvisioner}; use tsunagi::overlay::{ManagedTunFactory, NetlinkProvisioner};
let provisioner = NetlinkProvisioner::new()?; let provisioner = NetlinkProvisioner::new()?;
let rules = Arc::new(provisioner.host_rules()); let rules = Arc::new(provisioner.host_rules());
@@ -4967,7 +4969,9 @@ fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error
/// The Wintun adapter, created and configured by the agent and removed when it /// The Wintun adapter, created and configured by the agent and removed when it
/// exits, the same as the Linux one. /// exits, the same as the Linux one.
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> { fn system_tun_factory(
_state_dir: &std::path::Path,
) -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
use tsunagi::overlay::{ManagedTunFactory, WindowsHostRules, WintunProvisioner}; use tsunagi::overlay::{ManagedTunFactory, WindowsHostRules, WintunProvisioner};
let provisioner = WintunProvisioner::new()?; let provisioner = WintunProvisioner::new()?;
Ok(Arc::new( Ok(Arc::new(
@@ -4980,12 +4984,14 @@ fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error
/// exits, the same as the Linux and Windows ones. The kernel assigns the utun /// exits, the same as the Linux and Windows ones. The kernel assigns the utun
/// unit, so the interface reports a `utunN` name the agent adopts. /// unit, so the interface reports a `utunN` name the agent adopts.
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> { fn system_tun_factory(
state_dir: &std::path::Path,
) -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
use tsunagi::overlay::{MacosHostRules, ManagedTunFactory, UtunProvisioner}; use tsunagi::overlay::{MacosHostRules, ManagedTunFactory, UtunProvisioner};
let provisioner = UtunProvisioner::new()?; let provisioner = UtunProvisioner::new()?;
Ok(Arc::new( Ok(Arc::new(
ManagedTunFactory::new(Arc::new(provisioner)) 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<Arc<dyn TunFactory>, Box<dyn std::error::Error
/// Refused here rather than at the first packet, and with the one thing that /// Refused here rather than at the first packet, and with the one thing that
/// does work on every platform named. /// does work on every platform named.
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))] #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> { fn system_tun_factory(
_state_dir: &std::path::Path,
) -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
Err(format!( Err(format!(
"managing the overlay interface is not implemented on {} yet. \ "managing the overlay interface is not implemented on {} yet. \
Run with `--no-tun` to keep the tunnels off the operating system.", Run with `--no-tun` to keep the tunnels off the operating system.",
+3 -1
View File
@@ -14,7 +14,9 @@ set -euo pipefail
binary="$1" binary="$1"
arch="$2" 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" output="$4"
tray="${5:-}" tray="${5:-}"
+16
View File
@@ -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)"
+6
View File
@@ -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 socket is open to the `admin` group, so the CLI and the tray work without
`sudo` for an administrator. `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 ### Publishing Homebrew packages
After a stable `vMAJOR.MINOR.PATCH` GitHub release uploads its assets, the After a stable `vMAJOR.MINOR.PATCH` GitHub release uploads its assets, the
+23 -13
View File
@@ -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 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 time the rules are applied**; after it changes (Wi-Fi to Ethernet) switch the
offer off and on. offer off and on.
- **Using:** `0.0.0.0/1` and `128.0.0.0/1` routes through the overlay interface - When **using** an exit, ordinary IPv4 internet connections take the two
with the local address of the exit network as their source, split-default routes through the utun, with the local address of the selected
and a `pf` `route-to` rule that sends the agent's own traffic (matched by its network. More specific routes continue to reach their own networks.
user id, root) back out the physical interface, with translation to that - Sockets already using the physical address need matching routes scoped to
interface's address. Anything else you run as root also bypasses the tunnel. the uplink. Without them, macOS can reject a send before the packet reaches
IPv6 is blocked with rejecting `::/1` and `8000::/1` routes. PF. For new TCP and UDP sockets, PF sends the agent's traffic out the uplink
- Not verified on a live host when this was written: run `tsng exit-node` and and preserves its source port. Replies to these tagged connections return
check `sudo pfctl -a com.apple/tsunagi-exit-utunN -s rules -s nat`. 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 ## 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 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") overlay interface; a `/32` route with metric 7373 (the marker for "ours")
through the physical default gateway is added for every address the agent through the physical default gateway is added for every address the agent
talks to directly: verified direct paths of its connections, plus the relays talks to directly, including verified connection paths and current relay
it uses, resolved when the rules are applied. The set follows path changes. A servers. Existing LAN and other more specific routes keep their next hop.
newly authenticated connection supplies its direct paths immediately and the A newly authenticated connection supplies its direct paths immediately.
discovery tick refreshes them. Physical bypass routes exclude every active After a disconnect, the agent keeps its last verified paths for up to two
mesh subnet. Wintun can choose any local alias for the default route. For 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 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. tunnel and restores replies to the address the Windows socket used.
IPv6 is blackholed with `::/1` and `8000::/1` on the overlay interface, IPv6 is blackholed with `::/1` and `8000::/1` on the overlay interface,
+1 -1
View File
@@ -34,7 +34,7 @@ let
in in
rustPlatform.buildRustPackage { rustPlatform.buildRustPackage {
pname = if withTray then "tsunagi" else "tsunagi-cli"; pname = if withTray then "tsunagi" else "tsunagi-cli";
version = "1.0.2"; version = "1.0.3-rc1";
src = lib.cleanSource ../.; src = lib.cleanSource ../.;
cargoLock.lockFile = ../Cargo.lock; cargoLock.lockFile = ../Cargo.lock;