From e7de9b44af554c5b655790fc657685b50c724008 Mon Sep 17 00:00:00 2001 From: Aleksandr Bogomiakov Date: Wed, 25 Nov 2026 19:34:27 +0200 Subject: [PATCH] =?UTF-8?q?Keep=20forwarded=20exit=20traffic=20on=20the=20?= =?UTF-8?q?gateway=E2=80=99s=20own=20uplink?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When A selects B and B selects C, B’s own default route must not carry A’s forwarded packets on to C. Accept only locally sourced overlay traffic for the client default, while keeping authenticated member traffic on the physical uplink from its first packet. Replies still route to the owning member. Switching B’s default does not tear down A’s existing flows. On Linux, distinguish forwarded packets and SNAT replies from local traffic, including strict reverse-path checks when the agent runs as root. On macOS, tag packets on the offered utun and keep their PF NAT state on the physical interface. On Windows, use interface-bound sockets and a bounded smoltcp TCP endpoint, UDP flow mappings and ICMP echo. An offer and its live sockets survive changes to the client's split routes and transient uplink discovery failures. Remove only owned legacy WinNAT objects. Document the supported IPv4 protocols and resource limits. Real WireGuard agents exercised A, B and C. Two Linux ARM64 namespace tests passed in an isolated Colima container with strict reverse-path filtering. The same destination saw A keep its physical SNAT TCP session while B's local connections switched to C and back. Strict Linux core Clippy passed. Six portable socket regressions passed on macOS, including TCP resets, both half-close orders, UDP port stability and resource limits. The macOS PF rules passed native syntax checking and the Windows target cross-compiled on macOS. Extended privileged macOS and Windows fixtures are available in CI; neither native system routing test ran on this host. --- .github/workflows/subnet-source.yml | 25 + Cargo.lock | 1 + crates/tsunagi-core/Cargo.toml | 5 + crates/tsunagi-core/src/config.rs | 10 + crates/tsunagi-core/src/overlay/egress.rs | 353 +++++++++++++ crates/tsunagi-core/src/overlay/egress/tcp.rs | 153 ++++++ .../tsunagi-core/src/overlay/egress/tests.rs | 473 ++++++++++++++++++ .../src/overlay/egress/windows.rs | 32 ++ .../src/overlay/hostrules/exit.rs | 9 + .../src/overlay/hostrules/linux_exit.rs | 92 +++- .../overlay/hostrules/linux_exit_kernel.rs | 211 ++++++++ .../src/overlay/hostrules/linux_exit_mark.rs | 70 ++- .../src/overlay/hostrules/macos_exit.rs | 38 +- .../overlay/hostrules/macos_exit_kernel.rs | 57 ++- .../src/overlay/hostrules/windows.rs | 55 +- .../src/overlay/hostrules/windows_exit.rs | 264 ++++------ crates/tsunagi-core/src/overlay/interface.rs | 89 +++- crates/tsunagi-core/src/overlay/mod.rs | 2 + .../src/overlay/provision/linux.rs | 58 ++- crates/tsunagi-core/src/overlay/router.rs | 11 +- crates/tsunagi-wg-quic/tests/exit_node.rs | 59 +++ docs/exit-node.md | 36 +- docs/testing.md | 10 + 23 files changed, 1884 insertions(+), 229 deletions(-) create mode 100644 crates/tsunagi-core/src/overlay/egress.rs create mode 100644 crates/tsunagi-core/src/overlay/egress/tcp.rs create mode 100644 crates/tsunagi-core/src/overlay/egress/tests.rs create mode 100644 crates/tsunagi-core/src/overlay/egress/windows.rs diff --git a/.github/workflows/subnet-source.yml b/.github/workflows/subnet-source.yml index b46741b..8b770f3 100644 --- a/.github/workflows/subnet-source.yml +++ b/.github/workflows/subnet-source.yml @@ -5,6 +5,12 @@ on: branches: [master] paths: - '.github/workflows/subnet-source.yml' + - 'crates/tsunagi-core/src/overlay/egress.rs' + - 'crates/tsunagi-core/src/overlay/egress/**' + - 'crates/tsunagi-core/src/overlay/interface.rs' + - 'crates/tsunagi-core/src/overlay/router.rs' + - 'crates/tsunagi-core/src/overlay/hostrules/linux_exit*.rs' + - 'crates/tsunagi-core/src/overlay/provision/linux.rs' - 'crates/tsunagi-core/src/overlay/hostrules/macos*.rs' - 'crates/tsunagi-core/src/overlay/hostrules/windows*.rs' - 'crates/tsunagi-core/src/overlay/provision/macos.rs' @@ -27,6 +33,8 @@ jobs: fail-fast: false matrix: include: + - os: ubuntu-latest + test: overlay::hostrules::linux_exit_kernel::serving_an_established_flow_while_switching_the_local_exit - os: macos-latest test: overlay::provision::macos::tests::unbound_sockets_choose_each_networks_source_on_one_real_utun - os: windows-latest @@ -53,6 +61,10 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } if ($tests -notcontains "$($env:TEST_NAME): test") { throw "Missing ignored test: $env:TEST_NAME" } "TEST_BINARY=$binary" >> $env:GITHUB_ENV + - 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 - name: Verify source selection on a real utun if: runner.os == 'macOS' shell: bash @@ -65,6 +77,9 @@ jobs: 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" + previous=$(sysctl -n net.inet.ip.forwarding) + trap 'sudo -n sysctl -w "net.inet.ip.forwarding=$previous"' EXIT + sudo -n sysctl -w net.inet.ip.forwarding=1 sudo -n -- "$TEST_BINARY" --ignored --exact "$EXIT_TEST" --nocapture - name: Verify source selection on a real Wintun adapter if: runner.os == 'Windows' @@ -81,6 +96,16 @@ jobs: Copy-Item (Join-Path $directory 'wintun/bin/amd64/wintun.dll') (Split-Path -Parent $env:TEST_BINARY) & $env:TEST_BINARY --ignored --exact $env:TEST_NAME --nocapture exit $LASTEXITCODE + - name: Verify forwarded and local traffic to the same destination + if: runner.os == 'Windows' + shell: pwsh + timeout-minutes: 2 + run: | + $test = 'overlay::egress::tests::physical_member_sockets_survive_a_more_specific_wintun_route' + $listing = @(& $env:TEST_BINARY --ignored --exact $test --list) + if ($listing -notcontains "${test}: test") { throw "Missing ignored test $test" } + & $env:TEST_BINARY --ignored --exact $test --nocapture + exit $LASTEXITCODE - name: Verify one Windows exit bypass route through the physical gateway if: runner.os == 'Windows' shell: pwsh diff --git a/Cargo.lock b/Cargo.lock index 4b5147f..6bad4f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6385,6 +6385,7 @@ dependencies = [ "sha2", "simple-dns", "smoltcp", + "socket2", "subtle", "tempfile", "thiserror 2.0.20", diff --git a/crates/tsunagi-core/Cargo.toml b/crates/tsunagi-core/Cargo.toml index ab48311..4ac5071 100644 --- a/crates/tsunagi-core/Cargo.toml +++ b/crates/tsunagi-core/Cargo.toml @@ -99,13 +99,18 @@ futures-util = { version = "0.3", default-features = false, optional = true } # before deciding what to change. Creating an adapter needs the process to be # elevated and `wintun.dll` to be reachable at run time. [target.'cfg(target_os = "windows")'.dependencies] +smoltcp = { version = "0.12", default-features = false, features = ["medium-ip", "socket-tcp"] } +socket2 = { version = "0.6", features = ["all"] } windows-sys = { version = "0.61", features = [ + "Win32_Networking_WinSock", "Win32_Security", "Win32_Security_Authorization", "Win32_Foundation", ] } [dev-dependencies] +smoltcp = { version = "0.12", default-features = false, features = ["medium-ip", "socket-tcp"] } +socket2 = { version = "0.6", features = ["all"] } # Its own tests use the harness it publishes. tsunagi-core = { path = ".", features = ["testing"] } tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "process", "test-util"] } diff --git a/crates/tsunagi-core/src/config.rs b/crates/tsunagi-core/src/config.rs index 3439b5e..3e1c012 100644 --- a/crates/tsunagi-core/src/config.rs +++ b/crates/tsunagi-core/src/config.rs @@ -50,6 +50,16 @@ pub const DATA_REASSEMBLY_TTL: Duration = Duration::from_secs(5); /// Completed or discarded packet IDs retained to ignore late duplicate fragments. pub const DATA_RECENT_IDS: usize = 128; +/// Simultaneous TCP, UDP and ICMP work on a userspace exit. +#[cfg(any(windows, test))] +pub(crate) const EXIT_FORWARD_FLOWS: usize = 256; +/// Bounded packet queue shared by userspace exit clients. +#[cfg(any(windows, test))] +pub(crate) const EXIT_FORWARD_QUEUE: usize = 64; +/// Concurrent fragmented datagrams accepted by a userspace exit. +#[cfg(any(windows, test))] +pub(crate) const EXIT_FORWARD_FRAGMENTS: usize = 32; + /// Where the two stores live. /// /// The mandatory state and the disposable cache are separate both logically and diff --git a/crates/tsunagi-core/src/overlay/egress.rs b/crates/tsunagi-core/src/overlay/egress.rs new file mode 100644 index 0000000..cf06e1c --- /dev/null +++ b/crates/tsunagi-core/src/overlay/egress.rs @@ -0,0 +1,353 @@ +//! A Windows exit offer terminates its forwarded connections on physical +//! sockets. This keeps them out of the destination-only routes used by local +//! applications. The stack and its sockets live for the offer, independently +//! of this device's upstream selection. +use super::router::Route; +use crate::identity::NetworkId; +use crate::vip::{ + Protocol, + packet::{self, Tuple}, +}; +use bytes::Bytes; +use smoltcp::wire::{IpAddress, TcpPacket, UdpPacket}; +use std::{ + collections::HashMap, + io, + net::{Ipv4Addr, SocketAddr, SocketAddrV4}, + sync::Arc, + time::Duration, +}; +use tokio::{ + net::{TcpSocket, UdpSocket}, + sync::{mpsc, watch}, + task::{JoinHandle, JoinSet}, +}; + +mod tcp; +#[cfg(test)] +mod tests; +#[cfg(windows)] +mod windows; + +use crate::config::{EXIT_FORWARD_FLOWS, EXIT_FORWARD_FRAGMENTS, EXIT_FORWARD_QUEUE}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Physical { + pub index: u32, + pub address: Ipv4Addr, +} + +impl Physical { + async fn tcp(self, remote: SocketAddr) -> io::Result { + let socket = TcpSocket::new_v4()?; + #[cfg(windows)] + windows::pin(&socket, self.index)?; + socket.bind((self.address, 0).into())?; + socket.connect(remote).await + } + + fn datagram(self, protocol: socket2::Protocol) -> io::Result { + use socket2::{Domain, Protocol, Socket, Type}; + let ty = if protocol == Protocol::UDP { + Type::DGRAM + } else { + Type::RAW + }; + let socket = Socket::new(Domain::IPV4, ty, Some(protocol))?; + #[cfg(windows)] + windows::pin(&socket, self.index)?; + socket.bind(&SocketAddr::V4(SocketAddrV4::new(self.address, 0)).into())?; + socket.set_nonblocking(true)?; + UdpSocket::from_std(socket.into()) + } +} + +type Reply = Arc; +type Offers = Vec<(NetworkId, Physical)>; + +pub(super) struct Gateway { + input: mpsc::Sender<(Route, Bytes)>, + offers: watch::Sender, + worker: JoinHandle<()>, +} + +impl Gateway { + pub fn new(mtu: u32, reply: impl Fn(Route, Bytes) + Send + Sync + 'static) -> Self { + let (input, packets) = mpsc::channel(EXIT_FORWARD_QUEUE); + let (offers, serving) = watch::channel(Vec::new()); + let worker = tokio::spawn(run(mtu, Arc::new(reply), packets, serving)); + Self { + input, + offers, + worker, + } + } + + pub fn configure(&self, mut offers: Offers) { + offers.sort_by_key(|(network, _)| *network); + self.offers.send_if_modified(|old| { + if *old == offers { + return false; + } + *old = offers; + true + }); + } + + pub fn forward(&self, origin: Route, packet: Bytes) -> bool { + self.offers + .borrow() + .iter() + .any(|(network, _)| *network == origin.network) + && self.input.try_send((origin, packet)).is_ok() + } +} + +impl Drop for Gateway { + fn drop(&mut self) { + self.worker.abort(); + } +} + +type FlowKey = (NetworkId, iroh::EndpointId, Tuple); +struct Flow { + tx: mpsc::Sender, + task: tokio::task::AbortHandle, +} + +async fn run( + mtu: u32, + reply: Reply, + mut incoming: mpsc::Receiver<(Route, Bytes)>, + mut serving: watch::Receiver, +) { + let mut flows: HashMap = HashMap::new(); + let mut jobs = JoinSet::new(); + let mut fragments = packet::Reassembly::default(); + loop { + let (origin, part) = tokio::select! { + biased; + changed = serving.changed() => { + if changed.is_err() { return; } + let offers = serving.borrow_and_update(); + flows.retain(|(network, _, _), flow| { + let keep = offers.iter().any(|(net, _)| net == network); + if !keep { flow.task.abort(); } + keep + }); + // Incomplete datagrams from a withdrawn offer must not survive a rejoin. + fragments = packet::Reassembly::default(); + continue; + } + Some(result) = jobs.join_next_with_id(), if !jobs.is_empty() => { + if let Ok((id, Some(key))) = result + && flows.get(&key).is_some_and(|flow| flow.task.id() == id) { + flows.remove(&key); + } + continue; + } + input = incoming.recv() => match input { Some(input) => input, None => return }, + }; + let Some(physical) = serving + .borrow() + .iter() + .find(|(net, _)| *net == origin.network) + .map(|(_, p)| *p) + else { + continue; + }; + let Some(packet) = + fragments.accept(part, EXIT_FORWARD_FRAGMENTS, Some(*origin.peer.as_bytes())) + else { + continue; + }; + let Some(n) = packet::header(&packet) else { + continue; + }; + if packet[8] <= 1 { + continue; + } + if packet[9] == 1 { + if jobs.len() < EXIT_FORWARD_FLOWS + && packet.get(n) == Some(&8) + && packet.len() >= n + 8 + && packet[n + 1] == 0 + && packet::checksum(&packet[n..]) == 0 + { + let reply = reply.clone(); + let mut offers = serving.clone(); + jobs.spawn(async move { + tokio::select! { + _ = offers.wait_for(|nets| !nets.iter().any(|(net, _)| *net == origin.network)) => {}, + _ = echo(physical, origin, packet, n, &reply, mtu) => {} + } + None + }); + } + continue; + } + let Some(tuple) = packet::tuple(&packet) else { + continue; + }; + let src = IpAddress::Ipv4(tuple.src); + let dst = IpAddress::Ipv4(tuple.dst); + let valid = + match tuple.protocol { + Protocol::Tcp => TcpPacket::new_checked(&packet[n..]) + .is_ok_and(|p| p.verify_checksum(&src, &dst)), + Protocol::Udp => UdpPacket::new_checked(&packet[n..]) + .is_ok_and(|p| p.verify_checksum(&src, &dst)), + }; + if !valid { + continue; + } + let key = (origin.network, origin.peer, tuple); + if let Some(flow) = flows.get(&key) { + let _ = flow.tx.try_send(packet); + continue; + } + if jobs.len() >= EXIT_FORWARD_FLOWS + || (tuple.protocol == Protocol::Tcp && !packet::tcp_syn(&packet)) + { + continue; + } + let (tx, rx) = mpsc::channel(EXIT_FORWARD_QUEUE.min(16)); + let reply = reply.clone(); + let task = jobs.spawn(async move { + match tuple.protocol { + Protocol::Tcp => tcp::serve(physical, origin, tuple, packet, rx, reply, mtu).await, + Protocol::Udp => { + let _ = udp(physical, origin, tuple, packet, rx, reply, mtu).await; + } + } + Some(key) + }); + flows.insert(key, Flow { tx, task }); + } +} + +fn remote(t: Tuple) -> SocketAddr { + SocketAddr::V4(SocketAddrV4::new(t.dst, t.dport)) +} + +fn respond(reply: &Reply, origin: Route, packet: Bytes, mtu: u32) { + for part in packet::fragments(packet, mtu) { + reply(origin, part); + } +} + +async fn udp( + physical: Physical, + origin: Route, + tuple: Tuple, + first: Bytes, + mut incoming: mpsc::Receiver, + reply: Reply, + mtu: u32, +) -> io::Result<()> { + let socket = physical.datagram(socket2::Protocol::UDP)?; + socket.connect(remote(tuple)).await?; + let socket = &socket; + let send = |p: Bytes| async move { + if let Some(n) = packet::header(&p) { + socket.send(&p[n + 8..]).await?; + } + Ok::<_, io::Error>(()) + }; + send(first).await?; + let mut buf = vec![0; 65_507]; + loop { + tokio::select! { + packet = incoming.recv() => match packet { Some(p) => send(p).await?, None => return Ok(()) }, + result = socket.recv(&mut buf) => { + let len = result?; + if let Some(p) = udp_packet(tuple.reverse(), &buf[..len]) { respond(&reply, origin, p, mtu); } + }, + _ = tokio::time::sleep(Duration::from_secs(120)) => return Ok(()), + } + } +} + +fn ip_packet( + source: Ipv4Addr, + destination: Ipv4Addr, + proto: u8, + payload_len: usize, +) -> Option> { + let len = u16::try_from(20usize.checked_add(payload_len)?).ok()?; + let mut bytes = vec![0; usize::from(len)]; + bytes[0] = 0x45; + bytes[2..4].copy_from_slice(&len.to_be_bytes()); + bytes[4..6].copy_from_slice(&rand::random::().to_be_bytes()); + bytes[8] = 64; + bytes[9] = proto; + bytes[12..16].copy_from_slice(&source.octets()); + bytes[16..20].copy_from_slice(&destination.octets()); + let checksum = packet::checksum(&bytes[..20]); + bytes[10..12].copy_from_slice(&checksum.to_be_bytes()); + Some(bytes) +} + +fn udp_packet(tuple: Tuple, body: &[u8]) -> Option { + let mut bytes = ip_packet(tuple.src, tuple.dst, 17, body.len().checked_add(8)?)?; + let mut p = UdpPacket::new_unchecked(&mut bytes[20..]); + p.set_src_port(tuple.sport); + p.set_dst_port(tuple.dport); + p.set_len((body.len() + 8) as u16); + p.payload_mut().copy_from_slice(body); + p.fill_checksum(&tuple.src.into(), &tuple.dst.into()); + Some(bytes.into()) +} + +async fn echo( + physical: Physical, + origin: Route, + packet: Bytes, + n: usize, + reply: &Reply, + mtu: u32, +) -> io::Result<()> { + let Some((source, destination)) = packet::addresses(&packet) else { + return Ok(()); + }; + let socket = physical.datagram(socket2::Protocol::ICMPV4)?; + socket.set_ttl(u32::from(packet[8] - 1))?; + socket.connect((destination, 0)).await?; + // Raw ICMP sockets can observe other echo replies. An independent nonce and + // the original data correlate a reply with this one authenticated request. + let nonce = rand::random::().to_be_bytes(); + let mut request = packet[n..].to_vec(); + request[4..8].copy_from_slice(&nonce); + request[2..4].fill(0); + let checksum = packet::checksum(&request); + request[2..4].copy_from_slice(&checksum.to_be_bytes()); + socket.send(&request).await?; + // Winsock delivers unrelated replies to other raw ICMP sockets too. A longer + // reply must not trigger WSAEMSGSIZE and abort this request. + let mut buf = vec![0; usize::from(u16::MAX)]; + let until = tokio::time::Instant::now() + Duration::from_secs(3); + loop { + let len = tokio::time::timeout_at(until, socket.recv(&mut buf)).await??; + let Some(h) = packet::header(&buf[..len]) else { + continue; + }; + let body = &buf[h..len]; + if buf[9] != 1 + || body.len() != request.len() + || body[0..2] != [0, 0] + || body[4..] != request[4..] + || packet::checksum(body) != 0 + { + continue; + } + if let Some(mut out) = ip_packet(destination, source, 1, body.len()) { + out[20..].copy_from_slice(body); + out[24..28].copy_from_slice(&packet[n + 4..n + 8]); + out[22..24].fill(0); + let checksum = packet::checksum(&out[20..]); + out[22..24].copy_from_slice(&checksum.to_be_bytes()); + respond(reply, origin, out.into(), mtu); + } + return Ok(()); + } +} diff --git a/crates/tsunagi-core/src/overlay/egress/tcp.rs b/crates/tsunagi-core/src/overlay/egress/tcp.rs new file mode 100644 index 0000000..f7a2b1c --- /dev/null +++ b/crates/tsunagi-core/src/overlay/egress/tcp.rs @@ -0,0 +1,153 @@ +//! smoltcp owns the member-facing half of one stream. The OS owns the +//! physical TCP connection. Both directions apply backpressure independently. +use super::*; +use smoltcp::{ + iface::{Config, Interface, SocketSet}, + phy::{self, Device, DeviceCapabilities, Medium}, + socket::tcp::{Socket, SocketBuffer, State}, + time::Instant as NetTime, + wire::{HardwareAddress, IpCidr}, +}; +use std::collections::VecDeque; +use tokio::io::AsyncWriteExt; + +struct Wire { + mtu: usize, + input: Option, + output: VecDeque, +} + +struct Rx(Bytes); +impl phy::RxToken for Rx { + fn consume R>(self, f: F) -> R { + f(&self.0) + } +} + +struct Tx<'a>(&'a mut VecDeque); +impl phy::TxToken for Tx<'_> { + fn consume R>(self, len: usize, f: F) -> R { + let mut bytes = vec![0; len]; + let result = f(&mut bytes); + self.0.push_back(bytes.into()); + result + } +} + +impl Device for Wire { + type RxToken<'a> = Rx; + type TxToken<'a> = Tx<'a>; + fn receive(&mut self, _: NetTime) -> Option<(Rx, Tx<'_>)> { + self.input.take().map(|p| (Rx(p), Tx(&mut self.output))) + } + fn transmit(&mut self, _: NetTime) -> Option> { + (self.output.len() < EXIT_FORWARD_QUEUE).then_some(Tx(&mut self.output)) + } + fn capabilities(&self) -> DeviceCapabilities { + let mut caps = DeviceCapabilities::default(); + caps.medium = Medium::Ip; + caps.max_transmission_unit = self.mtu; + caps + } +} + +pub(super) async fn serve( + physical: Physical, + origin: Route, + flow: Tuple, + syn: Bytes, + mut incoming: mpsc::Receiver, + reply: Reply, + mtu: u32, +) { + let Ok(Ok(mut upstream)) = + tokio::time::timeout(Duration::from_secs(8), physical.tcp(remote(flow))).await + else { + if let Some(reset) = packet::reject(&syn) { + reply(origin, reset); + } + return; + }; + let mut wire = Wire { + mtu: mtu as usize, + input: Some(syn), + output: VecDeque::new(), + }; + let mut config = Config::new(HardwareAddress::Ip); + config.random_seed = rand::random(); + let mut iface = Interface::new(config, &mut wire, NetTime::ZERO); + iface.update_ip_addrs(|ips| { + let _ = ips.push(IpCidr::new(flow.dst.into(), 0)); + }); + let mut sockets = SocketSet::new(Vec::new()); + let buffer = || SocketBuffer::new(vec![0; 64 * 1024]); + let mut tcp = Socket::new(buffer(), buffer()); + tcp.set_timeout(Some(smoltcp::time::Duration::from_secs(120))); + if tcp.listen((flow.dst, flow.dport)).is_err() { + return; + } + let handle = sockets.add(tcp); + let start = std::time::Instant::now(); + let mut remote_fin = false; + let mut local_fin = false; + loop { + let now = NetTime::from_millis(start.elapsed().as_millis() as i64); + iface.poll(now, &mut wire, &mut sockets); + let tcp = sockets.get_mut::(handle); + if tcp.can_recv() { + let write = tcp.recv(|buf| match upstream.try_write(buf) { + Ok(n) => (n, Ok(n > 0)), + Err(e) if e.kind() == io::ErrorKind::WouldBlock => (0, Ok(false)), + Err(e) => (0, Err(e)), + }); + if matches!(write, Ok(Err(_))) { + tcp.abort(); + } + } + if !local_fin + && !tcp.may_recv() + && matches!( + tcp.state(), + State::CloseWait | State::Closing | State::LastAck | State::TimeWait + ) + { + let _ = upstream.shutdown().await; + local_fin = true; + } + if tcp.can_send() && !remote_fin { + match tcp.send(|buf| match upstream.try_read(buf) { + Ok(n) => (n, Ok(Some(n))), + Err(e) if e.kind() == io::ErrorKind::WouldBlock => (0, Ok(None)), + Err(e) => (0, Err(e)), + }) { + Ok(Ok(Some(0))) => { + remote_fin = true; + tcp.close(); + } + Ok(Err(_)) => tcp.abort(), + _ => {} + } + } + iface.poll(now, &mut wire, &mut sockets); + for p in wire.output.drain(..) { + reply(origin, p); + } + let tcp = sockets.get::(handle); + // A reset during the handshake returns smoltcp to Listen. This + // worker owns exactly one physical connection and must never accept + // a second SYN on that connection or retain an idle flow slot. + if matches!(tcp.state(), State::Listen | State::Closed) { + return; + } + let delay = iface + .poll_delay(now, &sockets) + .map(Duration::from) + .unwrap_or(Duration::from_secs(3600)); + tokio::select! { + packet = incoming.recv() => match packet { Some(p) => wire.input = Some(p), None => return }, + ready = upstream.readable(), if !remote_fin && tcp.can_send() => { if ready.is_err() { return; } } + ready = upstream.writable(), if tcp.can_recv() => { if ready.is_err() { return; } } + _ = tokio::time::sleep(delay) => {} + } + } +} diff --git a/crates/tsunagi-core/src/overlay/egress/tests.rs b/crates/tsunagi-core/src/overlay/egress/tests.rs new file mode 100644 index 0000000..a2d3140 --- /dev/null +++ b/crates/tsunagi-core/src/overlay/egress/tests.rs @@ -0,0 +1,473 @@ +//! These run on loopback on every host. The gateway uses the same code as +//! Windows, with a loopback source in place of the pinned physical adapter. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; +use tokio::net::{TcpListener, UdpSocket}; + +fn route() -> Route { + Route { + network: NetworkId::from_bytes([4; 32]), + peer: iroh::SecretKey::from_bytes(&[3; 32]).public(), + } +} + +fn addr() -> Ipv4Addr { + Ipv4Addr::new(10, 13, 37, 9) +} + +#[tokio::test] +async fn a_udp_flow_keeps_its_external_port_while_the_upstream_changes_and_stops_with_its_offer() { + let server = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); + let route = route(); + let (replies, mut rx) = mpsc::channel(8); + let gateway = Gateway::new(1280, move |r, p| { + assert_eq!(r, route); + let _ = replies.try_send(p); + }); + let physical = Physical { + index: 0, + address: Ipv4Addr::LOCALHOST, + }; + gateway.configure(vec![(route.network, physical)]); + let flow = Tuple { + src: addr(), + dst: Ipv4Addr::LOCALHOST, + sport: 10403, + dport: server.local_addr().unwrap().port(), + protocol: Protocol::Udp, + }; + let mut port = None; + for body in [b"first".as_slice(), b"after upstream change"] { + gateway.configure(vec![(route.network, physical)]); + assert!(gateway.forward(route, udp_packet(flow, body).unwrap())); + let mut buf = [0; 128]; + let (n, from) = tokio::time::timeout(Duration::from_secs(2), server.recv_from(&mut buf)) + .await + .unwrap() + .unwrap(); + assert_eq!(&buf[..n], body); + assert_eq!(port.get_or_insert(from.port()), &from.port()); + server.send_to(body, from).await.unwrap(); + let answer = tokio::time::timeout(Duration::from_secs(2), rx.recv()) + .await + .unwrap() + .unwrap(); + assert_eq!(crate::vip::packet::tuple(&answer), Some(flow.reverse())); + assert_eq!(&answer[28..], body); + } + gateway.configure(Vec::new()); + assert!(!gateway.forward(route, udp_packet(flow, b"withdrawn").unwrap())); +} + +#[tokio::test] +async fn refused_tcp_returns_a_reset_to_the_originating_client() { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + let (tx, mut rx) = mpsc::channel(2); + let route = route(); + let gateway = Gateway::new(1280, move |r, p| { + assert_eq!(r, route); + let _ = tx.try_send(p); + }); + gateway.configure(vec![( + route.network, + Physical { + index: 0, + address: Ipv4Addr::LOCALHOST, + }, + )]); + let flow = Tuple { + src: addr(), + dst: Ipv4Addr::LOCALHOST, + sport: 42000, + dport: port, + protocol: Protocol::Tcp, + }; + let mut syn = vec![0; 40]; + syn[0] = 0x45; + syn[2..4].copy_from_slice(&40u16.to_be_bytes()); + syn[8] = 64; + syn[9] = 6; + syn[32] = 0x50; + syn[33] = 2; + let checksum = crate::vip::packet::checksum(&syn[..20]); + syn[10..12].copy_from_slice(&checksum.to_be_bytes()); + assert!(gateway.forward(route, crate::vip::packet::rewrite(&syn, flow).unwrap())); + let answer = tokio::time::timeout(Duration::from_secs(2), rx.recv()) + .await + .unwrap() + .unwrap(); + assert!(crate::vip::packet::tcp_reset(&answer)); + assert_eq!(crate::vip::packet::tuple(&answer), Some(flow.reverse())); +} + +fn tcp_packet(tuple: Tuple, flags: u8, seq: u32, ack: u32, body: &[u8]) -> Bytes { + let mut bytes = ip_packet(tuple.src, tuple.dst, 6, 20 + body.len()).unwrap(); + bytes[24..28].copy_from_slice(&seq.to_be_bytes()); + bytes[28..32].copy_from_slice(&ack.to_be_bytes()); + bytes[32] = 0x50; + bytes[33] = flags; + bytes[34..36].copy_from_slice(&65535u16.to_be_bytes()); + bytes[40..].copy_from_slice(body); + packet::rewrite(&bytes, tuple).unwrap() +} + +#[tokio::test] +async fn a_tcp_stream_to_the_same_destination_survives_offer_reconciliation() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + for expected in [b"one", b"two"] { + let mut body = [0; 3]; + socket.read_exact(&mut body).await.unwrap(); + assert_eq!(&body, expected); + socket.write_all(&body).await.unwrap(); + } + }); + tokio::time::timeout(Duration::from_secs(4), async { + let route = route(); + let (tx, mut rx) = mpsc::channel(16); + let gateway = Gateway::new(1280, move |r, p| { + assert_eq!(r, route); + let _ = tx.try_send(p); + }); + let physical = Physical { + index: 0, + address: Ipv4Addr::LOCALHOST, + }; + gateway.configure(vec![(route.network, physical)]); + let flow = Tuple { + src: addr(), + dst: Ipv4Addr::LOCALHOST, + sport: 43210, + dport: port, + protocol: Protocol::Tcp, + }; + let mut seq: u32 = 123; + assert!(gateway.forward(route, tcp_packet(flow, 2, seq, 0, &[]))); + let synack = rx.recv().await.unwrap(); + assert!(packet::syn_ack(&synack)); + let mut ack = u32::from_be_bytes(synack[24..28].try_into().unwrap()).wrapping_add(1); + seq += 1; + for body in [b"one", b"two"] { + assert!(gateway.forward(route, tcp_packet(flow, 0x18, seq, ack, body))); + seq += body.len() as u32; + loop { + let p = rx.recv().await.unwrap(); + let tcp = TcpPacket::new_checked(&p[20..]).unwrap(); + if !tcp.payload().is_empty() { + assert_eq!(tcp.payload(), body); + ack = ack.wrapping_add(body.len() as u32); + assert!(gateway.forward(route, tcp_packet(flow, 0x10, seq, ack, &[]))); + break; + } + } + // A configuration change for a different membership cannot create a new B socket. + gateway.configure(vec![ + (route.network, physical), + (NetworkId::from_bytes([7; 32]), physical), + ]); + } + server.await.unwrap(); + }) + .await + .unwrap(); +} + +/// Two disposable Wintun adapters provide an offline "WAN" and an upstream. +/// A longer prefix on the latter captures local applications for the same IP. +#[cfg(all(windows, feature = "tun-device"))] +#[tokio::test] +#[ignore = "requires an elevated disposable Windows runner and wintun.dll"] +async fn physical_member_sockets_survive_a_more_specific_wintun_route() { + use crate::overlay::{ + Cidr, + provision::{InterfacePlan, InterfaceProvisioner, WintunProvisioner}, + tun::TunDevice, + }; + let wan = Ipv4Addr::new(198, 18, 222, 1); + let upstream = Ipv4Addr::new(198, 18, 222, 5); + let site = Ipv4Addr::new(198, 18, 222, 6); + for dev in netdev::get_interfaces() { + assert!( + dev.ipv4 + .iter() + .all(|net| !net.contains(&wan) && !net.contains(&site)), + "test subnet is in use on {}", + dev.name + ); + } + async fn read(device: &dyn TunDevice, endpoint: SocketAddrV4, body: &[u8]) -> Tuple { + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let p = device.recv().await.unwrap(); + if let Some(t) = packet::tuple(&p) + && t.dst == *endpoint.ip() + && t.dport == endpoint.port() + && p.get(28..) == Some(body) + { + return t; + } + } + }) + .await + .unwrap() + } + async fn wait_source(site: SocketAddrV4, wanted: Ipv4Addr) { + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let s = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap(); + if s.connect(site).await.is_ok() && s.local_addr().unwrap().ip() == wanted { + return; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + }) + .await + .unwrap(); + } + let id = rand::random::(); + let provision = WintunProvisioner::new().unwrap(); + let uplink = provision + .reconcile(&InterfacePlan::new( + format!("tsfw-a-{id:x}"), + 1280, + vec![Cidr::new(wan.into(), 24).unwrap()], + )) + .await + .unwrap() + .device + .unwrap(); + let site = SocketAddrV4::new(site, 38201); + wait_source(site, wan).await; + let index = netdev::get_interfaces() + .into_iter() + .find(|i| i.ipv4.iter().any(|a| a.addr() == wan)) + .unwrap() + .index; + let physical = Physical { + index, + address: wan, + }; + let origin = route(); + let (tx, mut rx) = mpsc::channel(8); + let gateway = Gateway::new(1280, move |_, packet| { + let _ = tx.try_send(packet); + }); + gateway.configure(vec![(origin.network, physical)]); + let flow = Tuple { + src: addr(), + dst: *site.ip(), + sport: 21002, + dport: site.port(), + protocol: Protocol::Udp, + }; + let mut send = async |tuple, payload: &[u8]| { + assert!(gateway.forward(origin, udp_packet(tuple, payload).unwrap())); + let observed = read(&*uplink, site, payload).await; + assert_eq!(observed.src, wan); + uplink + .send(udp_packet(observed.reverse(), payload).unwrap()) + .await + .unwrap(); + let back = tokio::time::timeout(Duration::from_secs(5), rx.recv()) + .await + .unwrap() + .unwrap(); + assert_eq!(packet::tuple(&back), Some(tuple.reverse())); + observed.sport + }; + let initial = send(flow, b"before").await; + let capture = provision + .reconcile(&InterfacePlan::new( + format!("tsfw-c-{id:x}"), + 1280, + vec![Cidr::new(upstream.into(), 30).unwrap()], + )) + .await + .unwrap() + .device + .unwrap(); + wait_source(site, upstream).await; + let local = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap(); + local.send_to(b"local B", site).await.unwrap(); + assert_eq!(read(&*capture, site, b"local B").await.src, upstream); + assert_eq!(send(flow, b"same A socket").await, initial); + send( + Tuple { + sport: 21003, + ..flow + }, + b"new A socket", + ) + .await; + + // Raw ICMP uses the identical physical interface selection and restores A's + // identifier and sequence after reading the actual reply from the uplink. + let mut ping = ip_packet(addr(), *site.ip(), 1, 12).unwrap(); + ping[20] = 8; + ping[24..32].copy_from_slice(b"pingdata"); + let checksum = packet::checksum(&ping[20..]); + ping[22..24].copy_from_slice(&checksum.to_be_bytes()); + assert!(gateway.forward(origin, ping.into())); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let wire = uplink.recv().await.unwrap(); + let Some(n) = packet::header(&wire) else { + continue; + }; + if wire[9] != 1 || wire.get(n + 8..) != Some(b"data") { + continue; + } + assert_eq!(packet::addresses(&wire), Some((wan, *site.ip()))); + let mut pong = ip_packet(*site.ip(), wan, 1, wire.len() - n).unwrap(); + pong[20..].copy_from_slice(&wire[n..]); + pong[20..24].fill(0); + let checksum = packet::checksum(&pong[20..]); + pong[22..24].copy_from_slice(&checksum.to_be_bytes()); + uplink.send(pong.into()).await.unwrap(); + break; + } + let reply = rx.recv().await.unwrap(); + assert_eq!(packet::addresses(&reply), Some((*site.ip(), addr()))); + assert_eq!(&reply[24..], b"pingdata"); + assert_eq!(packet::checksum(&reply[20..]), 0); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn resetting_a_half_open_mesh_handshake_closes_the_physical_socket() { + use tokio::io::AsyncReadExt; + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); + let route = route(); + let (tx, mut rx) = mpsc::channel(4); + let gateway = Gateway::new(1280, move |_, packet| { + let _ = tx.try_send(packet); + }); + gateway.configure(vec![( + route.network, + Physical { + index: 0, + address: Ipv4Addr::LOCALHOST, + }, + )]); + let flow = Tuple { + src: addr(), + dst: Ipv4Addr::LOCALHOST, + sport: 43211, + dport: listener.local_addr().unwrap().port(), + protocol: Protocol::Tcp, + }; + tokio::time::timeout(Duration::from_secs(3), async { + assert!(gateway.forward(route, tcp_packet(flow, 2, 500, 0, &[]))); + let (mut physical, _) = listener.accept().await.unwrap(); + let synack = rx.recv().await.unwrap(); + assert!(packet::syn_ack(&synack)); + let ack = u32::from_be_bytes(synack[24..28].try_into().unwrap()).wrapping_add(1); + assert!(gateway.forward(route, tcp_packet(flow, 0x14, 501, ack, &[]))); + assert_eq!(physical.read(&mut [0; 1]).await.unwrap(), 0); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn a_server_half_close_still_receives_the_members_final_bytes_and_fin() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); + let (out, mut rx) = mpsc::channel(8); + let origin = route(); + let gateway = Gateway::new(1280, move |_, packet| { + let _ = out.try_send(packet); + }); + gateway.configure(vec![( + origin.network, + Physical { + index: 0, + address: Ipv4Addr::LOCALHOST, + }, + )]); + let flow = Tuple { + src: addr(), + dst: Ipv4Addr::LOCALHOST, + sport: 42041, + dport: listener.local_addr().unwrap().port(), + protocol: Protocol::Tcp, + }; + tokio::time::timeout(Duration::from_secs(3), async { + assert!(gateway.forward(origin, tcp_packet(flow, 2, 200, 0, &[]))); + let (mut server, _) = listener.accept().await.unwrap(); + server.shutdown().await.unwrap(); + let synack = rx.recv().await.unwrap(); + assert!(packet::syn_ack(&synack)); + let ack = u32::from_be_bytes(synack[24..28].try_into().unwrap()).wrapping_add(1); + assert!(gateway.forward(origin, tcp_packet(flow, 0x10, 201, ack, &[]))); + loop { + let p = rx.recv().await.unwrap(); + if TcpPacket::new_checked(&p[20..]).unwrap().fin() { + break; + } + } + assert!(gateway.forward( + origin, + tcp_packet(flow, 0x19, 201, ack.wrapping_add(1), b"last bytes") + )); + let mut received = Vec::new(); + server.read_to_end(&mut received).await.unwrap(); + assert_eq!(received, b"last bytes"); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn at_capacity_existing_udp_flows_continue_and_a_new_tuple_is_dropped() { + let server = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); + let origin = route(); + let gateway = Gateway::new(1280, |_, _| {}); + gateway.configure(vec![( + origin.network, + Physical { + index: 0, + address: Ipv4Addr::LOCALHOST, + }, + )]); + let flow = Tuple { + src: addr(), + dst: Ipv4Addr::LOCALHOST, + sport: 1024, + dport: server.local_addr().unwrap().port(), + protocol: Protocol::Udp, + }; + tokio::time::timeout(Duration::from_secs(10), async { + let mut buf = [0; 2]; + for i in 0..EXIT_FORWARD_FLOWS { + let p = udp_packet( + Tuple { + sport: flow.sport + i as u16, + ..flow + }, + b"a", + ) + .unwrap(); + assert!(gateway.forward(origin, p)); + assert_eq!(server.recv(&mut buf).await.unwrap(), 1); + } + let extra = Tuple { + sport: u16::MAX, + ..flow + }; + assert!(gateway.forward(origin, udp_packet(extra, b"no").unwrap())); + assert!(gateway.forward(origin, udp_packet(flow, b"ok").unwrap())); + assert_eq!(server.recv(&mut buf).await.unwrap(), 2); + assert_eq!(&buf, b"ok"); + }) + .await + .unwrap(); +} diff --git a/crates/tsunagi-core/src/overlay/egress/windows.rs b/crates/tsunagi-core/src/overlay/egress/windows.rs new file mode 100644 index 0000000..0351b66 --- /dev/null +++ b/crates/tsunagi-core/src/overlay/egress/windows.rs @@ -0,0 +1,32 @@ +//! Winsock takes the IPv4 interface index in network byte order. +#![allow(unsafe_code)] +use std::{io, os::windows::io::AsRawSocket}; +use windows_sys::Win32::Networking::WinSock::{ + IP_UNICAST_IF, IPPROTO_IP, SOCKET_ERROR, WSAGetLastError, setsockopt, +}; + +pub(super) fn pin(socket: &impl AsRawSocket, index: u32) -> io::Result<()> { + #[cfg(test)] + if index == 0 { + return Ok(()); + } + if index == 0 { + return Err(io::Error::other("no physical exit interface")); + } + let bytes = index.to_be_bytes(); + // The socket owner stays alive for the call. Winsock reads exactly the + // four bytes of the interface index and retains no pointer to them. + if unsafe { + setsockopt( + socket.as_raw_socket() as _, + IPPROTO_IP, + IP_UNICAST_IF, + bytes.as_ptr(), + 4, + ) + } == SOCKET_ERROR + { + return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() })); + } + Ok(()) +} diff --git a/crates/tsunagi-core/src/overlay/hostrules/exit.rs b/crates/tsunagi-core/src/overlay/hostrules/exit.rs index cf536c4..86474e9 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/exit.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/exit.rs @@ -91,6 +91,12 @@ pub trait ExitHostRules: Send + Sync + std::fmt::Debug + 'static { Box::pin(async { None }) } + /// The physical interface index and IPv4 address used by a userspace exit. + /// Kernel-forwarding hosts do not need to expose an egress socket address. + fn forwarded_uplink(&self) -> Option<(u32, std::net::Ipv4Addr)> { + None + } + /// Whether using an exit node on this host needs the underlay addresses /// the agent talks to, because the host cannot exempt the agent's own /// traffic from the default route by user id (Windows). The default is no. @@ -112,6 +118,9 @@ pub fn exit_tag_prefix(interface: &str) -> String { /// The one-line detail for a set of offer outcomes. pub fn offer_detail(outcome: &RuleOutcome, range: &Ipv4Range) -> String { match outcome { + RuleOutcome::Applied if cfg!(windows) => { + format!("physical TCP, UDP and ICMP echo forwarding for {range}") + } RuleOutcome::Applied => format!("masquerade + forward for {range} in place"), RuleOutcome::Failed(reason) => reason.clone(), } diff --git a/crates/tsunagi-core/src/overlay/hostrules/linux_exit.rs b/crates/tsunagi-core/src/overlay/hostrules/linux_exit.rs index 458f119..45e049f 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/linux_exit.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/linux_exit.rs @@ -3,7 +3,7 @@ //! //! # Offering //! -//! For every network that offers this agent as an exit node, three rules, +//! For every network that offers this agent as an exit node, rules //! selected by that network's range and carrying the tag //! `tsunagi-exit::`: //! @@ -11,6 +11,8 @@ //! -t nat POSTROUTING -s ! -o -j MASQUERADE //! -t filter FORWARD -i -s ! -o -j ACCEPT //! -t filter FORWARD -o -d -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT +//! -t mangle PREROUTING -i -s -j MARK --set-xmark +//! -t mangle PREROUTING ! -i -m conntrack --ctorigsrc --ctdir REPLY --ctstate SNAT -j MARK --set-xmark //! ``` //! //! `! -o ` is the egress without naming it: whatever interface the @@ -28,7 +30,7 @@ //! 5205: from all fwmark 0x40000000/0x40000000 lookup main //! 5206: from all uidrange - lookup main //! 5290: from all lookup main suppress_prefixlength 0 -//! 5300: from all lookup 0x7473 +//! 5300: from all iif lo lookup 0x7473 //! ``` //! //! The first two keep the agent's *own* sockets and marked replies off the tunnel: its QUIC, relay, @@ -56,7 +58,11 @@ use super::linux::{ use super::linux_exit_mark; /// The chains the offering rules live in: `(table, chain)`. -const CHAINS: [(&str, &str); 2] = [("nat", "POSTROUTING"), ("filter", "FORWARD")]; +const CHAINS: [(&str, &str); 3] = [ + ("nat", "POSTROUTING"), + ("filter", "FORWARD"), + ("mangle", "PREROUTING"), +]; /// One firewall rule: where it goes, and its match and target. #[derive(Debug, Clone, PartialEq, Eq)] @@ -70,7 +76,7 @@ fn owned(words: &[&str]) -> Vec { words.iter().map(|word| word.to_string()).collect() } -/// The three rules of one offered range. +/// The rules of one offered range. /// /// Each carries a comment naming its interface and range, which is how it is /// found again. A kernel without the `comment` match (small router builds @@ -125,6 +131,37 @@ fn offer_rules(interface: &str, range: &Ipv4Range, comment: bool) -> Vec { &["-j", "ACCEPT"], ), }, + // These marks select the physical routing table for clients we + // forward, including the reverse-path check on physical replies. + // The conntrack original tuple survives switching our own upstream. + Rule { + table: "mangle", + chain: "PREROUTING", + spec: spec( + &["-i", interface, "-s", &range_text], + &["-j", "MARK", "--set-xmark", linux_exit_mark::MARK], + ), + }, + Rule { + table: "mangle", + chain: "PREROUTING", + spec: spec( + &[ + "!", + "-i", + interface, + "-m", + "conntrack", + "--ctorigsrc", + &range_text, + "--ctdir", + "REPLY", + "--ctstate", + "SNAT", + ], + &["-j", "MARK", "--set-xmark", linux_exit_mark::MARK], + ), + }, ] } @@ -159,7 +196,7 @@ struct Found { /// Every rule in an `iptables -S ` listing that is ours: carrying a /// tag that starts with `prefix`, or, on a kernel with no `comment` match, -/// being exactly one of the three rules this module writes for some range. +/// being exactly one of the rules this module writes for some range. /// Anything else in the chain is left alone. fn tagged_rules(listing: &str, chain: &str, prefix: &str) -> Vec { // `tsunagi-exit::` @@ -198,7 +235,7 @@ fn uncommented_tag(interface: &str, chain: &str, rest: &[String]) -> Option Option { std::fs::read_to_string(path).ok() } -fn check_kernel_rpf(overlay: &str) -> Result<(), String> { +fn check_kernel_rpf(overlay: &str, uid: u32) -> Result<(), String> { let directory = "/proc/sys/net/ipv4/conf"; let value = |name: &str, setting: &str| -> Result { read_sysctl(&format!("{directory}/{name}/{setting}")) @@ -391,7 +428,7 @@ fn check_kernel_rpf(overlay: &str) -> Result<(), String> { for entry in std::fs::read_dir(directory).map_err(|err| err.to_string())? { let entry = entry.map_err(|err| err.to_string())?; let name = entry.file_name().to_string_lossy().into_owned(); - if name != "all" && name != "default" && name != "lo" && name != overlay { + if name != "all" && name != "default" && name != "lo" && (name != overlay || uid == 0) { interfaces.push(( name.clone(), value(&name, "rp_filter")?, @@ -481,7 +518,7 @@ impl LinuxHostRules { } let name = interface.to_string(); let prepared = Self::blocking(move || { - check_kernel_rpf(&name)?; + check_kernel_rpf(&name, euid)?; linux_exit_mark::install( &run_firewall, &name, @@ -567,7 +604,7 @@ impl LinuxHostRules { .ok() .and_then(|s| parse_euid(&s)) .ok_or("cannot read agent UID")?; - check_kernel_rpf(&work_name)?; + check_kernel_rpf(&work_name, uid)?; let v6 = std::path::Path::new("/proc/sys/net/ipv6").is_dir(); let sockets = linux_exit_mark::local_sockets(uid, v6)?; if previous @@ -671,7 +708,21 @@ mod tests { #[test] fn the_rules_masquerade_the_range_out_of_every_other_interface_and_forward_it() { let rules = offer_rules("tsun0", &range(), true); - assert_eq!(rules.len(), 3); + assert_eq!(rules.len(), 5); + let outgoing = words(&rules[3].spec); + let replies = words(&rules[4].spec); + assert!( + outgoing.starts_with("-i tsun0 -s 10.13.37.0/24 "), + "{outgoing}" + ); + assert!( + replies.contains("--ctorigsrc 10.13.37.0/24 --ctdir REPLY --ctstate SNAT"), + "{replies}" + ); + for rule in &rules[3..] { + assert_eq!((rule.table, rule.chain), ("mangle", "PREROUTING")); + assert!(words(&rule.spec).ends_with("-j MARK --set-xmark 0x40000000/0x40000000")); + } assert_eq!( words(&rules[0].spec), "-s 10.13.37.0/24 ! -o tsun0 -m comment --comment tsunagi-exit:tsun0:10.13.37.0/24 -j MASQUERADE" @@ -805,7 +856,7 @@ mod tests { let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]); assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]); let inserted = fake.verbs("-I"); - assert_eq!(inserted.len(), 3, "{inserted:?}"); + assert_eq!(inserted.len(), 5, "{inserted:?}"); assert!( inserted.iter().all(|call| !call.contains("comment")), "{inserted:?}" @@ -837,12 +888,12 @@ mod tests { } #[test] - fn a_fresh_host_gets_the_three_rules() { + fn a_fresh_host_gets_the_offer_rules() { let fake = Fake::new(false); let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]); assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]); let inserted = fake.verbs("-I"); - assert_eq!(inserted.len(), 3, "{inserted:?}"); + assert_eq!(inserted.len(), 5, "{inserted:?}"); assert!(inserted[0].contains("-t nat -I POSTROUTING 1")); assert!(fake.verbs("-D").is_empty()); } @@ -857,6 +908,15 @@ mod tests { ) .with_rule("filter", &format!("-A FORWARD -i tsun0 -m comment --comment {tag} -j ACCEPT")) .with_rule("filter", &format!("-A FORWARD -o tsun0 -m comment --comment {tag} -j ACCEPT")); + let fake = offer_rules("tsun0", &range(), true) + .into_iter() + .filter(|rule| rule.chain == "PREROUTING") + .fold(fake, |fake, rule| { + fake.with_rule( + rule.table, + &format!("-A {} {}", rule.chain, words(&rule.spec)), + ) + }); let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]); assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]); assert!(fake.verbs("-I").is_empty()); @@ -875,7 +935,7 @@ mod tests { "-A POSTROUTING -s 10.99.0.0/24 -m comment --comment {old_tag} -j MASQUERADE" ), ) - // Only one of the three for the current range. + // Only one rule for the current range. .with_rule( "filter", &format!("-A FORWARD -i tsun0 -m comment --comment {tag} -j ACCEPT"), @@ -897,7 +957,7 @@ mod tests { deleted.iter().all(|call| !call.contains("eth0")), "{deleted:?}" ); - assert_eq!(fake.verbs("-I").len(), 3); + assert_eq!(fake.verbs("-I").len(), 5); } #[test] diff --git a/crates/tsunagi-core/src/overlay/hostrules/linux_exit_kernel.rs b/crates/tsunagi-core/src/overlay/hostrules/linux_exit_kernel.rs index 5b16bef..ac587a4 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/linux_exit_kernel.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/linux_exit_kernel.rs @@ -467,3 +467,214 @@ while True: String::from_utf8_lossy(&result.stderr) ); } + +const CHAIN_TEST: &str = "overlay::hostrules::linux_exit_kernel::serving_an_established_flow_while_switching_the_local_exit"; + +fn chain_namespace(role: &str) -> Namespace { + let name = format!("tsng-chain-{role}-{}", std::process::id()); + ip(&["netns", "add", &name]); + let guard = Namespace(name); + ip(&["-n", &guard.0, "link", "set", "lo", "up"]); + guard +} + +fn connect(a: &Namespace, left: &str, b: &Namespace, right: &str) { + ip(&[ + "link", "add", left, "netns", &a.0, "type", "veth", "peer", "name", right, "netns", &b.0, + ]); + ip(&["-n", &a.0, "link", "set", left, "up"]); + ip(&["-n", &b.0, "link", "set", right, "up"]); +} + +fn python_in(namespace: &str) -> Command { + let mut cmd = Command::new("ip"); + cmd.args(["netns", "exec", namespace, "python3"]); + cmd +} + +fn chain_echo(namespace: &Namespace, name: &str) -> Echo { + let code = r#"import socketserver, sys +class Echo(socketserver.StreamRequestHandler): + def handle(self): + for line in self.rfile: + self.wfile.write(f'{sys.argv[1]} {self.client_address[0]} '.encode() + line) +with socketserver.ThreadingTCPServer(('198.51.100.2', 42100), Echo) as server: + print('ready', flush=True) + server.serve_forever() +"#; + let mut server = Echo( + python_in(&namespace.0) + .args(["-u", "-c", code, name]) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(), + ); + let mut ready = String::new(); + BufReader::new(server.0.stdout.take().unwrap()) + .read_line(&mut ready) + .unwrap(); + assert_eq!(ready.trim(), "ready"); + server +} + +fn short_chain_probe(mut cmd: Command, phase: &str, expected: &str) { + let probe = r#"import socket +with socket.create_connection(('198.51.100.2', 42100), timeout=3) as s: + s.sendall(b'new\n') + print(s.makefile('rb').readline().decode().strip()) +"#; + let result = cmd.args(["-c", probe]).output().unwrap(); + assert!( + result.status.success(), + "TCP probe {phase} expected {expected}: {}\n{}\n{}\n{}", + String::from_utf8_lossy(&result.stderr), + ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]), + ip(&["-4", "rule", "show"]), + ip(&["neigh", "show"]), + ); + assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), expected); +} + +fn chain_middle(a: &str) { + use super::{BroadcastHostRules, ExitHostPlan, RuleOutcome}; + let range = "10.13.37.0/24".parse().unwrap(); + std::fs::write("/proc/sys/net/ipv4/ip_forward", "1").unwrap(); + // A root agent's UID bypass can also match a kernel reverse lookup. + // Both the NAT reply from the uplink and the reply from C on tsun0 must + // survive strict filtering when the remote Internet address is identical. + for setting in ["rp_filter", "src_valid_mark"] { + std::fs::write(format!("/proc/sys/net/ipv4/conf/all/{setting}"), "1").unwrap(); + } + let filter: Vec = [ + "-t", + "mangle", + "-A", + "PREROUTING", + "-m", + "rpfilter", + "--invert", + "--validmark", + "-j", + "DROP", + ] + .into_iter() + .map(str::to_owned) + .collect(); + let rpf = run_firewall(false, &filter); + assert!( + matches!(rpf, super::linux::Ran::Exited { success: true, .. }), + "{rpf:?}" + ); + let provisioner = NetlinkProvisioner::new().unwrap(); + let host = provisioner.host_rules(); + let exit = host.exit_rules().unwrap(); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let apply = |select| { + let plan = ExitHostPlan { + interface: "tsun0".into(), + offer: vec![range], + overlay: vec![range], + client: select, + client_source: select.then(|| "10.13.37.1".parse().unwrap()), + ..Default::default() + }; + let result = runtime.block_on(exit.apply(&plan)); + assert_eq!(result.offer, [(range, RuleOutcome::Applied)]); + assert_eq!(result.client, select.then_some(RuleOutcome::Applied)); + }; + apply(false); + // The socket is created once and remains open across both reconciliations. + let persistent = r#"import socket, sys +with socket.create_connection(('198.51.100.2',42100), timeout=3) as s: + out = s.makefile('rb') + for line in sys.stdin.buffer: + s.sendall(line) + print(out.readline().decode().strip(), flush=True) +"#; + let mut stream = Echo( + python_in(a) + .args(["-u", "-c", persistent]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(), + ); + let mut input = stream.0.stdin.take().unwrap(); + let mut output = BufReader::new(stream.0.stdout.take().unwrap()); + for (change, phase, b_egress) in [ + (None, "before", "uplink 192.0.2.1 new"), + (Some(true), "selected", "exit-c 10.13.37.1 new"), + (Some(false), "cleared", "uplink 192.0.2.1 new"), + ] { + if let Some(selected) = change { + apply(selected); + } + writeln!(input, "{phase}").unwrap(); + let mut reply = String::new(); + output.read_line(&mut reply).unwrap(); + assert_eq!( + reply.trim(), + format!("uplink 192.0.2.1 {phase}"), + "ongoing TCP stream from A" + ); + short_chain_probe(python_in(a), phase, "uplink 192.0.2.1 new"); + // A regular application on B sends to exactly the same IP and port as A. + let mut local = Command::new("python3"); + local.uid(991).gid(991); + short_chain_probe(local, phase, b_egress); + } + runtime.block_on(exit.clear("tsun0")); +} + +#[test] +#[ignore = "needs Linux network namespaces, iproute2, iptables and Python"] +fn serving_an_established_flow_while_switching_the_local_exit() { + if let Ok(a) = std::env::var("TSUNAGI_EXIT_CHAIN_A") { + chain_middle(&a); + return; + } + let a = chain_namespace("a"); + let b = chain_namespace("b"); + let c = chain_namespace("c"); + let uplink = chain_namespace("wan"); + // Emulate the one overlay interface on B. The bridge is a separate + // namespace so that A, B and C see only packets on their own veth. + let mesh = chain_namespace("lan"); + ip(&["-n", &mesh.0, "link", "add", "mesh", "type", "bridge"]); + ip(&["-n", &mesh.0, "link", "set", "mesh", "up"]); + for (ns, port, address) in [ + (&a, "to-a", "10.13.37.2/24"), + (&b, "to-b", "10.13.37.1/24"), + (&c, "to-c", "10.13.37.3/24"), + ] { + connect(ns, "tsun0", &mesh, port); + ip(&["-n", &mesh.0, "link", "set", port, "master", "mesh"]); + ip(&["-n", &ns.0, "addr", "add", address, "dev", "tsun0"]); + } + connect(&b, "wan-b", &uplink, "wan"); + ip(&["-n", &b.0, "addr", "add", "192.0.2.1/24", "dev", "wan-b"]); + ip(&["-n", &uplink.0, "addr", "add", "192.0.2.2/24", "dev", "wan"]); + ip(&["-n", &a.0, "route", "add", "default", "via", "10.13.37.1"]); + ip(&["-n", &b.0, "route", "add", "default", "via", "192.0.2.2"]); + for ns in [&uplink, &c] { + ip(&["-n", &ns.0, "addr", "add", "198.51.100.2/32", "dev", "lo"]); + } + let _physical = chain_echo(&uplink, "uplink"); + let _exit = chain_echo(&c, "exit-c"); + let result = Command::new("ip") + .args(["netns", "exec", &b.0]) + .arg(std::env::current_exe().unwrap()) + .args(["--ignored", "--exact", CHAIN_TEST, "--nocapture"]) + .env("TSUNAGI_EXIT_CHAIN_A", &a.0) + .output() + .unwrap(); + assert!( + result.status.success(), + "{}\n{}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); +} diff --git a/crates/tsunagi-core/src/overlay/hostrules/linux_exit_mark.rs b/crates/tsunagi-core/src/overlay/hostrules/linux_exit_mark.rs index 9eff582..59f8fc6 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/linux_exit_mark.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/linux_exit_mark.rs @@ -8,8 +8,10 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; /// Outside Tailscale's 0xff0000 mask and ordinary low-bit WireGuard marks. pub(crate) const UNDERLAY_MARK: u32 = 0x4000_0000; pub(crate) const UNDERLAY_MASK: u32 = UNDERLAY_MARK; -const MARK: &str = "0x40000000/0x40000000"; +pub(super) const MARK: &str = "0x40000000/0x40000000"; const MASK: &str = "0x40000000"; +/// An authenticated return packet from this host’s own upstream exit. +pub(crate) const EXIT_REPLY_MARK: u32 = 0x2000_0000; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub(super) struct Listener { @@ -141,11 +143,11 @@ fn words(values: &[&str]) -> Vec { values.iter().map(|s| (*s).into()).collect() } -fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec)> { +fn rules(interface: &str, uid: u32, ipv6: bool) -> Vec<(&'static str, Vec)> { let tag = tag(interface); - let uid = uid.to_string(); + let owner = uid.to_string(); // Insert at position one in this order: final OUTPUT order is MARK, SAVE. - vec![ + let mut rules = vec![ ( "PREROUTING", words(&[ @@ -175,7 +177,7 @@ fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec)> { "-m", "owner", "--uid-owner", - &uid, + &owner, "-m", "mark", "--mark", @@ -199,7 +201,7 @@ fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec)> { "-m", "owner", "--uid-owner", - &uid, + &owner, "-m", "comment", "--comment", @@ -210,7 +212,40 @@ fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec)> { MARK, ]), ), - ] + ]; + if !ipv6 && uid == 0 { + // Both xt_rpfilter and the kernel's strict rp_filter perform the + // reverse lookup as UID 0. For an established local application's + // reply from our upstream, the /0 must point back to this interface, + // ahead of the root daemon's UID bypass. The actual packet's LOCAL + // destination still uses routing table local at priority zero. + rules.push(( + "PREROUTING", + words(&[ + "-i", + interface, + "-m", + "addrtype", + "--dst-type", + "LOCAL", + "-m", + "conntrack", + "--ctdir", + "REPLY", + "--ctstate", + "ESTABLISHED,RELATED", + "-m", + "comment", + "--comment", + &tag, + "-j", + "MARK", + "--set-xmark", + "0x20000000/0x20000000", + ]), + )); + } + rules } fn execute(run: RunFamily<'_>, v6: bool, args: Vec) -> Result { @@ -295,7 +330,7 @@ fn install_with_listeners( clear(run, interface, v6)?; let result = (|| { for family in [false, true].into_iter().filter(|family| !family || v6) { - for (chain, spec) in rules(interface, uid) { + for (chain, spec) in rules(interface, uid, family) { let args = words(&["-t", "mangle", "-I", chain, "1"]) .into_iter() .chain(spec) @@ -409,6 +444,25 @@ mod tests { assert_eq!(UNDERLAY_MASK & 0x00ff_0000, 0); } + #[test] + fn only_root_daemons_mark_local_ipv4_replies_from_their_own_exit() { + for (uid, v6) in [(990, false), (0, true), (0, false)] { + let rules = rules("tsun0", uid, v6); + let marked: Vec<_> = rules + .iter() + .filter(|(_, args)| args.contains(&"0x20000000/0x20000000".to_string())) + .collect(); + if uid == 0 && !v6 { + assert_eq!(marked.len(), 1); + assert_eq!(marked[0].0, "PREROUTING"); + let text = marked[0].1.join(" "); + assert!(text.contains("-i tsun0 -m addrtype --dst-type LOCAL -m conntrack --ctdir REPLY --ctstate ESTABLISHED,RELATED")); + } else { + assert!(marked.is_empty()); + } + } + } + #[test] fn cleanup_retains_other_interfaces_and_rolls_back_partial_ipv6_installation() { let calls = RefCell::new(Vec::new()); diff --git a/crates/tsunagi-core/src/overlay/hostrules/macos_exit.rs b/crates/tsunagi-core/src/overlay/hostrules/macos_exit.rs index 75249bd..95774fa 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/macos_exit.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/macos_exit.rs @@ -9,7 +9,9 @@ //! //! ```text //! nat on inet from to any -> () -//! pass in quick on inet from to ! +//! pass in quick on inet from to ! tag no state +//! pass out quick on route-to ( ) inet from to any tagged no state +//! pass out quick on inet from any to any flags any tagged keep state (if-bound) //! ``` //! //! The anchor lives under `com.apple/` on purpose: the stock `/etc/pf.conf` @@ -310,6 +312,10 @@ fn pf_rules( let mut nat = Vec::new(); let mut filter = Vec::new(); let mut tables = Vec::new(); + let via = match egress.gateway { + Some(gateway) => format!("({out} {gateway})"), + None => out.clone(), + }; if let Some(client) = client { let tag = format!("tsng_underlay_{interface}"); nat.push(format!( @@ -327,10 +333,6 @@ fn pf_rules( )); format!("! ") }; - let via = match egress.gateway { - Some(gateway) => format!("({out} {gateway})"), - None => out.clone(), - }; filter.push(format!( "pass out quick on {interface} route-to {via} inet proto {{ tcp udp }} \ from any to {target} user {} tag {tag} no state", @@ -347,8 +349,24 @@ fn pf_rules( // 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})")); + let tag = format!("tsng_forward_{interface}"); + // 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}" + "pass in quick on {interface} inet from {range} to ! {range} tag {tag} no state" + )); + } + if !offer.is_empty() { + let tag = format!("tsng_forward_{interface}"); + filter.insert(0, format!( + "pass out quick on {interface} route-to {via} inet from any to any 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. + filter.push(format!( + "pass out quick on {out} inet from any to any flags any tagged {tag} keep state (if-bound)" )); } tables @@ -993,7 +1011,9 @@ destination: default\n\ assert_eq!( text, "nat on en0 inet from 10.13.37.0/24 to any -> (en0)\n\ - pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24\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 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" ); // Translation precedes filtering, as pf requires. assert!(text.find("nat on").unwrap() < text.find("pass in").unwrap()); @@ -1114,7 +1134,9 @@ destination: default\n\ assert_eq!( fake.stdins.borrow()[0], "nat on en0 inet from 10.13.37.0/24 to any -> (en0)\n\ - pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24\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 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" ); // sysctl is only ever asked, never told. assert!( diff --git a/crates/tsunagi-core/src/overlay/hostrules/macos_exit_kernel.rs b/crates/tsunagi-core/src/overlay/hostrules/macos_exit_kernel.rs index c11c1ef..c28a7b2 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/macos_exit_kernel.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/macos_exit_kernel.rs @@ -66,14 +66,14 @@ impl Drop for Capture<'_> { } impl Capture<'_> { - fn enable(&mut self) { + fn offer(&self, use_upstream: bool) { 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 { + &ranges[..1], + use_upstream.then_some(&ClientRules { uid: 0, overlay: &ranges, }), @@ -86,6 +86,9 @@ impl Capture<'_> { Some(&rules), ) .unwrap(); + } + fn enable(&mut self) { + self.offer(true); run_ok( &run_tool, Tool::Route, @@ -250,6 +253,45 @@ async fn udp_round_trip(uplink: &dyn TunDevice, socket: &UdpSocket, stage: &str) assert_eq!(&buf[..len], b"QUIC path"); } +async fn member_round_trip( + overlay: &dyn TunDevice, + uplink: &dyn TunDevice, + port: u16, + data: &[u8], +) -> u16 { + let member = Ipv4Addr::from(u32::from(FIRST) + 2); + let ip = Ipv4Repr { + src_addr: member, + dst_addr: REMOTE, + next_header: IpProtocol::Udp, + payload_len: 8 + data.len(), + hop_limit: 64, + }; + let mut raw = vec![0; ip.buffer_len() + ip.payload_len]; + let mut out = Ipv4Packet::new_unchecked(&mut raw[..]); + ip.emit(&mut out, &Default::default()); + let mut udp = UdpPacket::new_unchecked(out.payload_mut()); + udp.set_len(ip.payload_len as u16); + udp.set_src_port(port); + udp.set_dst_port(8020); + udp.payload_mut().copy_from_slice(data); + udp.fill_checksum(&member.into(), &REMOTE.into()); + overlay.send(raw.into()).await.unwrap(); + let outbound = packet(uplink, REMOTE, IpProtocol::Udp, 8020, data).await; + let physical = Ipv4Packet::new_checked(&outbound[..]).unwrap(); + assert_eq!(physical.src_addr(), UPLINK); + let translated = UdpPacket::new_checked(physical.payload()) + .unwrap() + .src_port(); + uplink.send(reply(&outbound)).await.unwrap(); + let inbound = packet(overlay, member, IpProtocol::Udp, port, data).await; + assert_eq!( + Ipv4Packet::new_checked(&inbound[..]).unwrap().src_addr(), + REMOTE + ); + translated +} + #[tokio::test] #[ignore = "requires root, the stock Apple PF anchor, and a disposable macOS runner"] async fn exit_preserves_underlay_and_both_meshes() { @@ -272,7 +314,16 @@ async fn exit_preserves_underlay_and_both_meshes() { added_route: false, added_scoped: false, }; + // The disposable runner enables kernel forwarding. A keeps the same + // translated address and port when B installs an upstream route to this IP. + capture.offer(false); + let port = member_round_trip(&*overlay, &*uplink, 43001, b"member before").await; capture.enable(); + assert_eq!( + member_round_trip(&*overlay, &*uplink, 43001, b"member during").await, + port + ); + member_round_trip(&*overlay, &*uplink, 43002, b"new member flow").await; check_capture_routes(overlay.name(), uplink.name()); udp_round_trip(&*uplink, &existing_quic, "existing socket after exit").await; diff --git a/crates/tsunagi-core/src/overlay/hostrules/windows.rs b/crates/tsunagi-core/src/overlay/hostrules/windows.rs index e02aace..0a9732c 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/windows.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/windows.rs @@ -159,6 +159,19 @@ async fn step(what: &'static str, script: String) -> RuleOutcome { #[derive(Debug, Default)] pub struct WindowsHostRules { relay_cache: Arc>, + uplink: Arc>>, +} + +/// A temporary inventory failure cannot revoke existing sockets. A positive +/// withdrawal of the last offer releases their uplink. +fn remember_uplink( + cache: &Mutex>, + offering: bool, + observed: Option<(u32, Ipv4Addr)>, +) { + if !offering || observed.is_some() { + *cache.lock().unwrap_or_else(|e| e.into_inner()) = observed; + } } impl WindowsHostRules { @@ -233,6 +246,10 @@ fn resolve_host(host: &str) -> Vec { } impl ExitHostRules for WindowsHostRules { + fn forwarded_uplink(&self) -> Option<(u32, Ipv4Addr)> { + *self.uplink.lock().unwrap_or_else(|e| e.into_inner()) + } + fn needs_bypass(&self) -> bool { true } @@ -241,17 +258,20 @@ impl ExitHostRules for WindowsHostRules { Box::pin(async move { let job = plan.clone(); let cache = Arc::clone(&self.relay_cache); + let uplink = Arc::clone(&self.uplink); 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( + let (report, physical) = windows_exit::reconcile( &|script| run_powershell_output(script), &|host| hosts.get(host).cloned().unwrap_or_default(), &job, - ) + ); + remember_uplink(&uplink, !job.offer.is_empty(), physical); + report }) .await .unwrap_or_else(|err| { @@ -271,11 +291,12 @@ impl ExitHostRules for WindowsHostRules { fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option> { Box::pin(async move { - if !plan.client { + if !plan.client && plan.offer.is_empty() { return None; } let job = plan.clone(); let cache = Arc::clone(&self.relay_cache); + let uplink = Arc::clone(&self.uplink); tokio::task::spawn_blocking(move || { let now = Instant::now(); let mut cache = cache.lock().unwrap_or_else(|p| p.into_inner()); @@ -287,6 +308,16 @@ impl ExitHostRules for WindowsHostRules { } let hosts = cache.lookup(&job.bypass_hosts, now, &resolve_host); drop(cache); + if !job.offer.is_empty() { + remember_uplink( + &uplink, + true, + windows_exit::uplink(&run_powershell_output, &job.interface).ok(), + ); + } + if !job.client { + return None; + } Some( match windows_exit::refresh_bypass( &run_powershell_output, @@ -307,7 +338,9 @@ impl ExitHostRules for WindowsHostRules { Box::pin(async move { let name = interface.to_string(); let cache = Arc::clone(&self.relay_cache); + let uplink = Arc::clone(&self.uplink); let _ = tokio::task::spawn_blocking(move || { + *uplink.lock().unwrap_or_else(|e| e.into_inner()) = None; *cache.lock().unwrap_or_else(|p| p.into_inner()) = RelayCache::default(); windows_exit::clear_all(&|script| run_powershell_output(script), &name) }) @@ -355,6 +388,22 @@ mod tests { use super::*; + #[test] + fn transient_uplink_lookup_failure_preserves_the_live_forwarding_address() { + let cache = Mutex::new(None); + let old = (4, Ipv4Addr::new(192, 0, 2, 5)); + let new = (7, Ipv4Addr::new(198, 51, 100, 3)); + for (offering, observed, expected) in [ + (true, Some(old), Some(old)), + (true, None, Some(old)), + (true, Some(new), Some(new)), + (false, None, None), + ] { + remember_uplink(&cache, offering, observed); + assert_eq!(*cache.lock().unwrap(), expected); + } + } + #[test] fn relay_dns_survives_a_transient_failure_and_retires_rotated_addresses() { use std::time::{Duration, Instant}; diff --git a/crates/tsunagi-core/src/overlay/hostrules/windows_exit.rs b/crates/tsunagi-core/src/overlay/hostrules/windows_exit.rs index 0cec553..564b431 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/windows_exit.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/windows_exit.rs @@ -1,4 +1,4 @@ -//! Exit-node host rules on Windows: WinNAT through PowerShell. +//! Physical exit socket selection and client routes on Windows, through PowerShell. //! //! Compiled on every platform so the scripts and the plan logic are tested //! everywhere; only `WindowsHostRules` runs them, and only on Windows. It @@ -6,20 +6,10 @@ //! //! # Offering //! -//! One NAT object per offered range, named with the usual tag -//! `tsunagi-exit::`: -//! -//! ```text -//! New-NetNat -Name -InternalIPInterfaceAddressPrefix -//! ``` -//! -//! WinNAT translates that range out of whichever interface the traffic leaves -//! by, which is the Windows counterpart of the Linux masquerade. Windows -//! forwards per interface, and the egress is not known here, so forwarding is -//! only *read* for the overlay interface; turning it on for the interfaces -//! involved is the owner's decision (`Set-NetIPInterface -Forwarding Enabled`). -//! Some Windows versions allow a single NAT per host: a second offered range -//! then reports its own failure. +//! Forwarded TCP/UDP and ICMP echo use sockets pinned to the physical +//! interface and address. This keeps a member's traffic independent of local +//! split routes even for the same destination. The userspace gateway owns the +//! flows; changing a local upstream does not recreate them. //! //! # Using //! @@ -51,7 +41,7 @@ use super::RuleOutcome; use std::net::Ipv4Addr; -use super::exit::{ExitHostPlan, ExitHostReport, exit_tag, exit_tag_prefix}; +use super::exit::{ExitHostPlan, ExitHostReport, exit_tag_prefix}; use crate::state::Ipv4Range; /// The route metric that marks a bypass route as this agent's. @@ -68,64 +58,67 @@ fn ps_literal(value: &str) -> String { format!("'{}'", value.replace('\'', "''")) } -/// Creates the NAT of one range, replacing one this agent made before. -fn nat_script(interface: &str, range: &Ipv4Range) -> String { - let name = ps_literal(&exit_tag(interface, range)); - let prefix = ps_literal(&range.to_string()); - format!( - "$ErrorActionPreference = 'Stop'\n\ - $name = {name}\n\ - Get-NetNat -Name $name -ErrorAction SilentlyContinue | \ - Remove-NetNat -Confirm:$false -ErrorAction SilentlyContinue\n\ - New-NetNat -Name $name -InternalIPInterfaceAddressPrefix {prefix} | Out-Null\n" - ) -} - -/// Removes this interface's NAT objects except those named in `keep`. -fn prune_script(interface: &str, keep: &[Ipv4Range]) -> String { +/// Remove only obsolete WinNAT objects created by older Tsunagi releases. +fn legacy_nat_cleanup(interface: &str) -> String { let prefix = ps_literal(&exit_tag_prefix(interface)); - let keep: Vec = keep - .iter() - .map(|range| ps_literal(&exit_tag(interface, range))) - .collect(); format!( "$ErrorActionPreference = 'SilentlyContinue'\n\ - $prefix = {prefix}\n\ - $keep = @({})\n\ - Get-NetNat | Where-Object {{ $_.Name.StartsWith($prefix) -and \ - ($keep -notcontains $_.Name) }} | Remove-NetNat -Confirm:$false\n\ - exit 0\n", - keep.join(", ") + $prefix = {prefix}\n\ + Get-NetNat | Where-Object {{ $_.Name.StartsWith($prefix) }} | Remove-NetNat -Confirm:$false\n\ + exit 0" ) } -/// Prints `Enabled` or `Disabled` for the interface's IPv4 forwarding. -fn forwarding_script(interface: &str) -> String { +/// Both client bypasses and forwarded sockets use the winning /0 outside Wintun. +fn select_gateway(interface: &str) -> String { let alias = ps_literal(interface); format!( "$ErrorActionPreference = 'Stop'\n\ - (Get-NetIPInterface -InterfaceAlias {alias} -AddressFamily IPv4).Forwarding\n" + $alias = {alias}\n\ + $best = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -AddressFamily IPv4 \ + -PolicyStore ActiveStore | Where-Object {{ $_.InterfaceAlias -ne $alias -and \ + $_.NextHop -ne '0.0.0.0' -and $_.State -ne 'Dead' }} | Sort-Object {{ $_.RouteMetric + \ + (Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }} | \ + Select-Object -First 1\n\ + if (-not $best) {{ throw 'the host has no default gateway outside the overlay' }}\n" ) } -/// Prints the physical default and the more specific routes that already -/// outrank the split defaults. Ignore our own host routes when refreshing. +/// Read a usable source on the selected physical interface, even while the two +/// client /1 routes point at Wintun. Never ask the default via the test target. +fn uplink_script(interface: &str) -> String { + format!( + "{}$source = Get-NetIPAddress -InterfaceIndex $best.InterfaceIndex -AddressFamily IPv4 \ + -AddressState Preferred | Where-Object {{ -not $_.SkipAsSource }} | Select-Object -First 1\n\ + if (-not $source) {{ throw 'the physical interface has no usable IPv4 address' }}\n\ + \"$($best.InterfaceIndex) $($source.IPAddress)\"", + select_gateway(interface) + ) +} + +pub(super) fn uplink(run: RunScript<'_>, interface: &str) -> Result<(u32, Ipv4Addr), String> { + let text = run(&uplink_script(interface))?; + parse_gateway(&text) + .filter(|(i, ip)| { + *i != 0 + && !ip.is_unspecified() + && !ip.is_multicast() + && !ip.is_loopback() + && !ip.is_broadcast() + }) + .ok_or_else(|| { + "cannot determine the physical interface and IPv4 source for forwarding".into() + }) +} + fn gateway_script(interface: &str) -> String { - let alias = ps_literal(interface); format!( - "$ErrorActionPreference = 'Stop'\n\ - $alias = {alias}\n\ - $best = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -AddressFamily IPv4 \ - -PolicyStore ActiveStore | Where-Object {{ $_.InterfaceAlias -ne $alias -and \ - $_.NextHop -ne '0.0.0.0' }} | Sort-Object {{ $_.RouteMetric + \ - (Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }} | \ - Select-Object -First 1\n\ - if (-not $best) {{ throw 'the host has no default gateway outside the overlay' }}\n\ - \"$($best.InterfaceIndex) $($best.NextHop)\"\n\ + "{}\"$($best.InterfaceIndex) $($best.NextHop)\"\n\ Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore | Where-Object {{ \ $_.InterfaceAlias -ne $alias -and $_.State -ne 'Dead' -and \ -not ($_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32')) }} | \ - Select-Object -ExpandProperty DestinationPrefix\n" + Select-Object -ExpandProperty DestinationPrefix\n", + select_gateway(interface) ) } @@ -269,35 +262,25 @@ fn apply_client( Ok(()) } -fn parse_forwarding(text: &str) -> Option { - match text.trim().to_ascii_lowercase().as_str() { - "enabled" | "1" => Some(true), - "disabled" | "0" => Some(false), - _ => None, - } -} - -/// Makes the host match the plan. -pub(super) fn apply_plan( +/// Decide the egress for all offered memberships, then reconcile the separate +/// destination routes used by this device's applications. +pub(super) fn reconcile( run: RunScript<'_>, resolve: Resolve<'_>, plan: &ExitHostPlan, -) -> ExitHostReport { +) -> (ExitHostReport, Option<(u32, Ipv4Addr)>) { let interface = plan.interface.as_str(); - // What an earlier plan left and this one no longer wants. - let pruned = run(&prune_script(interface, &plan.offer)); + let physical = (!plan.offer.is_empty()).then(|| uplink(run, interface)); let offer = plan .offer .iter() .map(|range| { - let outcome = match &pruned { - Err(why) => RuleOutcome::Failed(why.clone()), - Ok(_) => match run(&nat_script(interface, range)) { - Ok(_) => RuleOutcome::Applied, - Err(why) => RuleOutcome::Failed(why), - }, + let result = match &physical { + Some(Ok(_)) => RuleOutcome::Applied, + Some(Err(why)) => RuleOutcome::Failed(why.clone()), + None => RuleOutcome::Failed("no exit offer".into()), }; - (*range, outcome) + (*range, result) }) .collect(); let client = if plan.client { @@ -310,23 +293,19 @@ pub(super) fn apply_plan( let _ = run(&remove_client_script(interface)); None }; - let forwarding = if plan.offer.is_empty() { - None - } else { - run(&forwarding_script(interface)) - .ok() - .and_then(|text| parse_forwarding(&text)) - }; - ExitHostReport { - offer, - forwarding, - client, - } + ( + ExitHostReport { + offer, + forwarding: None, + client, + }, + physical.and_then(Result::ok), + ) } /// Removes every NAT object of this agent's for the interface. pub(super) fn clear_all(run: RunScript<'_>, interface: &str) { - if let Err(why) = run(&prune_script(interface, &[])) { + if let Err(why) = run(&legacy_nat_cleanup(interface)) { tracing::warn!(interface, "cannot remove the exit node NAT: {why}"); } if let Err(why) = run(&remove_client_script(interface)) { @@ -357,84 +336,51 @@ mod tests { } #[test] - fn the_nat_is_named_with_the_tag_and_replaces_its_own() { - let script = nat_script("tsun0", &range()); - assert!( - script.contains("$name = 'tsunagi-exit:tsun0:10.13.37.0/24'"), - "{script}" - ); - assert!(script.contains("-InternalIPInterfaceAddressPrefix '10.13.37.0/24'")); - assert!( - script.find("Remove-NetNat").unwrap() < script.find("New-NetNat").unwrap(), - "{script}" - ); - } - - #[test] - fn a_quote_in_a_value_cannot_escape_the_literal() { - let script = nat_script("x'; Remove-Item C:\\ #", &range()); - assert!(script.contains("'tsunagi-exit:x''; Remove-Item C:\\ #:10.13.37.0/24'")); - assert!(prune_script("x'y", &[]).contains("'tsunagi-exit:x''y:'")); - assert!(forwarding_script("x'y").contains("'x''y'")); - } - - #[test] - fn pruning_keeps_wanted_ranges_and_only_selects_this_interfaces_nats() { - let script = prune_script("tsun0", &[range()]); - assert!(script.contains("$prefix = 'tsunagi-exit:tsun0:'")); - assert!(script.contains("$keep = @('tsunagi-exit:tsun0:10.13.37.0/24')")); - assert!(script.contains("StartsWith($prefix)")); - assert!(script.contains("exit 0")); - assert!(prune_script("tsun0", &[]).contains("$keep = @()")); - } - - #[test] - fn forwarding_text_is_read_never_written() { - assert_eq!(parse_forwarding("Enabled\r\n"), Some(true)); - assert_eq!(parse_forwarding("Disabled"), Some(false)); - assert_eq!(parse_forwarding("what"), None); - let script = forwarding_script("tsun0"); - assert!(script.contains("Get-NetIPInterface")); - assert!(!script.contains("Set-NetIPInterface")); - } - - #[test] - fn offering_prunes_then_creates_and_reads_forwarding() { + fn selecting_an_upstream_never_recreates_a_forwarded_session_or_installs_a_destination_exception() + { let calls = RefCell::new(Vec::new()); let run = |script: &str| -> Result { calls.borrow_mut().push(script.to_string()); - Ok(if script.contains("Get-NetIPInterface") { - "Disabled\n".to_string() + Ok(if script.contains("Get-NetIPAddress") { + "7 192.0.2.15".into() + } else if script.contains("Select-Object -ExpandProperty DestinationPrefix") { + "7 192.0.2.1".into() } else { String::new() }) }; - let report = apply_plan(&run, &no_names, &plan(false)); - assert_eq!(report.offer, vec![(range(), RuleOutcome::Applied)]); - assert_eq!(report.forwarding, Some(false)); - assert_eq!(report.client, None); - let calls = calls.borrow(); - assert!(calls[0].contains("StartsWith"), "{calls:?}"); - assert!(calls[1].contains("New-NetNat"), "{calls:?}"); - // Without a client, the routes of an earlier plan are taken away. - assert!(calls[2].contains("RouteMetric -eq 7373"), "{calls:?}"); - assert!(calls[3].contains("Get-NetIPInterface"), "{calls:?}"); + for client in [false, true, false] { + let (report, physical) = reconcile(&run, &no_names, &plan(client)); + assert_eq!(physical, Some((7, "192.0.2.15".parse().unwrap()))); + assert_eq!(report.offer, vec![(range(), RuleOutcome::Applied)]); + assert_eq!(report.forwarding, None); + } + assert!( + !calls + .borrow() + .iter() + .any(|s| s.contains("NetNat") || s.contains("Set-NetIPInterface")) + ); + assert!(uplink_script("x'y").contains("'x''y'")); } #[test] - fn a_failing_nat_is_that_ranges_failure() { - let run = |script: &str| -> Result { - if script.contains("New-NetNat") { - Err("A NAT with this prefix already exists".into()) - } else { - Ok(String::new()) - } - }; - let report = apply_plan(&run, &no_names, &plan(false)); - let RuleOutcome::Failed(why) = &report.offer[0].1 else { - panic!("{report:?}"); - }; - assert!(why.contains("already exists"), "{why}"); + fn failure_to_find_a_physical_source_never_advertises_a_working_exit() { + for line in [ + "", + "0 198.51.100.3", + "5 0.0.0.0", + "5 127.0.0.1", + "3 10.0.0.1 extra", + ] { + let (report, physical) = reconcile(&|_| Ok(line.into()), &no_names, &plan(false)); + assert_eq!(physical, None); + assert!(matches!(&report.offer[0].1, RuleOutcome::Failed(_))); + } + } + + fn apply_plan(run: RunScript<'_>, resolve: Resolve<'_>, plan: &ExitHostPlan) -> ExitHostReport { + reconcile(run, resolve, plan).0 } fn no_names(_: &str) -> Vec { @@ -764,7 +710,7 @@ exit 0"# }; clear_all(&run, "tsun0"); let seen = seen.borrow(); - assert!(seen[0].contains("$keep = @()")); + assert!(seen[0].contains("StartsWith($prefix)")); assert!(seen[0].contains("'tsunagi-exit:tsun0:'")); } } diff --git a/crates/tsunagi-core/src/overlay/interface.rs b/crates/tsunagi-core/src/overlay/interface.rs index f9168c8..38143b1 100644 --- a/crates/tsunagi-core/src/overlay/interface.rs +++ b/crates/tsunagi-core/src/overlay/interface.rs @@ -147,6 +147,8 @@ impl Tally { /// The overlay interface. pub struct Interface { device: Arc, + #[cfg(windows)] + forwarding: Option, factory: Arc, name: String, mtu: u32, @@ -235,6 +237,25 @@ impl Interface { let name = device.name().to_string(); let tally = Arc::new(Tally::default()); + #[cfg(windows)] + let forwarding = factory.on_host().then(|| { + let routes = routes.clone(); + let carrier = carrier.clone(); + super::egress::Gateway::new(mtu, move |route, packet| { + if let Some(IpHeader::V4 { + source, + destination, + }) = IpHeader::parse(&packet) + && routes.accepts_exit_traffic(route.network, source) + && matches!( + routes.packet_source(route.network, route.peer, destination), + Some(PacketSource::Member) + ) + { + carrier.carry(route, packet); + } + }) + }); let vip_task = { let factory = Arc::clone(&factory); let routes = Arc::clone(&routes); @@ -320,9 +341,11 @@ impl Interface { tally.multicast.fetch_add(1, Ordering::Relaxed); continue; } - let selected = match destination { - IpAddr::V4(address) => routes.packet_route(address), - IpAddr::V6(_) => None, + let selected = match (header.source(), destination) { + (IpAddr::V4(source), IpAddr::V4(address)) => { + routes.packet_route(Some(source), address) + } + _ => None, }; let Some((route, exit)) = selected else { tally.note_unroutable(destination); @@ -342,6 +365,8 @@ impl Interface { }; Ok(Self { + #[cfg(windows)] + forwarding, device, factory, name, @@ -464,6 +489,10 @@ impl Interface { (state.plan.clone(), state.is_ok()) }; if wanted.is_empty() { + #[cfg(windows)] + if let Some(gateway) = &self.forwarding { + gateway.configure(Vec::new()); + } if planned.is_some() { exit.clear(&self.name).await; let mut state = self.exit_state(); @@ -482,9 +511,13 @@ impl Interface { report.client = Some(outcome); } } + #[cfg(windows)] + self.configure_forwarding(exit.forwarded_uplink()); return; } let report = exit.apply(&wanted).await; + #[cfg(windows)] + self.configure_forwarding(exit.forwarded_uplink()); for (range, outcome) in &report.offer { match outcome { RuleOutcome::Applied => tracing::info!( @@ -532,6 +565,22 @@ impl Interface { state.report = Some(report); } + #[cfg(windows)] + fn configure_forwarding(&self, physical: Option<(u32, std::net::Ipv4Addr)>) { + if let Some(gateway) = &self.forwarding { + gateway.configure( + self.routes + .exit_offers() + .into_iter() + .filter_map(|(network, _)| { + let (index, address) = physical?; + Some((network, super::egress::Physical { index, address })) + }) + .collect(), + ); + } + } + /// Whether the host routes its own transport by destination. pub(crate) fn needs_underlay_targets(&self) -> bool { self.host_rules @@ -781,6 +830,10 @@ impl Interface { /// Removes the interface from the host. pub async fn remove(&self) { + #[cfg(windows)] + if let Some(gateway) = &self.forwarding { + gateway.configure(Vec::new()); + } // The route goes with the interface; the firewall rule does not, so // it is taken out explicitly while the interface is still known. if let Some(rules) = &self.host_rules { @@ -848,14 +901,14 @@ impl Interface { self.tally.wrong_source.fetch_add(1, Ordering::Relaxed); return Err(Rejected::WrongSource); }; - let (broadcast, exit) = match (origin, header.destination()) { + let (broadcast, exit, forwarded) = match (origin, header.destination()) { ( PacketSource::ExitReply { local: Some(local), exit, }, IpAddr::V4(destination), - ) if destination == local => (false, Some(exit)), + ) if destination == local => (false, Some(exit), false), (PacketSource::Member, IpAddr::V4(destination)) if self.routes.is_broadcast(destination) => { @@ -865,13 +918,17 @@ impl Interface { self.tally.broadcast_dropped.fetch_add(1, Ordering::Relaxed); return Err(Rejected::BroadcastDenied); } - (true, None) + (true, None, false) } (PacketSource::Member, IpAddr::V4(destination)) - if self.routes.is_local_destination(network, destination) - || self.routes.accepts_exit_traffic(network, destination) => + if self.routes.is_local_destination(network, destination) => { - (false, None) + (false, None, false) + } + (PacketSource::Member, IpAddr::V4(destination)) + if self.routes.accepts_exit_traffic(network, destination) => + { + (false, None, true) } _ => { self.tally.wrong_destination.fetch_add(1, Ordering::Relaxed); @@ -896,6 +953,20 @@ impl Interface { crate::vip::router::Decision::Drop => return Ok(()), crate::vip::router::Decision::Pass => packet, }; + // Only authenticated member traffic admitted by the exit policy can + // open a physical socket. A rejected allocation never falls through + // to Wintun, where the local upstream's split routes might recapture it. + #[cfg(not(windows))] + let _ = forwarded; + #[cfg(windows)] + if forwarded && let Some(gateway) = &self.forwarding { + if gateway.forward(Route { network, peer }, packet) { + self.tally.received.fetch_add(1, Ordering::Relaxed); + } else { + self.tally.undeliverable.fetch_add(1, Ordering::Relaxed); + } + return Ok(()); + } // Remote broadcasts terminate here. Only local TUN ingress can fan out. let len = packet.len() as u64; if self.device.send(packet).await.is_ok() { diff --git a/crates/tsunagi-core/src/overlay/mod.rs b/crates/tsunagi-core/src/overlay/mod.rs index b20f8a0..31f5f81 100644 --- a/crates/tsunagi-core/src/overlay/mod.rs +++ b/crates/tsunagi-core/src/overlay/mod.rs @@ -40,6 +40,8 @@ pub enum OverlayError { pub mod broadcast; pub mod config; +#[cfg(any(windows, test))] +mod egress; pub mod exit; pub mod hostrules; pub mod interface; diff --git a/crates/tsunagi-core/src/overlay/provision/linux.rs b/crates/tsunagi-core/src/overlay/provision/linux.rs index b26b9c3..065f2c8 100644 --- a/crates/tsunagi-core/src/overlay/provision/linux.rs +++ b/crates/tsunagi-core/src/overlay/provision/linux.rs @@ -55,7 +55,7 @@ use crate::BoxFuture; use crate::overlay::OverlayError; use super::super::config::Cidr; -use super::super::hostrules::linux_exit_mark::{UNDERLAY_MARK, UNDERLAY_MASK}; +use super::super::hostrules::linux_exit_mark::{EXIT_REPLY_MARK, UNDERLAY_MARK, UNDERLAY_MASK}; use super::super::tun::{TunDevice, TunRequest}; use super::privilege::{NetAdmin, Privilege, probe_net_admin}; use super::{ @@ -671,6 +671,7 @@ const EXIT_TABLE: u32 = 0x7473; /// The main table. const MAIN_TABLE: u32 = 254; /// Protect marked underlay and initial socket routing before Tailscale's rules. +const EXIT_REPLY_PRIORITY: u32 = 5204; const EXIT_MARK_PRIORITY: u32 = 5205; const EXIT_BYPASS_PRIORITY: u32 = 5206; const LEGACY_EXIT_BYPASS_PRIORITY: u32 = 5280; @@ -704,6 +705,15 @@ fn rule_priority(rule: &RuleMessage) -> Option { fn is_exit_rule(rule: &RuleMessage) -> bool { let table = rule_table(rule); match rule_priority(rule) { + Some(EXIT_REPLY_PRIORITY) => { + table == EXIT_TABLE + && rule + .attributes + .contains(&RuleAttribute::FwMark(EXIT_REPLY_MARK)) + && rule + .attributes + .contains(&RuleAttribute::FwMask(EXIT_REPLY_MARK)) + } Some(EXIT_MARK_PRIORITY) => { table == MAIN_TABLE && rule @@ -865,11 +875,11 @@ async fn replace_exit_default( /// ip rule add priority 5205 fwmark 0x40000000/0x40000000 lookup main /// ip rule add priority 5206 uidrange - lookup main /// ip rule add priority 5290 lookup main suppress_prefixlength 0 -/// ip rule add priority 5300 lookup 0x7473 +/// ip rule add priority 5300 iif lo lookup 0x7473 /// ``` /// /// and the same for IPv6 with `ip -6 route replace unreachable default table -/// 0x7473`, so that IPv6 is refused instead of leaving the ordinary way. +/// 0x7473` and no interface selector, so IPv6 is refused. /// /// 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 @@ -886,7 +896,24 @@ async fn set_exit_client( }; replace_exit_default(&handle, name, source).await?; - add_mark_bypass(&handle, false).await?; + if uid == 0 { + add_mark_rule( + &handle, + false, + EXIT_TABLE, + EXIT_REPLY_PRIORITY, + EXIT_REPLY_MARK, + ) + .await?; + } + add_mark_rule( + &handle, + false, + MAIN_TABLE, + EXIT_MARK_PRIORITY, + UNDERLAY_MARK, + ) + .await?; let mut bypass = handle .rule() @@ -930,6 +957,7 @@ async fn set_exit_client( .table_id(EXIT_TABLE) .action(RuleAction::ToTable) .priority(EXIT_DEFAULT_PRIORITY) + .input_interface("lo") .execute() .await .map_err(|err| fail("rule for the default route", err))?; @@ -960,7 +988,7 @@ async fn set_exit_block_v6(handle: &rtnetlink::Handle, uid: u32) -> Result<(), O }; } - add_mark_bypass(handle, true).await?; + add_mark_rule(handle, true, MAIN_TABLE, EXIT_MARK_PRIORITY, UNDERLAY_MARK).await?; let mut bypass = handle .rule() .add() @@ -1008,14 +1036,20 @@ async fn set_exit_block_v6(handle: &rtnetlink::Handle, uid: u32) -> Result<(), O .map_err(|err| fail("rule for the default route", err)) } -async fn add_mark_bypass(handle: &rtnetlink::Handle, v6: bool) -> Result<(), OverlayError> { +async fn add_mark_rule( + handle: &rtnetlink::Handle, + v6: bool, + table: u32, + priority: u32, + bit: u32, +) -> Result<(), OverlayError> { let mut rule = handle .rule() .add() - .table_id(MAIN_TABLE) + .table_id(table) .action(RuleAction::ToTable) - .priority(EXIT_MARK_PRIORITY) - .fw_mark(UNDERLAY_MARK); + .priority(priority) + .fw_mark(bit); rule.message_mut().header.family = if v6 { rtnetlink::packet_route::AddressFamily::Inet6 } else { @@ -1023,9 +1057,11 @@ async fn add_mark_bypass(handle: &rtnetlink::Handle, v6: bool) -> Result<(), Ove }; rule.message_mut() .attributes - .push(RuleAttribute::FwMask(UNDERLAY_MASK)); + .push(RuleAttribute::FwMask(bit)); rule.execute().await.map_err(|err| { - OverlayError::Unavailable(format!("cannot protect marked underlay traffic: {err}")) + OverlayError::Unavailable(format!( + "cannot add exit routing rule {priority} for mark {bit:#x}: {err}" + )) }) } diff --git a/crates/tsunagi-core/src/overlay/router.rs b/crates/tsunagi-core/src/overlay/router.rs index 43276b7..ed70687 100644 --- a/crates/tsunagi-core/src/overlay/router.rs +++ b/crates/tsunagi-core/src/overlay/router.rs @@ -304,11 +304,12 @@ impl RoutingTable { /// unicast destination, goes to this device's exit node when it has one: /// that is what sending *all* traffic through a member means. pub fn route(&self, destination: Ipv4Addr) -> Option { - self.packet_route(destination).map(|(route, _)| route) + self.packet_route(None, destination).map(|(route, _)| route) } pub(super) fn packet_route( &self, + source: Option, destination: Ipv4Addr, ) -> Option<(Route, Option>)> { let networks = self.read(); @@ -336,6 +337,14 @@ impl RoutingTable { return None; } let exit = self.selected_exit.load_full()?; + // The host's default route may hand a forwarded packet back to the TUN. + // Only this device can originate traffic for its own upstream. Replies + // to a member above still route by destination with their internet source. + if let Some(source) = source + && networks.get(&exit.route.network)?.local != Some(source) + { + return None; + } Some((exit.route, Some(exit))) } diff --git a/crates/tsunagi-wg-quic/tests/exit_node.rs b/crates/tsunagi-wg-quic/tests/exit_node.rs index b64f310..f2d045d 100644 --- a/crates/tsunagi-wg-quic/tests/exit_node.rs +++ b/crates/tsunagi-wg-quic/tests/exit_node.rs @@ -216,6 +216,65 @@ impl<'a> ExitNetwork<'a> { } } +#[tokio::test] +async fn an_exit_keeps_serving_its_client_while_switching_its_own_upstream() { + let discovery = SharedMemoryDiscovery::new(); + let (name, secret) = network("independent-exits"); + let a = Node::spawn(&discovery, "client-a").await; + let b = Node::spawn(&discovery, "gateway-b").await; + let c = Node::spawn(&discovery, "upstream-c").await; + let net = b.agent.join_network(&name, &secret).await.unwrap(); + b.overlay(net).await; + b.agent.set_exit_offer(net, true).await.unwrap(); + a.agent.join_network(&name, &secret).await.unwrap(); + c.agent.join_network(&name, &secret).await.unwrap(); + c.agent.set_exit_offer(net, true).await.unwrap(); + wait_until("both exit offers have reached their clients", || async { + let offers = |status: NetworkStatus, id| { + status + .peers + .iter() + .any(|p| p.endpoint_id == id && p.exit_node) + }; + (offers(a.status(net).await, b.id()) && offers(b.status(net).await, c.id())).then_some(()) + }) + .await; + tokio::join!( + a.wait_for_tunnels(net, 2), + b.wait_for_tunnels(net, 2), + c.wait_for_tunnels(net, 2) + ); + a.agent.set_exit_via(net, Some(b.id())).await.unwrap(); + let (at, bt, ct) = (a.tun().await, b.tun().await, c.tun().await); + let (aa, ba) = (a.overlay(net).await, b.overlay(net).await); + for (epoch, upstream) in [false, true, false, true].into_iter().enumerate() { + b.agent + .set_exit_via(net, upstream.then(|| c.id())) + .await + .unwrap(); + // A retains the same pair of endpoints before, during and after B uses C. + let request = ipv4_packet(aa, INTERNET, &[epoch as u8]); + at.push_from_os(request.clone()); + assert_eq!(next(&bt).await, request); + if upstream { + // Even a misrouted host packet from A cannot be carried a second time. + bt.push_from_os(request); + let own = ipv4_packet(ba, INTERNET, b"B to the same server"); + bt.push_from_os(own.clone()); + assert_eq!(next(&ct).await, own); + let reply = ipv4_packet(INTERNET, ba, b"reply to B"); + ct.push_from_os(reply.clone()); + assert_eq!(next(&bt).await, reply); + } + let reply = ipv4_packet(INTERNET, aa, &[epoch as u8]); + bt.push_from_os(reply.clone()); + assert_eq!(next(&at).await, reply); + assert_eq!(a.status(net).await.exit_via, Some(b.id())); + assert!(b.status(net).await.exit_offer); + } + let _ = tokio::join!(a.shutdown(), b.shutdown(), c.shutdown()); +} + #[tokio::test] async fn switching_the_exit_between_networks_keeps_both_overlays_reachable() { let discovery = SharedMemoryDiscovery::new(); diff --git a/docs/exit-node.md b/docs/exit-node.md index 629233a..fdfa5d8 100644 --- a/docs/exit-node.md +++ b/docs/exit-node.md @@ -4,6 +4,11 @@ A member can offer itself as an **exit node** in a network. Other members can then send their default IPv4 internet traffic through it. Linux, macOS and Windows can offer or use an exit node. Android can use one. +An exit serves members through its own internet connection even while its local +applications use another exit. If A selects B and B selects C, the same website +sees B for requests from A and C for requests from B. Changing B’s selection +keeps established connections from A on B’s original egress. + ## Using it The offering side, per network, off by default: @@ -12,8 +17,7 @@ The offering side, per network, off by default: tsng network exit-node on # or off ``` -Rules are installed even when the kernel does not forward yet, and `status` -says so. Turning forwarding on is left to you, on purpose: +Linux and macOS report kernel forwarding in `status`. To enable it on Linux: ```sh sudo sysctl -w net.ipv4.ip_forward=1 @@ -57,7 +61,13 @@ subnet is dropped locally. Offering an exit remains a per-network choice. lookup main` and `5206 uidrange lookup main` keep the agent's sockets and their replies outside the tunnel, before Tailscale's rules. `5290 lookup main suppress_prefixlength 0` preserves LAN and other specific - routes, and `5300 lookup 29811` directs other traffic through the exit. + routes, and `5300 iif lo lookup 29811` directs locally originated + IPv4 traffic through the exit. Forwarded member packets and their SNAT + replies carry the agent’s underlay bit, including during strict reverse-path + checks. Their conntrack entries live independently of B’s exit selection. + When the daemon runs as root, rule `5204` directs reverse lookups for + authenticated replies to local exit-client connections back to the overlay + using the independent packet-mark bit `0x20000000`. The exit table is `29811` (`0x7473`). - **Linux reverse-path filtering:** only the agent's dedicated UID is marked in mangle `OUTPUT`. Its own bit, `0x40000000`, is saved to conntrack and @@ -99,7 +109,9 @@ is built from `pf` and `route`. The agent runs as root there. - **Offering:** a `pf` anchor `com.apple/tsunagi-exit-` (the stock `/etc/pf.conf` already evaluates `com.apple/*`) holds - `nat on from to any -> ()` and a `pass in` rule. + `nat on from to any -> ()` and tags packets entering 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. `pf` is enabled if it was off, and that reference is released when the rules go. Forwarding is only read: `sudo sysctl -w net.inet.ip.forwarding=1`, which macOS forgets at reboot. The egress is the default route's interface **at the @@ -122,13 +134,15 @@ is built from `pf` and `route`. The agent runs as root there. ## Windows -- **Offering:** each offered range gets a WinNAT object - `tsunagi-exit::` (`New-NetNat`), removed with the offer, the - network and the agent. Forwarding is read for the overlay interface and never - changed; Windows forwards per interface, so enable it on the ones involved - (`Get-NetIPInterface | Set-NetIPInterface -Forwarding Enabled`, administrator - PowerShell). Some Windows versions allow one NAT per host; a second range then - reports its own failure. +- **Offering** uses IPv4 sockets bound to the physical adapter index and + address (`IP_UNICAST_IF`). A bounded smoltcp stack handles the member-facing + TCP connection and passes stream data and half-closes in both directions. + Each UDP flow keeps its physical source port for two minutes of inactivity. + ICMP echo uses a physically bound raw socket. Fragmented IPv4 datagrams are + reassembled before transport processing and replies are split to the mesh + MTU. Other IPv4 protocols and new connections above the shared limit of 256 + are dropped. Legacy Tsunagi WinNAT objects are cleaned up on startup. The + Windows offer works with kernel IP forwarding disabled. - **Using:** Windows has no per-user routing, so the agent's own traffic is kept 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") diff --git a/docs/testing.md b/docs/testing.md index 9b3dc8e..ba1b4f5 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -211,6 +211,16 @@ atomic rollback. The CLI test starts two real agent processes and exercises offline cleanup by network and hostname through the control socket. Native tray rendering and physical screen sizing are not exercised automatically. +The three-agent exit test delivers A’s traffic to B before, during and after B +chooses C, including both agents contacting the same address. The isolated Linux +kernel test `serving_an_established_flow_while_switching_the_local_exit` uses +network namespaces and keeps a real TCP connection open across both switches. +On disposable macOS and Windows runners the native subnet workflow checks the +same-destination split on two utuns or two Wintun adapters. Its macOS test +requires IPv4 forwarding enabled. Windows userspace forwarding also has +ordinary loopback tests for TCP resets, half-closes, UDP port stability and +connection limits. + Linux exit-client unit tests cover preservation of foreign mark bits, matching only the agent's UID and locally owned TCP/UDP sockets, exact tagged cleanup, partial IPv6 failure and mark-aware strict kernel RPF validation. The ignored