Keep every active mesh reachable through a single internet exit

With several IPv4 aliases on a single TUN, the default route could select an address from a different mesh. The exit peer then rejected internet traffic as an invalid source. Concurrent cross-network exit selections could also clear each other in the running agent while SQLite kept one winner.

Serialize validated exit choices with network lifecycle and persist each choice before publishing it to the shared routing table. Replace the previous exit atomically and preserve it across allocation updates. Both mesh subnets keep their own routes. Only replies from the selected exit to the local address of its network qualify for the external-source exception.

Prefer the selected source on Linux and macOS default routes. Preserve physical transport paths and update split routes in place. On Windows reuse the Android packet translation to restore off-mesh TCP, UDP and ICMP replies to the original local socket. Existing databases, IPC commands and wire protocols remain compatible.

On macOS, formatting and strict workspace Clippy passed. The full locked workspace suite passed 577 tests with three ignored, after correcting a stale Windows script-test matcher. Three real agents covered switching, concurrent selection, offline isolation and restart. On Linux arm64, 88 focused tests and the privileged kernel routing/firewall test passed. The Android arm64 library built and linked. Wintun and privileged macOS utun were not exercised on live hosts.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-25 02:32:09 +02:00
1 parent 21b8381fa3
commit 32aa73721a
23 files changed
+1167 -304

No files matched your search

