Preserve macOS exit replies and isolate the Linux service fixture

Apple PF restores the forwarding tag from the physical NAT state on replies. Steer only packets sourced in an offered mesh and destined outside the offered ranges. Reverse-translated replies can then leave on the utun, including while the local host uses an upstream exit.

Apply the same rule in the authorized sharing helper. An older installed copy can still clear its anchors. Re-enabling sharing upgrades it through the normal authorization dialog and preserves existing subnet grants.

Run the Linux namespace B process with a service environment. Give its parent an explicit login environment in CI to keep exercising this boundary without weakening the agent’s login-session guard.

Reproduced the Linux denial and passed the corrected established-flow test in isolated kernel namespaces. On macOS the workspace suite, Clippy, formatting, exit helper regressions and the PF syntax check passed. The privileged two-utun test requires a disposable Mac and was not run locally.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-26 02:20:40 +02:00
1 parent 7dacc4517e
commit 9920d4c10f
7 files changed
+89 -18

No files matched your search

+2 -1
View File
@@ -65,7 +65,8 @@ jobs:
- name: Verify separate forwarding and local egress in Linux namespaces
if: runner.os == 'Linux'
shell: bash
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
# The invoking login and the service inside namespace B have distinct environments.
run: sudo -n -- env XDG_RUNTIME_DIR="/run/user/$(id -u)" "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
- name: Verify source selection on a real utun
if: runner.os == 'macOS'
shell: bash
@@ -669,6 +669,8 @@ fn serving_an_established_flow_while_switching_the_local_exit() {
.arg(std::env::current_exe().unwrap())
.args(["--ignored", "--exact", CHAIN_TEST, "--nocapture"])
.env("TSUNAGI_EXIT_CHAIN_A", &a.0)
// B runs as a system service, even when the test was started from a login.
.env_remove("XDG_RUNTIME_DIR")
.output()
.unwrap();
assert!(
@@ -14,7 +14,7 @@ helper="$directory/offer-v1"
/bin/chmod 0755 "$directory"
tmp=$(/usr/bin/mktemp -d "$directory/.install.XXXXXXXX")
trap '/bin/rm -rf "$tmp"' EXIT
printf '%s\n' "$helper_body" > "$tmp/offer"
printf '%s' "$helper_body" > "$tmp/offer"
printf '#%s ALL = (root) NOPASSWD: NOSETENV: %s\n' "$uid" "$helper" > "$tmp/rule"
/usr/sbin/visudo -c -q -f "$tmp/rule"
/bin/chmod 0755 "$tmp/offer"
@@ -125,7 +125,7 @@ if [ ! -f "$record" ]; then
fi
if ! /sbin/pfctl -q -a "$anchor" -f - <<RULES
nat on $out inet from $range to any tagged $tag -> ($out)
pass out quick on $iface route-to $via inet from any to any tagged $tag no state
pass out quick on $iface route-to $via inet from $range to ! $range tagged $tag no state
pass in quick on $iface inet from $range to ! $range tag $tag no state
pass out quick on $out inet from any to any flags any tagged $tag keep state (if-bound)
RULES
@@ -10,7 +10,7 @@
//! ```text
//! nat on <egress> inet from <range> to any tagged <forwarded> -> (<egress>)
//! pass in quick on <if> inet from <range> to ! <range> tag <forwarded> no state
//! pass out quick on <if> route-to (<egress> <gateway>) inet from <range> to any tagged <forwarded> no state
//! pass out quick on <if> route-to (<egress> <gateway>) inet from <range> to ! <range> tagged <forwarded> no state
//! pass out quick on <egress> inet from any to any flags any tagged <forwarded> keep state (if-bound)
//! ```
//!
@@ -88,6 +88,15 @@ use super::macos_authorization::{macos_exit_authorization_uid, macos_exit_needs_
const OFFER_HELPER: &str = "/private/etc/tsunagi-exit/offer-v1";
fn offer_helper_available(path: &std::path::Path, action: &str) -> bool {
// A previous release can still remove its own PF anchors. Applying its
// obsolete rules would silently restore the broken return path.
if action == "clear" {
return path.is_file();
}
std::fs::read(path).is_ok_and(|bytes| bytes == include_bytes!("macos/exit-offer.sh").as_slice())
}
/// The programs this module runs, always by absolute path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Tool {
@@ -133,7 +142,11 @@ pub(super) fn run_tool(tool: Tool, args: &[String], stdin: Option<&str>) -> Ran
use std::process::{Command, Stdio};
let mut command = if tool == Tool::OfferHelper {
if !std::path::Path::new(OFFER_HELPER).is_file() {
let path = std::path::Path::new(OFFER_HELPER);
if !args
.first()
.is_some_and(|op| offer_helper_available(path, op))
{
return Ran::Missing;
}
let mut sudo = Command::new("/usr/bin/sudo");
@@ -415,23 +428,30 @@ fn pf_rules(
from any to any flags any tagged {tag} keep state (if-bound)"
));
}
for range in offer {
if let [first, rest @ ..] = offer {
let members = if rest.is_empty() {
first.to_string()
} else {
let name = format!("<tsunagi_offer_{interface}>");
let ranges: Vec<_> = offer.iter().map(ToString::to_string).collect();
tables.push(format!("table {name} const {{ {} }}", ranges.join(", ")));
name
};
let tag = format!("tsng_forward_{interface}");
nat.push(format!(
"nat on {out} inet from {range} to any tagged {tag} -> ({out})"
"nat on {out} inet from {members} to any tagged {tag} -> ({out})"
));
// Classify at authenticated overlay ingress. Only packets the host
// actually forwards AND its routes send back to our utun need steering.
// Local services, connected LANs and the owner's forwarding switch
// retain their native kernel behavior.
filter.push(format!(
"pass in quick on {interface} inet from {range} to ! {range} tag {tag} no state"
"pass in quick on {interface} inet from {members} to ! {members} tag {tag} no state"
));
}
if !offer.is_empty() {
let tag = format!("tsng_forward_{interface}");
// PF restores the state's tag on replies after undoing NAT. A reply
// routed back to a member must leave on the overlay with that tag.
filter.insert(0, format!(
"pass out quick on {interface} route-to {via} inet from any to any tagged {tag} no state"
"pass out quick on {interface} route-to {via} inet from {members} to ! {members} tagged {tag} no state"
));
// Keep the outbound NAT state on the physical interface. A floating
// state could consume packets on the utun before the reroute rule runs.
@@ -1166,7 +1186,7 @@ destination: default\n\
assert_eq!(
text,
"nat on en0 inet from 10.13.37.0/24 to any tagged tsng_forward_utun5 -> (en0)\n\
pass out quick on utun5 route-to (en0 192.168.1.1) inet from any to any tagged tsng_forward_utun5 no state\n\
pass out quick on utun5 route-to (en0 192.168.1.1) inet from 10.13.37.0/24 to ! 10.13.37.0/24 tagged tsng_forward_utun5 no state\n\
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24 tag tsng_forward_utun5 no state\n\
pass out quick on en0 inet from any to any flags any tagged tsng_forward_utun5 keep state (if-bound)\n"
);
@@ -1174,6 +1194,32 @@ destination: default\n\
assert!(text.find("nat on").unwrap() < text.find("pass in").unwrap());
}
#[test]
fn forwarding_excludes_replies_to_every_offered_mesh() {
let ranges = [range(), "10.99.0.0/16".parse().unwrap()];
let client = ClientRules {
uid: 0,
overlay: &ranges,
};
for local_exit in [None, Some(&client)] {
let text = pf_rules("utun5", &egress(), &ranges, local_exit);
let offered = "<tsunagi_offer_utun5>";
assert!(text.contains(&format!(
"table {offered} const {{ 10.13.37.0/24, 10.99.0.0/16 }}"
)));
let mut steering = text
.lines()
.filter(|r| r.contains("route-to") && r.contains("tagged tsng_forward_"));
assert!(
steering
.next()
.unwrap()
.contains(&format!("from {offered} to ! {offered} "))
);
assert!(steering.next().is_none());
}
}
#[test]
fn the_agents_tagged_nat_precedes_any_general_masquerade_for_offered_ranges() {
let ranges = [range()];
@@ -1289,7 +1335,7 @@ destination: default\n\
assert_eq!(
fake.stdins.borrow()[0],
"nat on en0 inet from 10.13.37.0/24 to any tagged tsng_forward_utun5 -> (en0)\n\
pass out quick on utun5 route-to (en0 192.168.1.1) inet from any to any tagged tsng_forward_utun5 no state\n\
pass out quick on utun5 route-to (en0 192.168.1.1) inet from 10.13.37.0/24 to ! 10.13.37.0/24 tagged tsng_forward_utun5 no state\n\
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24 tag tsng_forward_utun5 no state\n\
pass out quick on en0 inet from any to any flags any tagged tsng_forward_utun5 keep state (if-bound)\n"
);
@@ -146,6 +146,25 @@ fn privileged_helper_accepts_only_a_granted_subnet_configured_on_the_utun() {
);
}
#[test]
fn an_update_replaces_the_old_helper_and_preserves_existing_subnet_grants() {
let host = Host::new();
let helper = host.0.path().join("grants/offer-v1");
assert!(!super::offer_helper_available(&helper, "clear"));
host.grant("501", "10.13.37.0_24");
fs::write(&helper, "#!/bin/sh\n# previous release\n").unwrap();
assert!(!super::offer_helper_available(&helper, "apply"));
assert!(super::offer_helper_available(&helper, "clear"));
host.grant("501", "10.99.0.0_16");
assert!(super::offer_helper_available(&helper, "apply"));
assert!(
host.0
.path()
.join("grants/grant_501_10.13.37.0_24")
.is_file()
);
}
#[test]
fn authorized_exit_owns_one_pf_reference_and_clears_only_its_anchor() {
let host = Host::new();
+7 -4
View File
@@ -116,9 +116,10 @@ and configured networks.
- **Offering:** a `pf` anchor `com.apple/tsunagi-exit-<interface>` (the stock
`/etc/pf.conf` already evaluates `com.apple/*`) holds
NAT for traffic tagged on entry from an offered range. A tagged packet that the
kernel would forward back to the utun gets a PF `route-to` through the
physical gateway. The physical NAT state is interface-bound.
NAT for traffic tagged on entry from an offered range. If the kernel chooses
the utun for a member's outbound internet packet, PF steers it through the
physical gateway. Replies keep the tag after reverse NAT and return to the
member over the utun. The physical NAT state is interface-bound.
`pf` is enabled if it was off, and that reference is released when the rules
go. After installing the rules the agent enables IPv4 forwarding and checks
the kernel's answer before advertising the exit. Stopping the offer removes
@@ -133,7 +134,9 @@ and configured networks.
a separate grant. The helper checks the live utun address and mask, selects
the uplink from the kernel, and manages its own PF anchor and enable token.
It accepts only sharing operations. The agent can subsequently reconcile and
remove these rules without prompting. At startup it reclaims orphaned helper
remove these rules without prompting. When an update changes the helper,
enabling sharing again prompts once to replace it and keeps existing subnet
grants. At startup the agent reclaims orphaned helper
anchors for the account by checking the owning process and its start time.
For a system agent with the necessary
rights, the initial enable completes directly.