@@ -24,7 +24,7 @@
//! Policy routing, with no `/1` routes and nothing in the main table:
//!
//! ```text
//! table 0x7473: default dev <if>
//! table 0x7473: default dev <if> src <selected overlay address>
//! 5205: from all fwmark 0x40000000/0x40000000 lookup main
//! 5206: from all uidrange <euid>-<euid> lookup main
//! 5290: from all lookup main suppress_prefixlength 0
@@ -45,6 +45,7 @@
use crate::BoxFuture;
use crate::state::Ipv4Range;
use std::net::Ipv4Addr;
use super::RuleOutcome;
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules, exit_tag, exit_tag_prefix};
@@ -441,7 +442,7 @@ impl LinuxHostRules {
.map_err(|err| format!("the task failed: {err}"))
}
async fn apply_client(&self, interface: &str) -> RuleOutcome {
async fn apply_client(&self, interface: &str, source: Option<Ipv4Addr>) -> RuleOutcome {
let xdg = std::env::var("XDG_RUNTIME_DIR").ok();
if let Some(reason) = client_refusal(xdg.as_deref()) {
// Whatever an earlier run left must not stay in force.
@@ -461,7 +462,15 @@ impl LinuxHostRules {
.as_ref()
.is_some_and(|(name, _, routed)| name == interface && *routed);
if installed {
// A failed socket refresh must never remove an active exit route.
// A different network can now supply the exit on this same TUN.
// Preserve the policy rules and underlay protection during the switch.
let route = self.route.clone();
let name = interface.to_string();
match Self::blocking(move || route.update_exit_source(&name, source)).await {
Ok(Ok(())) => {}
Ok(Err(err)) => return RuleOutcome::Failed(err.to_string()),
Err(reason) => return RuleOutcome::Failed(reason),
}
return self
.refresh_sockets(interface)
.await
@@ -492,7 +501,8 @@ impl LinuxHostRules {
}
let route = self.route.clone();
let name = interface.to_string();
let outcome = match Self::blocking(move || route.set_exit_client(&name, euid)).await {
let outcome = match Self::blocking(move || route.set_exit_client(&name, euid, source)).await
{
Ok(Ok(())) => RuleOutcome::Applied,
Ok(Err(err)) => RuleOutcome::Failed(err.to_string()),
Err(reason) => RuleOutcome::Failed(reason),
@@ -616,7 +626,7 @@ impl ExitHostRules for LinuxHostRules {
forwarding_state(read_sysctl, &interface)
};
let client = if plan.client {
Some(self.apply_client(&interface).await)
Some(self.apply_client(&interface, plan.client_source).await)
} else {
if let Err(reason) = self.clear_client(&interface).await {
tracing::warn!(%reason, "cannot remove exit-client rules");
@@ -217,7 +217,9 @@ fn client() {
ip(&["-6", "route", "add", "throw", prefix, "table", "52"]);
}
let mut passive = spawn_listener("listener");
route.set_exit_client("tsun0", 990).unwrap();
route
.set_exit_client("tsun0", 990, Some("10.99.0.1".parse().unwrap()))
.unwrap();
// uid bypass alone cannot protect reverse lookups, reproducing the bug.
run_probes("blocked");
install(&run_firewall, "tsun0", 990, true).unwrap();
@@ -248,6 +250,25 @@ for family,source,target in [(socket.AF_INET,'198.51.100.2','192.0.2.1'),(socket
install(&run_firewall, "tsun0", 990, true).unwrap();
run_probes("pass");
assert!(ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]).contains("dev tsun0"));
// Check our own default table without the foreign VPN's higher-priority default.
ip(&["-4", "rule", "del", "priority", "5270"]);
for (destination, source) in [
("10.13.37.2", "10.13.37.1"),
("10.99.0.2", "10.99.0.1"),
("198.51.100.2", "10.99.0.1"),
] {
let result = ip(&["-4", "route", "get", destination, "uid", "991"]);
assert!(
result.contains("dev tsun0") && result.contains(&format!("src {source}")),
"{result}"
);
}
route
.update_exit_source("tsun0", Some("10.13.37.1".parse().unwrap()))
.unwrap();
assert!(ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]).contains("src 10.13.37.1"));
assert!(ip(&["-4", "route", "get", "10.99.0.2", "uid", "991"]).contains("src 10.99.0.1"));
ip(&["-4", "rule", "add", "priority", "5270", "table", "52"]);
let blocked = Command::new("ip")
.args(["-6", "route", "get", "2001:db8:2::2", "uid", "991"])
.output()
@@ -384,6 +405,15 @@ fn strict_firewall_preserves_underlay_and_application_exit_routing() {
"tsun0",
]);
ip(&["-n", &client_name, "link", "set", "tsun0", "up"]);
ip(&[
"-n",
&client_name,
"addr",
"add",
"10.99.0.1/24",
"dev",
"tsun0",
]);
let echo_code = r#"import socket,selectors,sys
selector=selectors.DefaultSelector()
for family in [socket.AF_INET,socket.AF_INET6]:
@@ -29,8 +29,8 @@
//! Linux scheme does not carry over. Instead:
//!
//! ```text
//! route add -net 0.0.0.0/1 -interface <if>
//! route add -net 128.0.0.0/1 -interface <if>
//! 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>
//! pass out quick on <if> route-to (<egress> <gateway>) inet proto { tcp udp }
//! from any to ! <overlay ranges> user <agent uid>
//! nat on <egress> inet from (<if>) to any -> (<egress>)
@@ -104,6 +104,7 @@ pub(super) fn run_tool(tool: Tool, args: &[String], stdin: Option<&str>) -> Ran
let mut command = Command::new(tool.path());
command
.env("LC_ALL", "C")
.args(args)
.stdin(if stdin.is_some() {
Stdio::piped()
@@ -206,8 +207,8 @@ fn run_ok(
Ran::Exited {
success: true,
stdout,
..
} => Ok(stdout),
stderr,
} if tool != Tool::Route || stderr.is_empty() => Ok(stdout),
Ran::Exited { stderr, stdout, .. } => Err(format!(
"{} {} failed: {}",
tool.path(),
@@ -380,8 +381,17 @@ const HALVES: [&str; 2] = ["0.0.0.0/1", "128.0.0.0/1"];
/// The IPv6 halves, made unreachable.
const HALVES_V6: [&str; 2] = ["::/1", "8000::/1"];
fn route_add_args(half: &str, interface: &str) -> Vec<String> {
owned(&["-q", "-n", "add", "-net", half, "-interface", interface])
fn route_set_args(
action: &str,
half: &str,
interface: &str,
source: Option<Ipv4Addr>,
) -> Vec<String> {
let mut args = owned(&["-q", "-n", action, "-net", half, "-interface", interface]);
if let Some(source) = source {
args.extend(["-ifa".into(), source.to_string()]);
}
args
}
fn route_del_args(half: &str, interface: &str) -> Vec<String> {
@@ -407,12 +417,57 @@ fn clear_routes(run: Run<'_>, interface: &str) {
}
}
fn set_routes(run: Run<'_>, interface: &str) -> Result<(), String> {
clear_routes(run, interface);
/// Installs a split default, or changes its source in place when the route
/// already belongs to this utun. Returns whether this call added it.
fn set_half(
run: Run<'_>,
half: &str,
interface: &str,
source: Option<Ipv4Addr>,
) -> Result<bool, String> {
match run_ok(
run,
Tool::Route,
&route_set_args("add", half, interface, source),
None,
) {
Ok(_) => Ok(true),
Err(why) if why.contains("File exists") => {
let lookup = run_ok(run, Tool::Route, &owned(&["-n", "get", "-net", half]), None)
.map_err(|inspect| format!("{why}; {inspect}"))?;
let field = |key: &str| {
lookup
.lines()
.filter_map(|line| line.trim().split_once(':'))
.find_map(|(name, value)| (name == key).then(|| value.trim()))
};
if field("mask") != Some("128.0.0.0") || field("interface") != Some(interface) {
return Err(why);
}
run_ok(
run,
Tool::Route,
&route_set_args("change", half, interface, source),
None,
)?;
Ok(false)
}
Err(why) => Err(why),
}
}
fn set_routes(run: Run<'_>, interface: &str, source: Option<Ipv4Addr>) -> Result<(), String> {
let mut added = Vec::new();
for half in HALVES {
if let Err(why) = run_ok(run, Tool::Route, &route_add_args(half, interface), None) {
clear_routes(run, interface);
return Err(why);
match set_half(run, half, interface, source) {
Ok(true) => added.push(half),
Ok(false) => {}
Err(why) => {
for half in added {
let _ = run(Tool::Route, &route_del_args(half, interface), None);
}
return Err(why);
}
}
}
for half in HALVES_V6 {
@@ -490,7 +545,7 @@ fn apply_rules(
// The routes come after the rules that keep the agent's own traffic off
// them: the other order would loop for as long as it takes.
if plan.client {
set_routes(run, interface)?;
set_routes(run, interface, plan.client_source)?;
} else {
clear_routes(run, interface);
}
@@ -545,6 +600,7 @@ destination: default\n\
pf_missing: bool,
pf_load_fails: bool,
route_add_fails: bool,
half_interface: Option<&'static str>,
pf_enable_output: &'static str,
}
@@ -558,6 +614,7 @@ destination: default\n\
pf_missing: false,
pf_load_fails: false,
route_add_fails: false,
half_interface: None,
pf_enable_output: "pf enabled\nToken : 4242\n",
}
}
@@ -581,14 +638,29 @@ destination: default\n\
match tool {
Tool::Id => ok("0\n", ""),
Tool::Sysctl => ok(self.forwarding, ""),
Tool::Route
if args.iter().any(|arg| arg == "get")
&& args.iter().any(|arg| arg == "-net") =>
{
match self.half_interface {
Some(name) => ok(&format!("mask: 128.0.0.0\ninterface: {name}\n"), ""),
None => fail("not in table"),
}
}
Tool::Route if args.first().map(String::as_str) == Some("-n") => {
match &self.default_route {
Some(text) => ok(text, ""),
None => fail("route: writing to routing socket: not in table"),
}
}
Tool::Route if args.contains(&"add".to_string()) && self.route_add_fails => {
fail("route: writing to routing socket: File exists")
Tool::Route
if args.contains(&"add".to_string())
&& ((self.route_add_fails && args.iter().any(|a| a == HALVES[1]))
|| (self.half_interface.is_some()
&& HALVES.iter().any(|half| args.iter().any(|a| a == half)))) =>
{
// Darwin route can return success after a routing-socket write failed.
ok("", "route: writing to routing socket: File exists")
}
Tool::Route => ok("", ""),
Tool::Pfctl if self.pf_missing => Ran::Missing,
@@ -718,7 +790,7 @@ destination: default\n\
#[test]
fn the_overlay_default_routes_are_halves_and_ipv6_is_rejected() {
assert_eq!(
route_add_args("0.0.0.0/1", "utun5").join(" "),
route_set_args("add", "0.0.0.0/1", "utun5", None).join(" "),
"-q -n add -net 0.0.0.0/1 -interface utun5"
);
assert_eq!(
@@ -805,6 +877,55 @@ destination: default\n\
assert!(fake.position("-n get default").unwrap() < add);
}
#[test]
fn both_exit_halves_use_the_selected_networks_address_on_a_shared_utun() {
let fake = Fake::new();
let token = Mutex::new(None);
let mut selected = plan(false, true);
selected.overlay.push("10.99.0.0/24".parse().unwrap());
for source in ["10.99.0.17", "10.13.37.34"] {
selected.client_source = Some(source.parse().unwrap());
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &selected);
assert_eq!(report.client, Some(RuleOutcome::Applied));
for half in HALVES {
assert!(
fake.position(&format!("add -net {half} -interface utun5 -ifa {source}"))
.is_some()
);
}
}
}
#[test]
fn changing_the_active_exit_keeps_both_halves_routed_through_its_utun() {
let mut selected = plan(false, true);
selected.client_source = Some("10.99.0.17".parse().unwrap());
let mut fake = Fake::new();
fake.half_interface = Some("utun5");
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &Mutex::new(None), &selected);
assert_eq!(report.client, Some(RuleOutcome::Applied));
for half in HALVES {
assert!(
fake.position(&format!(
"change -net {half} -interface utun5 -ifa 10.99.0.17"
))
.is_some()
);
}
assert_eq!(fake.count(" delete "), 0);
let mut foreign = Fake::new();
foreign.half_interface = Some("utun9");
let report = apply_plan(
&|t, a, s| foreign.run(t, a, s),
&Mutex::new(None),
&selected,
);
assert!(matches!(report.client, Some(RuleOutcome::Failed(_))));
assert_eq!(foreign.count(" change "), 0);
assert_eq!(foreign.count(" delete "), 0);
}
#[test]
fn no_routes_are_added_when_the_rules_did_not_load() {
let mut fake = Fake::new();
@@ -141,13 +141,18 @@ fn bypass_script(index: u32, gateway: Ipv4Addr, addresses: &[Ipv4Addr]) -> Strin
.collect();
format!(
"$ErrorActionPreference = 'Stop'\n\
$keep = @(@({}) | ForEach-Object {{ \"$_/32\" }})\n\
foreach ($p in $keep) {{\n\
if (-not (Get-NetRoute -DestinationPrefix $p -InterfaceIndex {index} -NextHop '{gateway}' \
-PolicyStore ActiveStore -ErrorAction SilentlyContinue)) {{\n\
New-NetRoute -DestinationPrefix $p -InterfaceIndex {index} -NextHop '{gateway}' \
-RouteMetric {BYPASS_METRIC} -PolicyStore ActiveStore | Out-Null\n\
}}\n\
}}\n\
Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore -ErrorAction SilentlyContinue | \
Where-Object {{ $_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32') }} | \
Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n\
foreach ($ip in @({})) {{\n\
New-NetRoute -DestinationPrefix \"$ip/32\" -InterfaceIndex {index} -NextHop '{gateway}' \
-RouteMetric {BYPASS_METRIC} -PolicyStore ActiveStore -ErrorAction SilentlyContinue | Out-Null\n\
}}\n",
Where-Object {{ $_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32') -and \
($keep -notcontains $_.DestinationPrefix -or $_.InterfaceIndex -ne {index} -or $_.NextHop -ne '{gateway}') }} | \
Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n",
list.join(", ")
)
}
@@ -159,14 +164,14 @@ fn halves_script(interface: &str) -> String {
"$ErrorActionPreference = 'Stop'\n\
$alias = {alias}\n\
foreach ($p in '0.0.0.0/1', '128.0.0.0/1') {{\n\
Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -PolicyStore ActiveStore \
-ErrorAction SilentlyContinue | Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n\
if (Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '0.0.0.0' \
-PolicyStore ActiveStore -ErrorAction SilentlyContinue) {{ continue }}\n\
New-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '0.0.0.0' \
-RouteMetric 1 -PolicyStore ActiveStore | Out-Null\n\
}}\n\
foreach ($p in '::/1', '8000::/1') {{\n\
Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -PolicyStore ActiveStore \
-ErrorAction SilentlyContinue | Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n\
if (Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '::' \
-PolicyStore ActiveStore -ErrorAction SilentlyContinue) {{ continue }}\n\
New-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '::' \
-RouteMetric 1 -PolicyStore ActiveStore -ErrorAction SilentlyContinue | Out-Null\n\
}}\n"
@@ -197,13 +202,21 @@ fn bypass_addresses(
resolve: Resolve<'_>,
addresses: &[Ipv4Addr],
hosts: &[String],
overlay: &[Ipv4Range],
) -> Vec<Ipv4Addr> {
let mut all: std::collections::BTreeSet<Ipv4Addr> = addresses.iter().copied().collect();
for host in hosts {
all.extend(resolve(host));
}
all.into_iter()
.filter(|a| !a.is_loopback() && !a.is_unspecified() && !a.is_multicast())
.filter(|a| {
!a.is_loopback()
&& !a.is_unspecified()
&& !a.is_multicast()
&& !a.is_link_local()
&& !a.is_broadcast()
&& !overlay.iter().any(|range| range.contains(*a))
})
.collect()
}
@@ -216,7 +229,7 @@ fn apply_client(
let gateway = run(&gateway_script(interface))?;
let (index, hop) = parse_gateway(&gateway)
.ok_or_else(|| format!("cannot read the default gateway from `{}`", gateway.trim()))?;
let addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts);
let addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts, &plan.overlay);
run(&bypass_script(index, hop, &addresses))?;
if let Err(why) = run(&halves_script(interface)) {
// Do not leave a half-installed set: bypass routes alone are harmless
@@ -437,8 +450,10 @@ mod tests {
assert!(script.contains("-InterfaceIndex 12 -NextHop '192.168.1.1'"));
assert!(script.contains("-RouteMetric 7373"));
assert!(script.contains("-PolicyStore ActiveStore"));
// Stale marked routes go first, and only /32 ones with our metric.
assert!(script.find("Remove-NetRoute").unwrap() < script.find("New-NetRoute").unwrap());
// Install missing routes before pruning stale entries. Existing paths
// continue carrying the tunnel throughout another network's update.
assert!(script.find("New-NetRoute").unwrap() < script.find("Remove-NetRoute").unwrap());
assert!(script.contains("$keep -notcontains $_.DestinationPrefix"));
assert!(script.contains("RouteMetric -eq 7373"));
assert!(script.contains("EndsWith('/32')"));
}
@@ -446,6 +461,10 @@ mod tests {
#[test]
fn the_halves_go_through_the_overlay_and_ipv6_is_blackholed() {
let script = halves_script("tsun0");
assert!(
!script.contains("Remove-NetRoute"),
"reapplying must keep existing split defaults: {script}"
);
assert!(script.contains("'0.0.0.0/1', '128.0.0.0/1'"));
assert!(script.contains("-InterfaceAlias $alias -NextHop '0.0.0.0'"));
assert!(script.contains("'::/1', '8000::/1'"));
@@ -473,6 +492,7 @@ mod tests {
Ipv4Addr::UNSPECIFIED,
],
&["relay.example".into(), "gone.example".into()],
&[],
);
assert_eq!(
all,
@@ -505,12 +525,36 @@ mod tests {
);
}
#[test]
fn relay_dns_cannot_install_a_host_route_over_either_overlay() {
let mut plan = client_plan();
plan.overlay.push("10.99.0.0/24".parse().unwrap());
let resolve = |_: &str| {
["10.13.37.4", "10.99.0.6", "9.9.9.9"]
.map(|ip| ip.parse().unwrap())
.to_vec()
};
let calls = RefCell::new(Vec::new());
let run = |script: &str| {
calls.borrow_mut().push(script.to_string());
Ok("12 192.168.1.1".to_string())
};
apply_client(&run, &resolve, &plan).unwrap();
let calls = calls.borrow();
let bypass = calls
.iter()
.find(|c| c.contains("-RouteMetric 7373"))
.unwrap();
assert!(bypass.contains("'9.9.9.9'") && bypass.contains("'138.201.61.182'"));
assert!(!bypass.contains("'10.13.37.4'") && !bypass.contains("'10.99.0.6'"));
}
#[test]
fn nothing_goes_through_the_overlay_when_the_bypass_cannot_be_written() {
let run = |script: &str| -> Result<String, String> {
if script.contains("Select-Object -First 1") {
Ok("12 192.168.1.1".to_string())
} else if script.contains("-RouteMetric 7373") && script.contains("foreach ($ip") {
} else if script.contains("-RouteMetric 7373") && script.contains("New-NetRoute") {
Err("Access is denied".to_string())
} else {
assert!(!script.contains("-NextHop '0.0.0.0'"), "{script}");
+82 -18
View File
@@ -35,7 +35,7 @@ use super::hostrules::{
RuleOutcome, offer_detail,
};
use super::packet::IpHeader;
use super::router::{Route, RoutingTable};
use super::router::{PacketSource, Route, RoutingTable};
use super::tun::{TunDevice, TunFactory, TunRequest};
use super::{Cidr, OverlayError};
@@ -428,6 +428,9 @@ impl Interface {
ranges.sort_by_key(|range| (range.base, range.prefix_len));
ranges.dedup();
let (client, client_source) = self.routes.exit_client();
#[cfg(windows)]
self.device
.set_exit_source(&self.wanted_addresses(), client_source);
let overlay = self.routes.overlay_ranges();
let (bypass, bypass_hosts) = if client && exit.needs_bypass() {
self.underlay_targets(&overlay)
@@ -521,6 +524,14 @@ impl Interface {
state.report = Some(report);
}
/// Whether the host routes its own transport by destination.
pub(crate) fn needs_underlay_targets(&self) -> bool {
self.host_rules
.as_ref()
.and_then(|rules| rules.exit_rules())
.is_some_and(|exit| exit.needs_bypass())
}
/// Tells the interface where a network's runtime reaches peers and
/// relays outside the overlay. When the host needs those kept out of the
/// exit node's default route and the set changed, the rules follow.
@@ -545,13 +556,7 @@ impl Interface {
map.insert(network, new.clone()) != Some(new)
}
};
let needed = changed
&& self.routes.exit_via().is_some()
&& self
.host_rules
.as_ref()
.and_then(|rules| rules.exit_rules())
.is_some_and(|exit| exit.needs_bypass());
let needed = changed && self.routes.exit_via().is_some() && self.needs_underlay_targets();
if needed {
self.sync_exit_rules().await;
}
@@ -831,12 +836,19 @@ impl Interface {
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::WrongFamily);
};
if !self.routes.may_send_from(network, peer, source) {
let Some(origin) = self.routes.packet_source(network, peer, source) else {
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::WrongSource);
}
let broadcast = match header.destination() {
IpAddr::V4(destination) if self.routes.is_broadcast(destination) => {
};
let broadcast = match (origin, header.destination()) {
(PacketSource::ExitReply { local: Some(local) }, IpAddr::V4(destination))
if destination == local =>
{
false
}
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_broadcast(destination) =>
{
if !super::broadcast::valid_udp(&packet)
|| !self.routes.accepts_broadcast(network, peer, destination)
{
@@ -845,12 +857,10 @@ impl Interface {
}
true
}
IpAddr::V4(destination) if self.routes.is_local_destination(network, destination) => {
false
}
// This agent is an exit node of this network: a member's packet
// for the internet goes to the host, which masquerades it.
IpAddr::V4(destination) if self.routes.accepts_exit_traffic(network, destination) => {
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_local_destination(network, destination)
|| self.routes.accepts_exit_traffic(network, destination) =>
{
false
}
_ => {
@@ -1575,6 +1585,47 @@ mod tests {
assert_eq!(interface.counters().received, 1);
}
#[tokio::test]
async fn an_exit_reply_must_terminate_locally_even_while_this_agent_offers_forwarding() {
use super::super::broadcast::BroadcastPolicy;
let (interface, device, routes, _, id) = interface(false).await;
routes.set_exit(
id,
ExitPolicy {
offer: true,
via: Some(peer(2)),
},
);
routes.set_broadcast(
id,
BroadcastPolicy {
enabled: true,
peers: [peer(2)].into_iter().collect(),
},
);
let udp = [0, 1, 0, 2, 0, 8, 0, 0];
for destination in [Ipv4Addr::new(1, 1, 1, 1), Ipv4Addr::BROADCAST] {
assert_eq!(
interface
.deliver(id, peer(2), ipv4(INTERNET, destination, &udp))
.await,
Err(Rejected::WrongDestination)
);
}
assert_eq!(interface.counters().received, 0);
// The same peer can still return internet traffic to us, and can
// originate its own ordinary packets under the network's offer.
for packet in [ipv4(INTERNET, addr(1), &udp), ipv4(addr(2), INTERNET, &udp)] {
interface
.deliver(id, peer(2), packet.clone())
.await
.unwrap();
assert_eq!(device.pop_to_os().await.unwrap(), packet);
}
}
#[tokio::test]
async fn an_exit_node_hands_a_members_internet_packet_to_the_host_only_while_offering() {
let (interface, device, routes, _carrier, id) = interface(false).await;
@@ -1675,6 +1726,19 @@ mod tests {
vec![Ipv4Addr::new(5, 6, 7, 8)]
);
let second = network("second underlay");
let second_path = Ipv4Addr::new(203, 0, 113, 10);
interface.set_underlay(second, [second_path], []).await;
assert_eq!(
rules.exit().installed().unwrap().bypass,
[Ipv4Addr::new(5, 6, 7, 8), second_path]
);
interface.set_underlay(second, [], []).await;
assert_eq!(
rules.exit().installed().unwrap().bypass,
[Ipv4Addr::new(5, 6, 7, 8)]
);
// Not using an exit node: nothing to keep direct.
routes.set_exit(id, Default::default());
interface.sync_exit_rules().await;
+1
View File
@@ -46,6 +46,7 @@ pub mod interface;
pub mod packet;
pub mod provision;
pub mod router;
pub mod source;
pub mod tun;
pub use config::{Cidr, DEFAULT_INTERFACE_PREFIX, MAX_INTERFACE_NAME_LEN, interface_name};
@@ -76,7 +76,9 @@ enum Command {
DelBroadcastRoute(String, Reply<()>),
/// Send the host's default traffic through this interface, except what
/// this user id sends.
SetExitClient(String, u32, Reply<()>),
SetExitClient(String, u32, Option<Ipv4Addr>, Reply<()>),
/// Replace only the default route on an already protected interface.
UpdateExitSource(String, Option<Ipv4Addr>, Reply<()>),
/// Take those routing rules away again.
ClearExitClient(Reply<()>),
/// Stop the thread.
@@ -213,10 +215,25 @@ impl RouteHandle {
/// Sends the host's default traffic through `interface`, except what the
/// user id `uid` sends. Replaces what an earlier call set up.
pub(crate) fn set_exit_client(&self, interface: &str, uid: u32) -> Result<(), OverlayError> {
pub(crate) fn set_exit_client(
&self,
interface: &str,
uid: u32,
source: Option<Ipv4Addr>,
) -> Result<(), OverlayError> {
let interface = interface.to_string();
call_thread(&self.commands, |reply| {
Command::SetExitClient(interface, uid, reply)
Command::SetExitClient(interface, uid, source, reply)
})
}
pub(crate) fn update_exit_source(
&self,
interface: &str,
source: Option<Ipv4Addr>,
) -> Result<(), OverlayError> {
call_thread(&self.commands, |reply| {
Command::UpdateExitSource(interface.to_string(), source, reply)
})
}
@@ -346,7 +363,8 @@ fn netlink_thread(requests: mpsc::Receiver<Command>) {
| Command::Configure(_, reply)
| Command::SetBroadcastRoute(_, _, reply)
| Command::DelBroadcastRoute(_, reply)
| Command::SetExitClient(_, _, reply) => {
| Command::SetExitClient(_, _, _, reply)
| Command::UpdateExitSource(_, _, reply) => {
let _ = reply.send(Err(OverlayError::Unavailable(message)));
}
Command::ClearExitClient(reply) => {
@@ -398,9 +416,19 @@ fn netlink_thread(requests: mpsc::Receiver<Command>) {
});
let _ = reply.send(result);
}
Command::SetExitClient(name, uid, reply) => {
Command::SetExitClient(name, uid, source, reply) => {
let result = NetAdmin::acquire().and_then(|guard| {
let result = runtime.block_on(set_exit_client(&name, uid));
let result = runtime.block_on(set_exit_client(&name, uid, source));
drop(guard);
result
});
let _ = reply.send(result);
}
Command::UpdateExitSource(name, source, reply) => {
let result = NetAdmin::acquire().and_then(|guard| {
let result = runtime.block_on(with_netlink(|handle| async move {
replace_exit_default(&handle, &name, source).await
}));
drop(guard);
result
});
@@ -704,13 +732,19 @@ fn is_exit_rule(rule: &RuleMessage) -> bool {
}
}
fn exit_default_route(index: Option<u32>) -> rtnetlink::packet_route::route::RouteMessage {
fn exit_default_route(
index: Option<u32>,
source: Option<Ipv4Addr>,
) -> rtnetlink::packet_route::route::RouteMessage {
let mut builder = RouteMessageBuilder::<Ipv4Addr>::new()
.destination_prefix(Ipv4Addr::UNSPECIFIED, 0)
.table_id(EXIT_TABLE);
if let Some(index) = index {
builder = builder.output_interface(index).scope(RouteScope::Link);
}
if let Some(source) = source {
builder = builder.pref_source(source);
}
builder.build()
}
@@ -772,7 +806,12 @@ async fn remove_exit_rules(
async fn remove_exit_client(handle: &rtnetlink::Handle) -> Result<(), OverlayError> {
remove_exit_rules(handle, IpVersion::V4).await?;
match handle.route().del(exit_default_route(None)).execute().await {
match handle
.route()
.del(exit_default_route(None, None))
.execute()
.await
{
Ok(()) => {}
// "No such process": no such route, which is the goal.
Err(err) if err.to_string().contains("No such") => {}
@@ -797,10 +836,32 @@ async fn remove_exit_client(handle: &rtnetlink::Handle) -> Result<(), OverlayErr
}
}
/// Replace the default route atomically when the selected overlay address changes.
async fn replace_exit_default(
handle: &rtnetlink::Handle,
name: &str,
source: Option<Ipv4Addr>,
) -> Result<(), OverlayError> {
let index = link_index(handle, name).await.ok_or_else(|| {
OverlayError::Unavailable(format!(
"interface `{name}` disappeared before the exit node route could be added"
))
})?;
handle
.route()
.add(exit_default_route(Some(index), source))
.replace()
.execute()
.await
.map_err(|err| {
OverlayError::Unavailable(format!("cannot set the exit node default route: {err}"))
})
}
/// Sets up the using side of an exit node.
///
/// ```text
/// ip route replace default dev <if> table 0x7473
/// ip route replace default dev <if> src <selected overlay address> table 0x7473
/// ip rule add priority 5205 fwmark 0x40000000/0x40000000 lookup main
/// ip rule add priority 5206 uidrange <uid>-<uid> lookup main
/// ip rule add priority 5290 lookup main suppress_prefixlength 0
@@ -813,24 +874,17 @@ async fn remove_exit_client(handle: &rtnetlink::Handle) -> Result<(), OverlayErr
/// What an earlier call left is removed first, so repeating it is safe, and
/// the rules go in last, so a failure part way never leaves a rule that
/// sends traffic to a table with no route in it.
async fn set_exit_client(name: &str, uid: u32) -> Result<(), OverlayError> {
async fn set_exit_client(
name: &str,
uid: u32,
source: Option<Ipv4Addr>,
) -> Result<(), OverlayError> {
with_netlink(|handle| async move {
let index = link_index(&handle, name).await.ok_or_else(|| {
OverlayError::Unavailable(format!(
"interface `{name}` disappeared before the exit node routes could be added"
))
})?;
remove_exit_client(&handle).await?;
let fail = |what: &str, err: rtnetlink::Error| {
OverlayError::Unavailable(format!("cannot add the exit node {what}: {err}"))
};
handle
.route()
.add(exit_default_route(Some(index)))
.replace()
.execute()
.await
.map_err(|err| fail("default route", err))?;
replace_exit_default(&handle, name, source).await?;
add_mark_bypass(&handle, false).await?;
@@ -1190,13 +1244,17 @@ mod tests {
#[test]
fn the_default_route_of_the_exit_table_names_the_table_and_the_interface() {
let route = exit_default_route(Some(7));
let source = Ipv4Addr::new(10, 99, 0, 1);
let route = exit_default_route(Some(7), Some(source));
assert_eq!(route.header.destination_prefix_length, 0);
let debug = format!("{route:?}");
assert!(debug.contains(&format!("Table({EXIT_TABLE})")), "{debug}");
assert!(debug.contains("Oif(7)"), "{debug}");
assert!(route.attributes.contains(
&rtnetlink::packet_route::route::RouteAttribute::PrefSource(source.into())
));
// Deleting names no interface, so it matches whatever it was added on.
assert!(!format!("{:?}", exit_default_route(None)).contains("Oif"));
assert!(!format!("{:?}", exit_default_route(None, None)).contains("Oif"));
}
#[test]
+114 -18
View File
@@ -40,6 +40,12 @@ pub struct Route {
pub peer: EndpointId,
}
/// An internet source is valid only for a reply to our address in the exit's network.
pub(super) enum PacketSource {
Member,
ExitReply { local: Option<Ipv4Addr> },
}
/// A network's exit-node settings, as far as packets are concerned.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ExitPolicy {
@@ -120,7 +126,29 @@ impl RoutingTable {
/// interface an address can belong to only one network, and guessing
/// which would send somebody's traffic to a stranger.
pub fn set_network(&self, network: NetworkId, routes: NetworkRoutes) -> Result<(), RouteError> {
self.replace_network(&mut self.write(), network, routes)
}
/// A fresh allocation snapshot cannot change the operator's exit settings.
pub(crate) fn update_allocations(
&self,
network: NetworkId,
mut routes: NetworkRoutes,
) -> Result<(), RouteError> {
let mut networks = self.write();
routes.exit = networks
.get(&network)
.map(|current| current.exit)
.unwrap_or_default();
self.replace_network(&mut networks, network, routes)
}
fn replace_network(
&self,
networks: &mut HashMap<NetworkId, NetworkRoutes>,
network: NetworkId,
routes: NetworkRoutes,
) -> Result<(), RouteError> {
if let Some(range) = routes.range {
for (other, existing) in networks.iter() {
if *other == network {
@@ -139,9 +167,12 @@ impl RoutingTable {
}
}
}
if routes.exit.via.is_some() {
clear_other_exits(networks, network);
}
networks.insert(network, routes);
self.broadcast
.store(Arc::new(BroadcastTable::build(&networks)));
.store(Arc::new(BroadcastTable::build(networks)));
Ok(())
}
@@ -172,8 +203,16 @@ impl RoutingTable {
/// A network that has no entry yet (its range is not agreed) takes them
/// from [`NetworkRoutes::exit`] when it is added.
pub fn set_exit(&self, network: NetworkId, policy: ExitPolicy) {
if let Some(routes) = self.write().get_mut(&network) {
routes.exit = policy;
self.update_exit(network, |current| *current = policy);
}
pub(crate) fn update_exit(&self, network: NetworkId, update: impl FnOnce(&mut ExitPolicy)) {
let mut networks = self.write();
if let Some(routes) = networks.get_mut(&network) {
update(&mut routes.exit);
if routes.exit.via.is_some() {
clear_other_exits(&mut networks, network);
}
}
}
@@ -241,20 +280,30 @@ impl RoutingTable {
/// internet carries the internet's addresses, so from *that* peer any
/// source outside the overlay ranges is accepted.
pub fn may_send_from(&self, network: NetworkId, peer: EndpointId, source: Ipv4Addr) -> bool {
self.packet_source(network, peer, source).is_some()
}
pub(super) fn packet_source(
&self,
network: NetworkId,
peer: EndpointId,
source: Ipv4Addr,
) -> Option<PacketSource> {
let networks = self.read();
let Some(routes) = networks.get(&network) else {
return false;
};
let routes = networks.get(&network)?;
if routes
.peers
.iter()
.any(|(address, holder)| *address == source && *holder == peer)
{
return true;
return Some(PacketSource::Member);
}
routes.exit.via == Some(peer)
(exit_via(&networks) == Some((network, peer))
&& is_internet_destination(source)
&& !in_any_range(&networks, source)
&& !in_any_range(&networks, source))
.then_some(PacketSource::ExitReply {
local: routes.local,
})
}
/// Whether this agent, as an exit node of `network`, takes a member's
@@ -275,8 +324,7 @@ impl RoutingTable {
/// The network and member this device sends its internet traffic through.
///
/// One default route, so one answer; if several networks claim one (they
/// should not) the lowest network id decides, so two runs agree.
/// Choosing another exit replaces the previous one under the table's write lock.
pub fn exit_via(&self) -> Option<(NetworkId, EndpointId)> {
exit_via(&self.read())
}
@@ -423,12 +471,19 @@ fn in_any_range(networks: &HashMap<NetworkId, NetworkRoutes>, address: Ipv4Addr)
.any(|routes| routes.range.is_some_and(|range| range.contains(address)))
}
/// The exit node in use, if any, from the lowest network that names one.
fn clear_other_exits(networks: &mut HashMap<NetworkId, NetworkRoutes>, selected: NetworkId) {
for (id, routes) in networks {
if *id != selected {
routes.exit.via = None;
}
}
}
/// Only the selected network can have an exit peer.
fn exit_via(networks: &HashMap<NetworkId, NetworkRoutes>) -> Option<(NetworkId, EndpointId)> {
networks
.iter()
.filter_map(|(network, routes)| Some((*network, routes.exit.via?)))
.min_by_key(|(network, _)| *network)
.find_map(|(network, routes)| Some((*network, routes.exit.via?)))
}
/// Whether two ranges share any address.
@@ -745,6 +800,46 @@ mod tests {
const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34);
#[test]
fn refreshing_either_networks_addresses_preserves_the_last_exit_choice() {
let table = RoutingTable::new();
let (a, b) = (network("first"), network("second"));
let first = with_exit(true, Some(peer(2)));
let second = NetworkRoutes {
range: Some("10.99.0.0/24".parse().unwrap()),
local: Some(Ipv4Addr::new(10, 99, 0, 1)),
..Default::default()
};
table.set_network(a, first.clone()).unwrap();
table.set_network(b, second.clone()).unwrap();
table.set_exit(
b,
ExitPolicy {
offer: false,
via: Some(peer(3)),
},
);
table.update_allocations(a, first).unwrap();
table.update_allocations(b, second).unwrap();
assert_eq!(
table.exit_client(),
(true, Some(Ipv4Addr::new(10, 99, 0, 1)))
);
assert_eq!(table.exit_via(), Some((b, peer(3))));
assert_eq!(
table.exit_settings(a).unwrap().0,
ExitPolicy {
offer: true,
via: None
}
);
table.remove_network(a);
assert_eq!(table.exit_via(), Some((b, peer(3))));
table.remove_network(b);
assert_eq!(table.exit_via(), None);
}
#[test]
fn without_an_exit_node_the_internet_has_nowhere_to_go() {
let table = RoutingTable::new();
@@ -819,7 +914,7 @@ mod tests {
}
#[test]
fn two_exit_choices_resolve_to_the_lowest_network_id() {
fn competing_exit_choices_use_the_same_peer_for_requests_and_replies() {
let table = RoutingTable::new();
let (a, b) = (network("one"), network("two"));
table
@@ -838,9 +933,10 @@ mod tests {
},
)
.unwrap();
let (chosen, _) = table.exit_via().unwrap();
assert_eq!(chosen, a.min(b));
assert_eq!(table.route(INTERNET).unwrap().network, a.min(b));
assert_eq!(table.exit_via(), Some((b, peer(9))));
assert_eq!(table.route(INTERNET).unwrap().network, b);
assert!(table.may_send_from(b, peer(9), INTERNET));
assert!(!table.may_send_from(a, peer(2), INTERNET));
}
#[test]
+787
View File
@@ -0,0 +1,787 @@
//! Translate host-selected IPv4 aliases at the local packet interface.
use super::Cidr;
use super::packet::{Ipv4Reassembly, fragment_ipv4};
use bytes::Bytes;
use smoltcp::wire::{Ipv4Cidr, Ipv4Packet};
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr};
use std::time::{Duration, Instant};
mod icmp;
#[cfg(any(all(windows, feature = "tun-device"), test))]
pub(crate) mod windows;
// No mappings are persisted, and a new flow cannot evict a live socket.
const MAX_FLOWS: usize = 4096;
const MAX_FRAGMENTED: usize = 16;
const UDP_IDLE: Duration = Duration::from_secs(120);
const TCP_IDLE: Duration = Duration::from_secs(2 * 60 * 60);
const ECHO_IDLE: Duration = Duration::from_secs(30);
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct WireFlow {
local: Ipv4Addr,
remote: Ipv4Addr,
protocol: u8,
local_port: u16,
remote_port: u16,
}
impl WireFlow {
// ICMP errors quote as few as eight transport bytes; the caller validates
// the outer packet separately. Echo requests in opposite directions can
// have the same identifier without sharing a flow.
fn parse(packet: &[u8], outbound: bool) -> Option<Self> {
let h = usize::from(*packet.first()? & 15) * 4;
if packet[0] >> 4 != 4
|| h < 20
|| packet.len() < h + 8
|| u16::from_be_bytes([packet[6], packet[7]]) & 0x1fff != 0
{
return None;
}
let src = Ipv4Addr::from(<[u8; 4]>::try_from(&packet[12..16]).ok()?);
let dst = Ipv4Addr::from(<[u8; 4]>::try_from(&packet[16..20]).ok()?);
let (local, remote) = if outbound { (src, dst) } else { (dst, src) };
let protocol = packet[9];
let data = &packet[h..];
let (local_port, remote_port) = match protocol {
6 | 17 => {
let src = u16::from_be_bytes([data[0], data[1]]);
let dst = u16::from_be_bytes([data[2], data[3]]);
if outbound { (src, dst) } else { (dst, src) }
}
1 if matches!(data[0], 0 | 8) && data[1] == 0 => {
let id = u16::from_be_bytes([data[4], data[5]]);
(id, u16::from(outbound != (data[0] == 8)))
}
_ => return None,
};
Some(Self {
local,
remote,
protocol,
local_port,
remote_port,
})
}
}
#[derive(Clone, Copy)]
struct Binding {
host: Ipv4Addr,
// A response from an unbound UDP listener can leave Android with the
// primary address even though its request targeted a different alias.
remote_initiated: bool,
expires: Instant,
}
/// How the host chooses a source at the TUN boundary.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SourceMode {
/// Android can choose the primary VPN address even for another mesh.
Primary,
/// Windows chooses the matching subnet for mesh traffic, but may select
/// any local alias for a default route.
ExitOnly,
}
#[derive(Debug, PartialEq, Eq)]
struct Domains {
aliases: Vec<Ipv4Cidr>,
exit: Option<Ipv4Addr>,
mode: SourceMode,
}
impl Domains {
fn new(addresses: &[Cidr], exit: Option<Ipv4Addr>, mode: SourceMode) -> Self {
let aliases = addresses
.iter()
.filter_map(|cidr| match cidr.addr {
IpAddr::V4(addr) if cidr.prefix_len <= 32 => {
Some(Ipv4Cidr::new(addr, cidr.prefix_len))
}
_ => None,
})
.collect();
Self {
aliases,
exit,
mode,
}
}
fn primary(&self) -> Option<Ipv4Addr> {
match self.mode {
SourceMode::Primary => self.aliases.first().map(Ipv4Cidr::address),
SourceMode::ExitOnly => None,
}
}
fn has(&self, addr: Ipv4Addr) -> bool {
self.aliases.iter().any(|alias| alias.address() == addr)
}
fn owner(&self, remote: Ipv4Addr) -> Option<Ipv4Addr> {
if remote.is_broadcast()
|| remote.is_multicast()
|| remote.is_unspecified()
|| remote.is_loopback()
|| self.has(remote)
{
return None;
}
if let Some(prefix) = self.aliases.iter().find(|p| p.contains_addr(&remote)) {
return (self.mode == SourceMode::Primary && prefix.broadcast() != Some(remote))
.then(|| prefix.address());
}
self.exit
}
}
/// Bounded flow bindings restore replies to the socket that opened each flow.
pub struct SourceFlows {
domains: Domains,
mtu: u32,
flows: HashMap<Ipv4Addr, HashMap<WireFlow, Binding>>,
primary_has_translations: bool,
last_sweep: Instant,
outgoing_parts: HashMap<Ipv4Addr, Ipv4Reassembly>,
incoming_parts: HashMap<Ipv4Addr, Ipv4Reassembly>,
}
impl SourceFlows {
/// Addresses are in the same order as on the device, primary first where applicable.
pub fn new(addresses: &[Cidr], exit: Option<Ipv4Addr>, mtu: u32, mode: SourceMode) -> Self {
Self {
domains: Domains::new(addresses, exit, mode),
mtu,
flows: HashMap::new(),
primary_has_translations: false,
last_sweep: Instant::now(),
outgoing_parts: HashMap::new(),
incoming_parts: HashMap::new(),
}
}
/// Keep live bindings whose host and wire addresses still belong to the same domains.
pub fn reconfigure(&mut self, addresses: &[Cidr], exit: Option<Ipv4Addr>, mtu: u32) {
self.domains = Domains::new(addresses, exit, self.domains.mode);
self.mtu = mtu;
self.flows.retain(|_, table| {
table.retain(|wire, entry| {
self.domains.has(entry.host) && self.domains.owner(wire.remote) == Some(wire.local)
});
!table.is_empty()
});
self.refresh_primary();
// Outstanding fragments belong to the previous VPN attachment.
self.outgoing_parts.clear();
self.incoming_parts.clear();
}
fn refresh_primary(&mut self) {
if let Some(primary) = self.domains.primary() {
self.primary_has_translations = self
.flows
.get(&primary)
.is_some_and(|table| table.values().any(|entry| entry.host != primary));
if !self.primary_has_translations {
self.flows.remove(&primary);
}
}
}
/// Packets read from the host.
pub fn outbound(&mut self, packet: Bytes) -> Vec<Bytes> {
self.process(packet, true)
}
/// Packets admitted by the mesh and destined for the host.
pub fn inbound(&mut self, packet: Bytes) -> Vec<Bytes> {
self.process(packet, false)
}
fn process(&mut self, packet: Bytes, outbound: bool) -> Vec<Bytes> {
if self.domains.aliases.len() < 2 || packet.first().is_none_or(|byte| byte >> 4 != 4) {
return vec![packet];
}
let Ok(ip) = Ipv4Packet::new_checked(&packet[..]) else {
return vec![];
};
let h = usize::from(ip.header_len());
if h < 20 || usize::from(ip.total_len()) != packet.len() {
return vec![];
}
let (local, remote) = if outbound {
(ip.src_addr(), ip.dst_addr())
} else {
(ip.dst_addr(), ip.src_addr())
};
// ICMP errors can come from a router other than the original peer.
let is_icmp = packet[9] == 1;
let owner = self.domains.owner(remote);
let fragmented = ip.more_frags() || ip.frag_offset() != 0;
if self.domains.mode == SourceMode::ExitOnly {
// A mesh router can report PMTU for an internet flow whose source
// we translated. All other native mesh and forwarded packets pass
// directly, including fragments and packets headed to the gateway.
let exit_error = !outbound
&& Some(local) == self.domains.exit
&& is_icmp
&& (fragmented || matches!(packet.get(h), Some(3 | 11 | 12)));
if !self.domains.has(local) || (owner.is_none() && !exit_error) {
return vec![packet];
}
}
if !ip.verify_checksum() {
return vec![];
}
let primary = self.domains.primary();
// The kernel already uses the primary address for its own subnet. A
// primary change can leave earlier translated sockets draining there.
if Some(local) == primary
&& (!outbound || owner == primary)
&& !self.primary_has_translations
{
return vec![packet];
}
if owner.is_none() && !(is_icmp && self.domains.has(local)) {
return vec![packet];
}
if !self.domains.has(local) {
// Never translate addresses outside the local host's assignments.
return if outbound { vec![] } else { vec![packet] };
}
let now = Instant::now();
if now.duration_since(self.last_sweep) >= Duration::from_secs(5) {
self.flows.retain(|_, table| {
table.retain(|_, entry| now < entry.expires);
!table.is_empty()
});
self.refresh_primary();
self.last_sweep = now;
}
let packet = if fragmented {
let parts = if outbound {
&mut self.outgoing_parts
} else {
&mut self.incoming_parts
};
let key = if outbound {
owner.unwrap_or(local)
} else {
local
};
let Some(packet) = parts
.entry(key)
.or_default()
.accept(packet, MAX_FRAGMENTED, None)
else {
return vec![];
};
packet
} else {
packet
};
let h = usize::from(packet[0] & 15) * 4;
let output = if is_icmp
&& packet
.get(h)
.is_some_and(|kind| matches!(kind, 3 | 11 | 12))
{
icmp::rewrite_error(packet, h, !outbound, |quote, quote_outbound| {
let binding = WireFlow::parse(quote, quote_outbound)
.and_then(|flow| self.domains.owner(flow.remote).map(|alias| (flow, alias)));
let Some((flow, alias)) = binding else {
// The quote passed validation but never required exit translation,
// for example a native socket talking to a peer inside the mesh.
return (self.domains.mode == SourceMode::ExitOnly).then_some((local, local));
};
let wire = WireFlow {
local: alias,
..flow
};
let entry = self
.flows
.get(&wire.local)
.and_then(|table| table.get(&wire))
.filter(|entry| now < entry.expires);
let Some(entry) = entry else {
return (wire.local == flow.local
&& (Some(wire.local) == primary
|| self.domains.mode == SourceMode::ExitOnly))
.then_some((wire.local, wire.local));
};
if quote_outbound {
(flow.local == wire.local).then_some((wire.local, entry.host))
} else {
(flow.local == entry.host).then_some((entry.host, wire.local))
}
})
} else {
self.translate(packet, h, local, remote, outbound, now)
};
match output {
Some(packet) if fragmented => fragment_ipv4(packet, self.mtu),
Some(packet) => vec![packet],
None => vec![],
}
}
fn translate(
&mut self,
packet: Bytes,
h: usize,
local: Ipv4Addr,
remote: Ipv4Addr,
outbound: bool,
now: Instant,
) -> Option<Bytes> {
let Some(alias) = self.domains.owner(remote) else {
return Some(packet);
};
// VIP/exit replies and any other special delivery already admitted by
// core may have a source outside the addressed subnet.
if !outbound && local != alias {
return Some(packet);
}
let Some(flow) = WireFlow::parse(&packet, outbound) else {
return (local == alias).then_some(packet);
};
let data = &packet[h..];
let idle = match flow.protocol {
6 => {
let n = usize::from(*data.get(12)? >> 4) * 4;
if n < 20 || n > data.len() {
return None;
}
if data[13] & 5 != 0 {
UDP_IDLE
} else {
TCP_IDLE
}
}
17 => {
if usize::from(u16::from_be_bytes([data[4], data[5]])) != data.len() {
return None;
}
UDP_IDLE
}
_ => ECHO_IDLE,
};
let wire = WireFlow {
local: alias,
..flow
};
let table = self.flows.entry(alias).or_default();
if table.get(&wire).is_some_and(|entry| entry.expires <= now) {
table.remove(&wire);
}
if !table.contains_key(&wire) {
if Some(alias) == self.domains.primary() && local == alias {
return Some(packet);
}
if table.len() >= MAX_FLOWS {
return None;
}
if outbound
&& local != alias
&& (self
.domains
.primary()
.is_some_and(|primary| primary != local)
|| flow.protocol == 6 && data[13] & 0x12 != 2)
{
return None;
}
}
let entry = table.entry(wire).or_insert(Binding {
host: local,
remote_initiated: !outbound,
expires: now + idle,
});
let target = if outbound {
if local != entry.host {
let wildcard_reply = entry.remote_initiated
&& entry.host == alias
&& flow.protocol == 17
&& self.domains.primary() == Some(local);
if !wildcard_reply {
return None;
}
}
alias
} else {
if entry.host != alias && flow.protocol == 6 && data[13] & 0x12 == 2 {
return None;
}
entry.host
};
entry.expires = now + idle;
if target == local {
return Some(packet);
}
let mut out = packet.to_vec();
let address = if outbound { 12 } else { 16 };
out[address..address + 4].copy_from_slice(&target.octets());
let check = u16::from_be_bytes([out[10], out[11]]);
out[10..12].copy_from_slice(&update_checksum(check, local, target).to_be_bytes());
if matches!(flow.protocol, 6 | 17) {
let off = h + if flow.protocol == 6 { 16 } else { 6 };
let check = u16::from_be_bytes([out[off], out[off + 1]]);
if flow.protocol == 6 || check != 0 {
let new = update_checksum(check, local, target);
let new = if new == 0 && flow.protocol == 17 {
u16::MAX
} else {
new
};
out[off..off + 2].copy_from_slice(&new.to_be_bytes());
}
}
Some(out.into())
}
}
/// RFC 1624 one's-complement adjustment for replacing an IPv4 address.
fn update_checksum(checksum: u16, old: Ipv4Addr, new: Ipv4Addr) -> u16 {
let mut sum = u32::from(!checksum);
for (old, new) in old
.octets()
.as_chunks::<2>()
.0
.iter()
.zip(new.octets().as_chunks::<2>().0)
{
sum += u32::from(!u16::from_be_bytes(*old)) + u32::from(u16::from_be_bytes(*new));
}
while sum >> 16 != 0 {
sum = (sum & 0xffff) + (sum >> 16);
}
!(sum as u16)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
const FIRST: Ipv4Addr = Ipv4Addr::new(10, 1, 0, 1);
const SECOND: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 1);
const PEER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 8);
fn aliases() -> Vec<Cidr> {
vec![
Cidr::new(FIRST.into(), 24).unwrap(),
Cidr::new(SECOND.into(), 24).unwrap(),
]
}
fn udp(src: Ipv4Addr, dst: Ipv4Addr, sport: u16, dport: u16, payload: &[u8]) -> Bytes {
use smoltcp::wire::{IpAddress, Ipv4Packet, UdpPacket};
let mut bytes = vec![0; 28 + payload.len()];
bytes[0] = 0x45;
let size = bytes.len() as u16;
bytes[2..4].copy_from_slice(&size.to_be_bytes());
bytes[8] = 64;
bytes[9] = 17;
bytes[12..16].copy_from_slice(&src.octets());
bytes[16..20].copy_from_slice(&dst.octets());
Ipv4Packet::new_unchecked(&mut bytes[..]).fill_checksum();
let mut udp = UdpPacket::new_unchecked(&mut bytes[20..]);
udp.set_src_port(sport);
udp.set_dst_port(dport);
udp.set_len(size - 20);
udp.payload_mut().copy_from_slice(payload);
udp.fill_checksum(&IpAddress::Ipv4(src), &IpAddress::Ipv4(dst));
bytes.into()
}
#[test]
fn connected_udp_keeps_its_kernel_address_while_the_peer_sees_the_right_alias() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
let request = udp(FIRST, PEER, 4123, 1234, b"request");
assert_eq!(
flows.outbound(request),
vec![udp(SECOND, PEER, 4123, 1234, b"request")]
);
assert_eq!(
flows.inbound(udp(PEER, SECOND, 1234, 4123, b"reply")),
vec![udp(PEER, FIRST, 1234, 4123, b"reply")]
);
assert!(
flows
.outbound(udp(SECOND, PEER, 4123, 1234, b"bound collision"))
.is_empty()
);
assert_eq!(
flows.inbound(udp(PEER, SECOND, 1234, 4124, b"to a listener")),
vec![udp(PEER, SECOND, 1234, 4124, b"to a listener")]
);
assert_eq!(
flows.outbound(udp(FIRST, PEER, 4124, 1234, b"wildcard listener reply")),
vec![udp(SECOND, PEER, 4124, 1234, b"wildcard listener reply")]
);
assert_eq!(
flows.inbound(udp(PEER, SECOND, 1234, 4124, b"again")),
vec![udp(PEER, SECOND, 1234, 4124, b"again")]
);
}
#[test]
fn windows_exit_accepts_any_local_alias_and_restores_external_replies() {
let mut flows = SourceFlows::new(&aliases(), Some(FIRST), 1280, SourceMode::ExitOnly);
let internet = Ipv4Addr::new(203, 0, 113, 2);
let request = udp(SECOND, internet, 4123, 443, b"external");
assert_eq!(
flows.outbound(request),
[udp(FIRST, internet, 4123, 443, b"external")]
);
assert_eq!(
flows.inbound(udp(internet, FIRST, 443, 4123, b"reply")),
[udp(internet, SECOND, 443, 4123, b"reply")]
);
// An explicitly bound socket cannot take replies from this flow.
assert!(
flows
.outbound(udp(FIRST, internet, 4123, 443, b"collision"))
.is_empty()
);
// An address in either overlay, including the gateway itself, stays native.
let mesh = udp(SECOND, PEER, 4123, 443, b"mesh");
assert_eq!(flows.outbound(mesh.clone()), [mesh]);
}
#[tokio::test]
async fn wintun_normalizes_only_external_flows_while_an_exit_is_selected() {
use super::windows::ExitSourceTun;
use crate::overlay::{MemoryTun, TunDevice};
let device = MemoryTun::new("test", 1280);
let tun = ExitSourceTun::new(device.clone());
let internet = Ipv4Addr::new(203, 0, 113, 2);
let request = udp(FIRST, internet, 4000, 80, &[1; 1600]);
let on_wire = udp(SECOND, internet, 4000, 80, &[1; 1600]);
tun.set_exit_source(&aliases(), Some(SECOND));
for part in fragment_ipv4(request.clone(), 1280) {
device.push_from_os(part);
}
for expected in fragment_ipv4(on_wire, 1280) {
assert_eq!(tun.recv().await, Some(expected));
}
// Periodic exit rule refreshes must preserve the original socket.
tun.set_exit_source(&aliases(), Some(SECOND));
tun.send(udp(internet, SECOND, 80, 4000, b"reply"))
.await
.unwrap();
assert_eq!(
device.pop_to_os().await,
Some(udp(internet, FIRST, 80, 4000, b"reply"))
);
let forwarded = udp(PEER, internet, 4000, 80, b"forwarded");
device.push_from_os(forwarded.clone());
assert_eq!(tun.recv().await, Some(forwarded));
tun.set_exit_source(&aliases(), None);
device.push_from_os(request.clone());
assert_eq!(tun.recv().await, Some(request));
}
#[test]
fn proper_bound_flows_and_limited_broadcast_keep_their_identity() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
let native = udp(SECOND, PEER, 3000, 3001, b"bound");
assert_eq!(flows.outbound(native.clone()), vec![native]);
assert!(
flows
.outbound(udp(FIRST, PEER, 3000, 3001, b"collision"))
.is_empty()
);
let reply = udp(PEER, SECOND, 3001, 3000, b"native");
assert_eq!(flows.inbound(reply.clone()), vec![reply]);
let broadcast = udp(FIRST, Ipv4Addr::BROADCAST, 3000, 3001, b"lan");
assert_eq!(flows.outbound(broadcast.clone()), vec![broadcast]);
assert!(
flows
.outbound(udp(PEER, PEER, 3100, 3100, b"forged source"))
.is_empty()
);
}
fn packet(src: Ipv4Addr, dst: Ipv4Addr, protocol: u8, data: &[u8]) -> Bytes {
let mut out = vec![0; 20 + data.len()];
let size = out.len() as u16;
out[0] = 0x45;
out[2..4].copy_from_slice(&size.to_be_bytes());
out[8] = 64;
out[9] = protocol;
out[12..16].copy_from_slice(&src.octets());
out[16..20].copy_from_slice(&dst.octets());
out[20..].copy_from_slice(data);
Ipv4Packet::new_unchecked(&mut out).fill_checksum();
out.into()
}
fn tcp(src: Ipv4Addr, dst: Ipv4Addr, sport: u16, dport: u16, flags: u8) -> Bytes {
use smoltcp::wire::{IpAddress, TcpPacket};
let mut data = [0; 20];
data[..2].copy_from_slice(&sport.to_be_bytes());
data[2..4].copy_from_slice(&dport.to_be_bytes());
data[12] = 0x50;
data[13] = flags;
TcpPacket::new_unchecked(&mut data[..])
.fill_checksum(&IpAddress::Ipv4(src), &IpAddress::Ipv4(dst));
packet(src, dst, 6, &data)
}
#[test]
fn tcp_keeps_direction_and_bindings_survive_unrelated_plans() {
let mut aliases = aliases();
let mut flows = SourceFlows::new(&aliases, None, 1280, SourceMode::Primary);
assert!(flows.outbound(tcp(FIRST, PEER, 333, 443, 16)).is_empty());
assert_eq!(
flows.outbound(tcp(FIRST, PEER, 333, 443, 2)),
[tcp(SECOND, PEER, 333, 443, 2)]
);
flows.reconfigure(&aliases, None, 1280);
assert_eq!(
flows.inbound(tcp(PEER, SECOND, 443, 333, 18)),
[tcp(PEER, FIRST, 443, 333, 18)]
);
// An inbound connection cannot replace a client's active translation.
assert!(flows.inbound(tcp(PEER, SECOND, 443, 333, 2)).is_empty());
let inbound = tcp(PEER, SECOND, 12345, 80, 2);
assert_eq!(flows.inbound(inbound.clone()), [inbound]);
let syn_ack = tcp(SECOND, PEER, 80, 12345, 18);
assert_eq!(flows.outbound(syn_ack.clone()), [syn_ack]);
aliases.remove(0);
flows.reconfigure(&aliases, None, 1280);
assert!(
!flows
.flows
.values()
.any(|table| table.values().any(|e| e.host == FIRST))
);
}
#[test]
fn a_new_primary_drains_earlier_translations_and_passes_its_own_packets() {
let mut aliases = aliases();
let mut flows = SourceFlows::new(&aliases, None, 1280, SourceMode::Primary);
assert_eq!(flows.outbound(udp(FIRST, PEER, 2222, 53, b"q")).len(), 1);
aliases.swap(0, 1);
flows.reconfigure(&aliases, Some(SECOND), 1280);
assert_eq!(
flows.inbound(udp(PEER, SECOND, 53, 2222, b"a")),
[udp(PEER, FIRST, 53, 2222, b"a")]
);
let bound = udp(SECOND, PEER, 4444, 443, b"native");
assert_eq!(flows.outbound(bound.clone()), [bound]);
let native_reply = udp(PEER, SECOND, 443, 4444, b"r");
assert_eq!(flows.inbound(native_reply.clone()), [native_reply]);
assert_eq!(flows.flows[&SECOND].len(), 1);
}
#[test]
fn untracked_primary_errors_and_point_to_point_destinations_are_preserved() {
let mut aliases = aliases();
let mut flows = SourceFlows::new(&aliases, None, 1280, SourceMode::Primary);
let router = Ipv4Addr::new(10, 1, 0, 7);
let mut unreachable = vec![3, 1, 0, 0, 0, 0, 0, 0];
unreachable.extend_from_slice(&udp(FIRST, router, 50_000, 7, b"probe")[..28]);
smoltcp::wire::Icmpv4Packet::new_unchecked(&mut unreachable).fill_checksum();
let error = packet(router, FIRST, 1, &unreachable);
assert_eq!(flows.inbound(error.clone()), [error]);
let directed = udp(FIRST, Ipv4Addr::new(10, 2, 0, 255), 5, 6, b"broadcast");
assert_eq!(flows.outbound(directed.clone()), [directed]);
let point = Ipv4Addr::new(10, 2, 0, 0);
aliases[1] = Cidr::new(point.into(), 31).unwrap();
flows.reconfigure(&aliases, None, 1280);
assert_eq!(
flows.outbound(udp(FIRST, SECOND, 5, 6, b"p2p")),
[udp(point, SECOND, 5, 6, b"p2p")]
);
}
#[test]
fn echo_ids_can_match_in_both_directions() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
let message = |src, dst, kind| {
use smoltcp::wire::Icmpv4Packet;
let mut data = [kind, 0, 0, 0, 0x12, 0x34, 0, 2];
Icmpv4Packet::new_unchecked(&mut data[..]).fill_checksum();
packet(src, dst, 1, &data)
};
assert_eq!(
flows.outbound(message(FIRST, PEER, 8)),
[message(SECOND, PEER, 8)]
);
assert_eq!(
flows.inbound(message(PEER, SECOND, 8)),
[message(PEER, SECOND, 8)]
);
assert_eq!(
flows.outbound(message(SECOND, PEER, 0)),
[message(SECOND, PEER, 0)]
);
assert_eq!(
flows.inbound(message(PEER, SECOND, 0)),
[message(PEER, FIRST, 0)]
);
}
#[test]
fn saturated_network_does_not_take_another_networks_capacity() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
for port in 0..MAX_FLOWS {
assert_eq!(
flows
.outbound(udp(FIRST, PEER, port as u16, 53, b"q"))
.len(),
1
);
}
assert!(
flows
.outbound(udp(FIRST, PEER, 60000, 53, b"full"))
.is_empty()
);
let primary_peer = Ipv4Addr::new(10, 1, 0, 20);
let own = udp(FIRST, primary_peer, 60000, 53, b"first");
assert_eq!(flows.outbound(own.clone()), [own]);
for entry in flows.flows.get_mut(&SECOND).unwrap().values_mut() {
entry.expires = Instant::now();
}
flows.last_sweep -= Duration::from_secs(6);
assert_eq!(
flows.outbound(udp(FIRST, PEER, 60000, 53, b"free")).len(),
1
);
assert_eq!(flows.flows[&SECOND].len(), 1);
}
#[test]
fn fragmented_udp_translates_after_assembly_in_both_directions() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
let mut original = udp(FIRST, PEER, 3333, 4444, &[7; 1900]);
let parts = fragment_ipv4(original.clone(), 1280);
let mut output = Vec::new();
for part in parts.into_iter().rev() {
output.extend(flows.outbound(part));
}
assert_eq!(
output,
fragment_ipv4(udp(SECOND, PEER, 3333, 4444, &[7; 1900]), 1280)
);
original = udp(PEER, SECOND, 4444, 3333, &[8; 1900]);
let mut output = Vec::new();
for part in fragment_ipv4(original, 1280) {
output.extend(flows.inbound(part));
}
assert_eq!(
output,
fragment_ipv4(udp(PEER, FIRST, 4444, 3333, &[8; 1900]), 1280)
);
}
}
@@ -0,0 +1,255 @@
//! Translate errors on existing flows, including truncated RFC 792 quotations.
use super::update_checksum;
use bytes::Bytes;
use smoltcp::wire::{Icmpv4Packet, IpProtocol, Ipv4Packet};
use std::net::Ipv4Addr;
pub(super) fn rewrite_error(
packet: Bytes,
header_len: usize,
inbound: bool,
mut lookup: impl FnMut(&[u8], bool) -> Option<(Ipv4Addr, Ipv4Addr)>,
) -> Option<Bytes> {
let outer = Ipv4Packet::new_checked(&packet[..]).ok()?;
if outer.version() != 4
|| header_len < 20
|| header_len != usize::from(outer.header_len())
|| usize::from(outer.total_len()) != packet.len()
|| outer.next_header() != IpProtocol::Icmp
|| outer.more_frags()
|| outer.frag_offset() != 0
|| !outer.verify_checksum()
{
return None;
}
let icmp = outer.payload();
if !Icmpv4Packet::new_checked(icmp).ok()?.verify_checksum() || !matches!(icmp[0], 3 | 11 | 12) {
return None;
}
let payload = &icmp[8..];
// RFC 4884 records the padded quotation length in words when extensions follow.
let quote = match icmp[5] {
0 => payload,
words => payload.get(..usize::from(words) * 4)?,
};
quote.get(..20)?;
// The original total length may exceed the bytes the router chose to quote.
let inner = Ipv4Packet::new_unchecked(quote);
let inner_header = usize::from(inner.header_len());
let quote_len = quote.len().min(usize::from(inner.total_len()));
if inner.version() != 4
|| inner_header < 20
|| quote_len < inner_header + 8
|| inner.frag_offset() != 0
|| !inner.verify_checksum()
{
return None;
}
let (outer_local, inner_local) = if inbound {
(outer.dst_addr(), inner.src_addr())
} else {
(outer.src_addr(), inner.dst_addr())
};
if outer_local != inner_local {
return None;
}
let (old, new) = lookup(&quote[..quote_len], inbound)?;
if old != inner_local {
return None;
}
if old == new {
return Some(packet);
}
let transport = inner.next_header();
let mut result = packet.to_vec();
let quote_start = header_len + 8;
let mut inner = Ipv4Packet::new_unchecked(&mut result[quote_start..quote_start + quote_len]);
if inbound {
inner.set_src_addr(new);
} else {
inner.set_dst_addr(new);
}
inner.fill_checksum();
let transport_bytes = &mut inner.into_inner()[inner_header..];
// A minimum TCP quote includes ports and sequence number, but not its checksum.
let field = match transport {
IpProtocol::Tcp => transport_bytes.get_mut(16..18),
IpProtocol::Udp => transport_bytes.get_mut(6..8),
_ => None,
};
if let Some(field) = field {
let previous = u16::from_be_bytes([field[0], field[1]]);
if previous != 0 || transport == IpProtocol::Tcp {
let adjusted = update_checksum(previous, old, new);
let value = if adjusted == 0 && transport == IpProtocol::Udp {
u16::MAX
} else {
adjusted
};
field.copy_from_slice(&value.to_be_bytes());
}
}
Icmpv4Packet::new_unchecked(&mut result[header_len..]).fill_checksum();
let mut outer = Ipv4Packet::new_unchecked(&mut result);
if inbound {
outer.set_dst_addr(new);
} else {
outer.set_src_addr(new);
}
outer.fill_checksum();
Some(result.into())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use smoltcp::wire::{TcpPacket, UdpPacket};
const APP: Ipv4Addr = Ipv4Addr::new(10, 1, 0, 1);
const WIRE: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 1);
const PEER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 2);
const ROUTER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 3);
fn ipv4(protocol: u8, src: Ipv4Addr, dst: Ipv4Addr, payload: &[u8]) -> Vec<u8> {
let mut p = vec![0; 20 + payload.len()];
let total = p.len() as u16;
p[0] = 0x45;
p[2..4].copy_from_slice(&total.to_be_bytes());
p[8] = 64;
p[9] = protocol;
p[12..16].copy_from_slice(&src.octets());
p[16..20].copy_from_slice(&dst.octets());
p[20..].copy_from_slice(payload);
Ipv4Packet::new_unchecked(&mut p).fill_checksum();
p
}
fn error(src: Ipv4Addr, dst: Ipv4Addr, quote: &[u8]) -> Bytes {
let mut icmp = vec![3, 4, 0, 0, 0, 0, 5, 0];
icmp.extend_from_slice(quote);
Icmpv4Packet::new_unchecked(&mut icmp).fill_checksum();
ipv4(1, src, dst, &icmp).into()
}
#[test]
fn wintun_keeps_mesh_errors_and_restores_exit_errors_from_a_mesh_router() {
use super::super::{SourceFlows, SourceMode};
use crate::overlay::Cidr;
let external = Ipv4Addr::new(203, 0, 113, 200);
let mut flows = SourceFlows::new(
&[
Cidr::new(APP.into(), 24).unwrap(),
Cidr::new(WIRE.into(), 24).unwrap(),
],
Some(WIRE),
1280,
SourceMode::ExitOnly,
);
let mut udp = [0; 8];
udp[4..6].copy_from_slice(&8u16.to_be_bytes());
let mesh_packet = ipv4(17, WIRE, PEER, &udp);
let mesh_error = error(ROUTER, WIRE, &mesh_packet);
assert_eq!(flows.inbound(mesh_error.clone()), [mesh_error]);
let original = ipv4(17, APP, external, &udp);
let translated = flows.outbound(original.clone().into()).pop().unwrap();
assert_eq!(
flows.inbound(error(ROUTER, WIRE, &translated)),
[error(ROUTER, APP, &original)]
);
}
#[test]
fn inbound_pmtu_restores_a_truncated_udp_quote_and_preserves_the_reporting_router() {
use super::super::{SourceFlows, SourceMode};
use crate::overlay::Cidr;
let mut flows = SourceFlows::new(
&[
Cidr::new(APP.into(), 24).unwrap(),
Cidr::new(WIRE.into(), 24).unwrap(),
],
None,
1280,
SourceMode::Primary,
);
let mut udp = [0x71; 16];
udp[4..6].copy_from_slice(&16u16.to_be_bytes());
UdpPacket::new_unchecked(&mut udp[..]).fill_checksum(&APP.into(), &PEER.into());
let original = ipv4(17, APP, PEER, &udp);
let wire = flows.outbound(original.clone().into()).pop().unwrap();
let p = error(ROUTER, WIRE, &wire[..28]);
let restored = flows.inbound(p).pop().unwrap();
let outer = Ipv4Packet::new_checked(&restored[..]).unwrap();
assert!(outer.verify_checksum());
assert_eq!(outer.src_addr(), ROUTER);
assert_eq!(outer.dst_addr(), APP);
assert!(
Icmpv4Packet::new_checked(outer.payload())
.unwrap()
.verify_checksum()
);
assert_eq!(outer.payload()[6..8], 1280u16.to_be_bytes());
assert_eq!(outer.payload()[8..], original[..28]);
}
#[test]
fn outbound_error_restores_tcp_quotes_with_or_without_a_transport_checksum() {
let mut tcp = [0x41; 48];
tcp[12] = 0x50;
TcpPacket::new_unchecked(&mut tcp[..]).fill_checksum(&PEER.into(), &APP.into());
let original = ipv4(6, PEER, APP, &tcp);
TcpPacket::new_unchecked(&mut tcp[..]).fill_checksum(&PEER.into(), &WIRE.into());
let wire = ipv4(6, PEER, WIRE, &tcp);
for length in [28, original.len()] {
let p = error(APP, PEER, &original[..length]);
let rewritten = rewrite_error(p, 20, false, |_, outbound| {
assert!(!outbound);
Some((APP, WIRE))
})
.unwrap();
assert_eq!(rewritten, error(WIRE, PEER, &wire[..length]));
}
}
#[test]
fn malformed_quotes_unknown_flows_and_unrelated_outer_addresses_are_rejected() {
let original = ipv4(17, WIRE, PEER, &[0; 8]);
let p = error(ROUTER, WIRE, &original);
assert_eq!(
rewrite_error(p.clone(), 20, true, |_, _| Some((WIRE, WIRE))),
Some(p.clone())
);
assert!(rewrite_error(p, 20, true, |_, _| None).is_none());
for invalid in [
error(ROUTER, APP, &original),
error(ROUTER, WIRE, &original[..26]),
{
let mut fragment = original.clone();
fragment[7] = 1;
Ipv4Packet::new_unchecked(&mut fragment).fill_checksum();
error(ROUTER, WIRE, &fragment)
},
{
let mut damaged = error(ROUTER, WIRE, &original).to_vec();
damaged[22] ^= 1;
damaged.into()
},
] {
assert!(
rewrite_error(invalid, 20, true, |_, _| panic!(
"invalid quote reached lookup"
))
.is_none()
);
}
// IPv4 UDP allows a zero checksum; translation may not enable it.
let restored = rewrite_error(error(ROUTER, WIRE, &original), 20, true, |_, _| {
Some((WIRE, APP))
})
.unwrap();
assert_eq!(restored[54..56], [0, 0]);
}
}
@@ -0,0 +1,102 @@
//! Wintun default routes cannot specify a preferred IPv4 source address.
use super::{Domains, SourceFlows, SourceMode};
use crate::BoxFuture;
use crate::overlay::{Cidr, OverlayError, TunDevice};
use bytes::Bytes;
use std::net::Ipv4Addr;
use std::sync::{Arc, Mutex, MutexGuard};
pub(crate) struct ExitSourceTun {
device: Arc<dyn TunDevice>,
state: Mutex<Option<State>>,
}
struct State {
flows: SourceFlows,
pending: std::vec::IntoIter<Bytes>,
}
impl std::fmt::Debug for ExitSourceTun {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ExitSourceTun").field(&self.device).finish()
}
}
impl ExitSourceTun {
pub(crate) fn new(device: Arc<dyn TunDevice>) -> Self {
Self {
device,
state: Mutex::default(),
}
}
fn state(&self) -> MutexGuard<'_, Option<State>> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
}
impl TunDevice for ExitSourceTun {
fn name(&self) -> &str {
self.device.name()
}
fn mtu(&self) -> u32 {
self.device.mtu()
}
fn set_exit_source(&self, addresses: &[Cidr], source: Option<Ipv4Addr>) {
let mut active = self.state();
let domains = Domains::new(addresses, source, SourceMode::ExitOnly);
if domains.aliases.len() < 2 || !source.is_some_and(|addr| domains.has(addr)) {
*active = None;
return;
}
if let Some(state) = active.as_mut() {
if state.flows.domains != domains {
state.flows.reconfigure(addresses, source, self.mtu());
state.pending = Vec::new().into_iter();
}
} else {
*active = Some(State {
flows: SourceFlows::new(addresses, source, self.mtu(), SourceMode::ExitOnly),
pending: Vec::new().into_iter(),
});
}
}
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
Box::pin(async {
if let Some(part) = self.state().as_mut().and_then(|s| s.pending.next()) {
return Some(part);
}
loop {
let packet = self.device.recv().await?;
let mut active = self.state();
let Some(state) = active.as_mut() else {
return Some(packet);
};
state.pending = state.flows.outbound(packet).into_iter();
if let Some(part) = state.pending.next() {
return Some(part);
}
}
})
}
fn send(&self, packet: Bytes) -> BoxFuture<'_, Result<(), OverlayError>> {
Box::pin(async move {
let parts = self
.state()
.as_mut()
.map(|s| s.flows.inbound(packet.clone()));
if let Some(parts) = parts {
for part in parts {
self.device.send(part).await?;
}
Ok(())
} else {
self.device.send(packet).await
}
})
}
}
+10 -2
View File
@@ -66,6 +66,10 @@ pub trait TunDevice: Send + Sync + std::fmt::Debug + 'static {
/// The interface MTU.
fn mtu(&self) -> u32;
/// Supply the local Wintun address and exit selection used for off-mesh flows.
#[cfg(any(windows, test))]
fn set_exit_source(&self, _addresses: &[super::Cidr], _source: Option<std::net::Ipv4Addr>) {}
/// The next packet the operating system wants to send, or `None` once the
/// device is gone.
fn recv(&self) -> BoxFuture<'_, Option<Bytes>>;
@@ -476,12 +480,16 @@ mod system {
let name = request.name.clone();
let (reader, writer) = tokio::io::split(device);
Ok(Arc::new(SystemTun {
let device: Arc<dyn TunDevice> = Arc::new(SystemTun {
name,
mtu: request.mtu,
reader: Mutex::new(reader),
writer: Mutex::new(writer),
}) as Arc<dyn TunDevice>)
});
#[cfg(windows)]
let device: Arc<dyn TunDevice> =
Arc::new(crate::overlay::source::windows::ExitSourceTun::new(device));
Ok(device)
}
fn open_error(name: &str, error: tun::Error) -> OverlayError {