Compare commits

..
14 Commits
Author SHA1 Message Date
Aleksandr Bogomiakov a189d0ad3e Preserve mesh transport through an internet exit in 1.0.3-rc1
On macOS a connected socket using the physical source lost its route before
PF could see the packet. Fresh sockets could leave via the physical uplink,
but Darwin rejected reverse-NAT replies delivered to a utun address there.
With two live meshes remote control and data sessions expired within a minute.

Install matching interface-scoped uplink routes before capturing the two
unscoped defaults. Keep PF state on the physical interface, preserve transport
ports and return tagged replies via loopback. Reconcile uplink changes and
recover only owned routes using a private journal and kernel markers. On
Windows keep existing LAN routes, retain recent verified reconnect paths and
refresh the gateway and relay DNS without replacing the split defaults.

Exercise two memberships of the same peer, new and established native
transport sockets, ordinary application traffic and scoped route cleanup.
Run hosted macOS and Windows native regressions on affected changes. Bump the
packages to 1.0.3-rc1 and encode Debian prereleases with a tilde so apt can
upgrade to the final release. Mesh wire formats and identities are unchanged.

Checked workspace formatting, strict Clippy and the full workspace suite on
macOS (586 passed, four opt-in tests skipped by default). The privileged macOS
kernel test passed separately. A launchd trial of the RC kept master and ch
reachable over both meshes and used the external exit past the original
timeout. Disabling the exit restored the physical IP and cleared the routes.
Linux ARM64 passed four real-agent exit tests and the privileged netns
regression. The RC APK passed the dual-subnet UDP/ICMP test on an Android 37
ARM64 emulator. Verified Debian and pacman version ordering. Native Windows
execution is covered by the hosted workflow and was not run on this Mac.
2026-11-25 03:47:49 +02:00
Aleksandr Bogomiakov 32aa73721a Keep every active mesh reachable through a single internet exit
With several IPv4 aliases on a single TUN, the default route could select an address from a different mesh. The exit peer then rejected internet traffic as an invalid source. Concurrent cross-network exit selections could also clear each other in the running agent while SQLite kept one winner.

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

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

On macOS, formatting and strict workspace Clippy passed. The full locked workspace suite passed 577 tests with three ignored, after correcting a stale Windows script-test matcher. Three real agents covered switching, concurrent selection, offline isolation and restart. On Linux arm64, 88 focused tests and the privileged kernel routing/firewall test passed. The Android arm64 library built and linked. Wintun and privileged macOS utun were not exercised on live hosts.
2026-11-25 02:32:09 +02:00
Aleksandr Bogomiakov 21b8381fa3 Restore Homebrew publication after stable GitHub releases
The v1.0.2 build published a valid macOS archive, but its release workflow lacked the Homebrew job that published v1.0.0. Restore the job, updater, tests and setup notes from a707076 alongside the existing Arch and OpenArtifact jobs.

Verify the Apple Silicon archive against the published GitHub digest before updating the CLI formula and GUI cask in one tap commit. Skip prereleases and older versions, and retry from the current tap head after a concurrent push. Use the existing HOMEBREW_TAP_TOKEN with the same tap and branch.

On macOS, all three updater tests passed. Exercised the workflow shell with the real v1.0.2 archive, mocked release transport and a local Git remote, including checksum rejection, concurrent updates and retries. Actionlint and ShellCheck passed with the old actionlint runner list exception for ubuntu-26.04. Workspace formatting and strict Clippy passed. All 568 default tests passed with three ignored after enabling loopback for the test run. No live workflow was triggered.
2026-11-25 01:11:33 +02:00
Aleksandr Bogomiakov ee77ddb9ac Prepare the 1.0.2 release
Set package versions and internal dependency requirements to 1.0.2 throughout the workspace, lockfile, Android app and Nix package. The optional link comparison uses the existing mesh wire versions. Upgrade the CLI and tray with the local agent for IPC v24.

Checked locked Cargo metadata and tsng --version. Workspace formatting and strict Clippy passed on macOS, and 568 tests passed with three opt-in checks skipped by default. Native elevated macOS utun and Windows Wintun source selection passed on hosted runners. Verified Linux kernel source selection in a disposable network namespace and bidirectional UDP and system ping on an Android API 37 ARM64 emulator.
2026-11-25 00:12:11 +02:00
Aleksandr Bogomiakov 219bd018db Let healthy carrier comparisons recover from startup probe loss
The first probe on a newly opened carrier can precede the responder’s private health profile. Keep measuring for up to 30 seconds if the 20-probe window still contains losses or too few samples. A clean link still qualifies after six seconds. The ordinary 60-percent link failure detector continues to count every missed probe.

Tested the acquisition, recovery, insufficient data and persistent-loss decisions. The slow TLS and fast QUIC loopback fixture can expose its measurements through the existing test logging switch. Workspace Clippy and formatting passed.
2026-11-25 00:09:53 +02:00
Aleksandr Bogomiakov 15a4e45710 Prioritize live traffic recovery over a stalled carrier comparison
When the incumbent went down during a background dial, an unrelated healthy third carrier could wait up to 30 seconds. Restore the configured fallback order immediately if another carrier is eligible. Cancel the pending dial and invalidate its result so a late link cannot overwrite recovery. Keep the comparison alive if it is the only available fallback.

Reproduced the timeout with two loopback agents, a real WG carrier, a stalled TLS handshake and QUIC. All four carrier integration tests passed after the change, including bidirectional delivery over the recovered path. Workspace formatting and Clippy passed on macOS.
2026-11-25 00:05:51 +02:00
Aleksandr Bogomiakov 972b98363d Restore the socket source address across Android mesh networks
Android VpnService routes can select the primary VPN address for traffic to a second subnet even when both aliases are installed. Keep a bounded binding at the local TUN boundary so the peer receives the source it owns in that network and the original Android socket receives the reply. Preserve native primary traffic, separate per-subnet capacity, handle fragmented IPv4 and quoted ICMP errors, and retain eligible bindings when VpnService replaces its descriptor.

Support TCP, UDP and ICMP echo. An ambiguous tuple retains its original binding. Explicitly bound traffic for other IPv4 protocols passes using the proper network address. Mesh authentication, address admission and wire formats stay unchanged.

Reproduced the wrong source on a disposable Android API 37 ARM64 emulator. After the fix, system ping and an unbound connected UDP socket both received replies across each real VPN subnet. Built both debug APKs and confirmed that only the instrumentation APK includes its helper. Eleven focused Rust checks cover reverse mapping, checksums, fragments, limits and reconfiguration.
2026-11-25 00:03:02 +02:00
Aleksandr Bogomiakov 2e83483f00 Restore Windows native test compilation
The real Wintun check exposed three Windows-only test calls that predated the access argument to ControlSocket::bind. Pass Private for these isolated named pipes, matching the Unix fixtures. Run native subnet checks for edits to the underlying TUN implementation as well.

Confirmed the first hosted Windows compilation failed on exactly these calls. The revised Windows checks run on the hosted runner. Production IPC behavior is unchanged.
2026-11-25 00:00:16 +02:00
Aleksandr Bogomiakov 27e29cf8a7 Keep concurrent overlays working and select faster data carriers
A second subnet on macOS could send with the first utun alias. Reconcile and verify each owned subnet route with its actual source, retry partially applied plans and expose host errors to clients. On Windows verify the alias and prefix on the intended adapter. Do not restart underlay sockets when the only network change is a local overlay address.

Compare mutually enabled carriers using authenticated data probes while the incumbent carries traffic. The dialler coordinates a generation-scoped decision after a sustained median RTT improvement. Old peers retain ordered fallback. Local IPC moves to v24 to report data RTT and the physical path independently of control RTT. The mesh wire versions, keys and saved network settings stay compatible.

Validated formatting, workspace Clippy and the workspace test suite on macOS, including bidirectional dual-network traffic and a live TLS-to-QUIC switch on loopback. Added focused native CI tests for macOS and Windows. The elevated utun test requires administrative access unavailable on the development host.
2026-11-24 23:55:55 +02:00
Aleksandr Bogomiakov 8d107cf0e9 Declare installer and tray dependencies in Linux packages
Require adduser on Debian and shadow on Arch for the package installation hooks. For GUI packages, derive the minimum glibc version from the tray ELF imports so the dependency follows the binary built by each runner.

Checked generated Debian control files and Arch package metadata for both variants on macOS using the released tray binary (glibc 2.43). Checked shell syntax; no Rust changes or release rebuild.
2026-11-24 22:11:42 +02:00
Aleksandr Bogomiakov 01b51081c3 Publish pacman packages with the version from PKGINFO
OpenArtifact validates the upload path against the full Arch package version. Keep the release assets as built and derive the registry filename, including its epoch, from the package metadata. Duplicate checks use the same URL.

Checked actionlint, Bash syntax and the upload paths for all four SHA-256-verified v1.0.1 Arch release assets.
2026-11-24 21:44:03 +02:00
Aleksandr Bogomiakov d72e8886d6 Restore GitHub-hosted macOS release builds
Restore the release workflow from before the temporary laptop runner was introduced. The Apple Silicon build uses macos-latest again, and release publication continues to target GitHub and OpenArtifact.

Verified the workflow matches 04b5ebc byte for byte, validated the macOS matrix and publication job, and ran actionlint with its outdated Ubuntu 26.04 label check excluded.
2026-11-24 21:25:02 +02:00
Aleksandr Bogomiakov e3a86aa9d3 Prepare the 1.0.1 release
Align the workspace package versions and internal requirements, lockfile, Nix package and Android default version name with the release tag.

Validated on Apple Silicon with cargo fmt, clippy and all workspace targets (547 tests passed, 2 ignored). Built the release CLI and tray, checked the CLI version and verified the ad hoc signature of the packaged macOS application.
2026-11-24 21:21:30 +02:00
Aleksandr Bogomiakov 42c25f29ec Prefer a self-hosted Apple Silicon runner for GitHub releases
Select the macOS runner before creating the release build matrix. Default to a self-hosted ARM64 Mac. With a repository runner-status credential, choose GitHub-hosted macOS when no matching runner is online and idle or when the lookup fails. MACOS_USE_HOSTED can force the hosted pool. Limit build jobs to read-only contents.

Validated the workflow with actionlint (its bundled label list predates the existing Ubuntu 26.04 jobs) and exercised the online, offline, busy, mismatched-label, missing-token, API-error and hosted-override cases.
2026-11-24 21:17:47 +02:00
80 changed files with 5966 additions and 707 deletions

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
import tempfile
import unittest
from pathlib import Path
from update_homebrew import update_tap
class UpdateTapTest(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
self.tap = Path(directory.name)
self.formula = self.tap / "Formula/tsunagi.rb"
self.cask = self.tap / "Casks/tsunagi-gui.rb"
self.formula.parent.mkdir()
self.cask.parent.mkdir()
self.old_hash = "a" * 64
self.new_hash = "b" * 64
self.formula.write_text(f' VERSION = "1.9.0"\n SHA256 = "{self.old_hash}"\n')
self.cask.write_text(f' version "1.9.0"\n sha256 "{self.old_hash}"\n')
def test_updates_both_packages_and_allows_retry(self):
for _ in range(2):
update_tap(self.tap, "v1.10.0", self.new_hash)
self.assertEqual(self.formula.read_text(), f' VERSION = "1.10.0"\n SHA256 = "{self.new_hash}"\n')
self.assertEqual(self.cask.read_text(), f' version "1.10.0"\n sha256 "{self.new_hash}"\n')
def test_older_release_does_not_replace_either_package(self):
before = self.formula.read_bytes(), self.cask.read_bytes()
update_tap(self.tap, "v1.8.9", self.new_hash)
self.assertEqual((self.formula.read_bytes(), self.cask.read_bytes()), before)
def test_invalid_release_or_cask_leaves_formula_untouched(self):
before = self.formula.read_bytes()
with self.assertRaises(ValueError):
update_tap(self.tap, "v1.10.0-rc.1", self.new_hash)
with self.assertRaises(ValueError):
update_tap(self.tap, "v1.10.0", "invalid")
self.cask.write_text(' version "1.9.0"\n')
with self.assertRaises(ValueError):
update_tap(self.tap, "v1.10.0", self.new_hash)
self.assertEqual(self.formula.read_bytes(), before)
+51
View File
@@ -0,0 +1,51 @@
"""Update the tap's formula and cask for a verified macOS release archive."""
import argparse
import re
from pathlib import Path
VERSION = r"(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*)){2}"
SHA256 = r"[0-9a-f]{64}"
def update_tap(tap: Path, tag: str, checksum: str) -> None:
if not re.fullmatch(f"v{VERSION}", tag):
raise ValueError("expected a stable vMAJOR.MINOR.PATCH release")
if not re.fullmatch(SHA256, checksum):
raise ValueError("expected a SHA-256 digest")
version = tag[1:]
updates = {}
for filename, version_field, hash_field in (
("Formula/tsunagi.rb", "VERSION = ", "SHA256 = "),
("Casks/tsunagi-gui.rb", "version ", "sha256 "),
):
path = tap / filename
original = path.read_text()
version_pattern = rf'^( {version_field}")({VERSION})(")$'
hash_pattern = rf'^( {hash_field}")({SHA256})(")$'
current = re.findall(version_pattern, original, re.MULTILINE)
if len(current) != 1 or len(re.findall(hash_pattern, original, re.MULTILINE)) != 1:
raise ValueError(f"expected one version and one SHA-256 in {filename}")
if tuple(map(int, version.split("."))) < tuple(map(int, current[0][1].split("."))):
print(f"Skipping older release {tag}: {filename} already has {current[0][1]}")
return
updated = re.sub(version_pattern, rf"\g<1>{version}\g<3>", original, flags=re.MULTILINE)
updated = re.sub(hash_pattern, rf"\g<1>{checksum}\g<3>", updated, flags=re.MULTILINE)
updates[path] = (original, updated)
for path, (original, updated) in updates.items():
if updated != original:
path.write_text(updated)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("tap", type=Path)
parser.add_argument("tag")
parser.add_argument("checksum")
args = parser.parse_args()
try:
update_tap(args.tap, args.tag, args.checksum)
except (OSError, ValueError) as error:
parser.exit(1, f"{error}\n")
+3 -1
View File
@@ -2,7 +2,7 @@ name: CI
on:
push:
branches: [main]
branches: [master, main]
pull_request:
workflow_dispatch:
@@ -25,6 +25,8 @@ jobs:
- uses: Swatinem/rust-cache@v2
- run: cargo fmt --all -- --check
- run: cargo clippy --locked --workspace --all-targets -- -D warnings
- name: Check Debian release candidate upgrade ordering
run: bash dist/deb/test-deb.sh
test:
name: test (${{ matrix.os }})
+101 -3
View File
@@ -412,6 +412,99 @@ jobs:
'{event_type: "new_package", client_payload: {repository: $repository, tag: $tag}}' \
| gh api --method POST repos/house-of-vanity/arch_repo/dispatches --input -
update-homebrew:
name: Update the Homebrew tap
needs: publish
if: github.server_url == 'https://github.com' && github.repository == 'house-of-vanity/tsunagi'
runs-on: ubuntu-latest
permissions:
contents: read
env:
RELEASE_TAG: ${{ github.ref_name }}
steps:
- name: Check the release tag and tap credentials
id: stable
env:
TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
run: |
set -euo pipefail
if [[ ! "$RELEASE_TAG" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then
echo "Skipping Homebrew for non-stable tag $RELEASE_TAG"
exit 0
fi
if [[ -z "$TAP_TOKEN" ]]; then
echo '::error::Set HOMEBREW_TAP_TOKEN with Contents: write access to house-of-vanity/homebrew-tap.'
exit 1
fi
echo "publish=true" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@v5
if: steps.stable.outputs.publish == 'true'
with:
persist-credentials: false
- name: Verify the published macOS archive
if: steps.stable.outputs.publish == 'true'
id: archive
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
archive="tsunagi-macos-aarch64-${RELEASE_TAG#v}.tar.gz"
digest=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$RELEASE_TAG" \
| jq -er --arg archive "$archive" '
select(.draft == false and .prerelease == false)
| .assets[] | select(.name == $archive and .state == "uploaded")
| .digest | select(type == "string" and test("^sha256:[0-9a-f]{64}$"))
')
gh release download "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \
--pattern "$archive" --dir "$RUNNER_TEMP"
hash="${digest#sha256:}"
actual=$(sha256sum "$RUNNER_TEMP/$archive")
if [[ "${actual%% *}" != "$hash" ]]; then
echo "::error::SHA-256 mismatch for $archive."
exit 1
fi
echo "hash=$hash" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@v5
if: steps.stable.outputs.publish == 'true'
with:
repository: house-of-vanity/homebrew-tap
ref: main
path: homebrew-tap
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
- name: Update and push the formula and cask
if: steps.stable.outputs.publish == 'true'
env:
ARCHIVE_SHA256: ${{ steps.archive.outputs.hash }}
run: |
set -euo pipefail
# Retry from the latest tap state if another publisher pushes first.
for attempt in 1 2 3; do
git -C homebrew-tap fetch origin main
git -C homebrew-tap checkout --detach --force FETCH_HEAD
python3 .github/scripts/update_homebrew.py homebrew-tap "$RELEASE_TAG" "$ARCHIVE_SHA256"
cd homebrew-tap
ruby -c Formula/tsunagi.rb
ruby -c Casks/tsunagi-gui.rb
if git diff --quiet -- Formula/tsunagi.rb Casks/tsunagi-gui.rb; then
exit 0
fi
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
git add -- Formula/tsunagi.rb Casks/tsunagi-gui.rb
git commit -m "tsunagi ${RELEASE_TAG#v}"
if git push origin HEAD:main; then
exit 0
fi
echo "Push to the Homebrew tap failed on attempt $attempt of 3." >&2
cd ..
done
echo '::error::Could not push the updated formula and cask to the tap.'
exit 1
publish-openartifact:
name: Publish APT and pacman packages
needs: publish
@@ -455,9 +548,14 @@ jobs:
"$OA_SERVER/api/v1/repositories/hexor-apt/debs")
;;
*.pkg.tar.zst)
stem=${name%.pkg.tar.zst}
arch=${stem##*-}
url="$OA_SERVER/repos/hexor-pacman/os/$arch/$name"
# Release asset names omit the epoch. OpenArtifact matches the
# upload path against the full version recorded in .PKGINFO.
pkginfo=$(tar --zstd -xOf "$file" .PKGINFO)
pkg=$(sed -n 's/^pkgname = //p' <<< "$pkginfo")
version=$(sed -n 's/^pkgver = //p' <<< "$pkginfo")
arch=$(sed -n 's/^arch = //p' <<< "$pkginfo")
: "${pkg:?missing pkgname}" "${version:?missing pkgver}" "${arch:?missing arch}"
url="$OA_SERVER/repos/hexor-pacman/os/$arch/$pkg-$version-$arch.pkg.tar.zst"
status=$(curl -sS -o "$RUNNER_TEMP/oa-upload.json" -w '%{http_code}' \
"${auth[@]}" -T "$file" "$url")
;;
+94
View File
@@ -0,0 +1,94 @@
name: Native subnet source selection
on:
push:
branches: [master]
paths:
- '.github/workflows/subnet-source.yml'
- 'crates/tsunagi-core/src/overlay/hostrules/macos*.rs'
- 'crates/tsunagi-core/src/overlay/hostrules/windows*.rs'
- 'crates/tsunagi-core/src/overlay/provision/macos.rs'
- 'crates/tsunagi-core/src/overlay/provision/windows.rs'
- 'crates/tsunagi-core/src/overlay/provision/mod.rs'
- 'crates/tsunagi-core/src/overlay/provision/factory.rs'
- 'crates/tsunagi-core/src/overlay/tun.rs'
- 'crates/tsunagi-core/src/net.rs'
workflow_dispatch:
permissions:
contents: read
jobs:
source:
if: github.server_url == 'https://github.com'
runs-on: ${{ matrix.os }}
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
include:
- os: macos-latest
test: overlay::provision::macos::tests::unbound_sockets_choose_each_networks_source_on_one_real_utun
- os: windows-latest
test: overlay::provision::windows::tests::two_windows_subnets_choose_their_own_source_and_survive_removal
env:
TEST_NAME: ${{ matrix.test }}
CARGO_PROFILE_TEST_DEBUG: '0'
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build and locate the native test
shell: pwsh
run: |
$artifacts = @(cargo test --locked -p tsunagi-core --lib --features tun-device --no-run --message-format=json-render-diagnostics |
ForEach-Object { ConvertFrom-Json -InputObject $_ } |
Where-Object { $_.reason -eq 'compiler-artifact' -and $_.target.name -eq 'tsunagi' -and $_.profile.test -and $_.executable })
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
if ($artifacts.Count -ne 1) { throw "Expected one core test binary, found $($artifacts.Count)" }
$binary = $artifacts[0].executable
$tests = @(& $binary --ignored --exact $env:TEST_NAME --list)
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 source selection on a real utun
if: runner.os == 'macOS'
shell: bash
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
- name: Verify exit routing and PF translation on two real utuns
if: runner.os == 'macOS'
shell: bash
timeout-minutes: 2
env:
EXIT_TEST: overlay::hostrules::macos_exit::kernel::exit_preserves_underlay_and_both_meshes
run: |
"$TEST_BINARY" --ignored --exact "$EXIT_TEST" --list | grep -Fx "$EXIT_TEST: test"
sudo -n -- "$TEST_BINARY" --ignored --exact "$EXIT_TEST" --nocapture
- name: Verify source selection on a real Wintun adapter
if: runner.os == 'Windows'
shell: pwsh
run: |
$zip = Join-Path $env:RUNNER_TEMP 'wintun.zip'
Invoke-WebRequest -Uri https://www.wintun.net/builds/wintun-0.14.1.zip -OutFile $zip
# This is the signed Wintun distribution pinned by the Windows installer.
if ((Get-FileHash $zip -Algorithm SHA256).Hash -ne '07C256185D6EE3652E09FA55C0B673E2624B565E02C4B9091C79CA7D2F24EF51') {
throw 'Unexpected Wintun archive checksum'
}
$directory = Join-Path $env:RUNNER_TEMP 'wintun-dl'
Expand-Archive -Path $zip -DestinationPath $directory
Copy-Item (Join-Path $directory 'wintun/bin/amd64/wintun.dll') (Split-Path -Parent $env:TEST_BINARY)
& $env:TEST_BINARY --ignored --exact $env:TEST_NAME --nocapture
exit $LASTEXITCODE
- name: Verify one Windows exit bypass route through the physical gateway
if: runner.os == 'Windows'
shell: pwsh
timeout-minutes: 2
run: |
$test = 'overlay::hostrules::windows_exit::tests::windows_refresh_installs_only_the_external_test_address'
$listing = @(& $env:TEST_BINARY --ignored --exact $test --list)
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
if ($listing -notcontains "${test}: test") { throw "Missing ignored test: $test" }
& $env:TEST_BINARY --ignored --exact $test --nocapture
exit $LASTEXITCODE
Generated
+11 -10
View File
@@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tsunagi"
version = "1.0.0"
version = "1.0.3-rc1"
dependencies = [
"anstream",
"anstyle",
@@ -6320,7 +6320,7 @@ dependencies = [
[[package]]
name = "tsunagi-android"
version = "1.0.0"
version = "1.0.3-rc1"
dependencies = [
"bytes",
"egui",
@@ -6344,7 +6344,7 @@ dependencies = [
[[package]]
name = "tsunagi-awg"
version = "1.0.0"
version = "1.0.3-rc1"
dependencies = [
"bytes",
"iroh",
@@ -6359,7 +6359,7 @@ dependencies = [
[[package]]
name = "tsunagi-core"
version = "1.0.0"
version = "1.0.3-rc1"
dependencies = [
"arc-swap",
"bytes",
@@ -6384,6 +6384,7 @@ dependencies = [
"serde",
"sha2",
"simple-dns",
"smoltcp",
"subtle",
"tempfile",
"thiserror 2.0.20",
@@ -6401,7 +6402,7 @@ dependencies = [
[[package]]
name = "tsunagi-runtime"
version = "1.0.0"
version = "1.0.3-rc1"
dependencies = [
"tokio",
"tracing",
@@ -6414,7 +6415,7 @@ dependencies = [
[[package]]
name = "tsunagi-tcp-tls"
version = "1.0.0"
version = "1.0.3-rc1"
dependencies = [
"bytes",
"caps",
@@ -6434,7 +6435,7 @@ dependencies = [
[[package]]
name = "tsunagi-tray"
version = "1.0.0"
version = "1.0.3-rc1"
dependencies = [
"eframe",
"egui-phosphor",
@@ -6450,7 +6451,7 @@ dependencies = [
[[package]]
name = "tsunagi-ui"
version = "1.0.0"
version = "1.0.3-rc1"
dependencies = [
"egui",
"egui-phosphor",
@@ -6460,7 +6461,7 @@ dependencies = [
[[package]]
name = "tsunagi-wg-quic"
version = "1.0.0"
version = "1.0.3-rc1"
dependencies = [
"boringtun",
"bytes",
@@ -6487,7 +6488,7 @@ dependencies = [
[[package]]
name = "tsunagi-wireguard"
version = "1.0.0"
version = "1.0.3-rc1"
dependencies = [
"boringtun",
"bytes",
+12 -4
View File
@@ -114,15 +114,18 @@ explicit Save. [Commands, health, metrics and limits](docs/vip.md).
```sh
tsng network exit-node home on # on the machine that should be the exit
tsng exit-node # on another one: who offers an exit
tsng exit-node laptop # send everything through it
tsng exit-node laptop # send internet traffic through it
tsng exit-node off
```
One exit serves the whole agent. Peers in every active Tsunagi network stay
reachable on their own mesh routes.
The tray does the same with a checkbox. An exit node sees everything you send
through it, so use only members you trust.
[Details and per-OS notes](docs/exit-node.md).
The default data transport order is `wg,awg,wg-quic,tcp-tls`. AWG negotiates a
The initial data transport order is `wg,awg,wg-quic,tcp-tls` by default. AWG negotiates a
fresh masking profile and outer keys for each pair connection attempt, including
reentry after fallback. Sustained data loss triggers switching independently of
the iroh control connection. [Configuration and limits](docs/amnezia.md).
@@ -132,14 +135,19 @@ Change a network's protocol selection without editing its service or restarting:
```sh
tsng protocols # available protocols and settings
tsng protocols home # this device's choice for home
tsng protocols home awg,wg-quic # prefer AWG, retain QUIC as fallback
tsng protocols home awg,wg-quic # enable AWG and QUIC, try AWG first
tsng protocols home none # control plane only
```
Exact network names, full ids and unique id prefixes work here. The choice is
local to this device, saved per network and applied immediately; an offline
change applies on the next start. In the tray, expand **data transports** on a network
tile to toggle protocols or change their preference order. Adjacent peers need a common external transport at the same wire version.
tile to enable transports and set their initial preference order. Adjacent peers need a common external transport at the same wire version.
Peers that both support link comparison probe another mutually enabled transport
while traffic continues on the current one. They can switch to a faster healthy link.
`tsng status` and the tray show the direct data link's measured RTT separately
from the control connection's RTT. A mesh relay's first-hop RTT cannot measure
the round trip to the destination.
Selection applies to this device's incoming and outgoing data links; control and
discovery are independent. A relay's next hop may use a different transport.
Every pair uses one internal WireGuard cipher, hidden from these controls.
+15 -1
View File
@@ -20,11 +20,25 @@ Open **tsunagi**, tap **Start VPN**, accept Android’s VPN prompt, then join wi
The Rust agent owns one interface across the active networks. The Android service establishes the TUN and supplies its descriptor when addresses or exit routes change. Discovery and transport sockets use the selected physical network. TCP health checks bind to the VPN and the address of their own mesh network. The per-network transport selector offers `wg`, `awg`, `wg-quic` and `tcp-tls` in the same default order as the desktop. Each network retains its saved selection and priority. An advertised remote exit can carry the phone’s IPv4 internet traffic.
When Android chooses the first VPN address for a connection to another mesh, tsunagi translates TCP, UDP and ICMP echo traffic to that mesh’s address and returns replies to the original socket. Applications using other IPv4 protocols should bind to the address of their target mesh. If two sockets would use the same addresses, ports and protocol on the wire, the existing flow keeps its binding.
Applications using Android’s system resolver can connect to `<member>.<network>` and `<vip>.<network>`, for example `k8s.tsng:6443`. The VPN answers UDP and TCP DNS questions locally using the same signed roster and service records as the desktop. Unknown names in a joined mesh receive an authoritative negative answer. Other names go to Android’s resolver on the underlying Wi-Fi or cellular network, including while using a remote exit. Android 10 and later support arbitrary external DNS record types. On Android 8 and 9 the system lookup API supplies external A and AAAA records.
The tray and Android use the same egui network tiles, join form, device list, VIP editor and live traffic diagram from `crates/tsunagi-ui`. On Android, the Rust activity view opens each form in the current viewport. Kotlin handles the service, connectivity, rendering surface, input and clipboard.
Open **Exit node…** on a network tile to compare remote gateways by control RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
Open **Exit node…** on a network tile to compare remote gateways by measured data RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
## Check two networks on an emulator
Use a disposable ARM64 emulator. The test establishes a temporary VPN, sends UDP and system pings through the production TUN adapter to a local echo peer in each subnet, and checks that the originating applications receive their replies. Set `ANDROID_SERIAL` to that emulator's serial and run from the `android` directory.
```sh
./gradlew :app:assembleDebug :app:assembleDebugAndroidTest
adb -s "$ANDROID_SERIAL" install -r app/build/outputs/apk/debug/app-debug.apk
adb -s "$ANDROID_SERIAL" install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
adb -s "$ANDROID_SERIAL" shell appops set cy.hexor.tsunagi ACTIVATE_VPN allow
adb -s "$ANDROID_SERIAL" shell am instrument -w cy.hexor.tsunagi.test/androidx.test.runner.AndroidJUnitRunner
```
## Configure GitHub release signing
+25 -3
View File
@@ -22,8 +22,9 @@ android {
applicationId 'cy.hexor.tsunagi'
minSdk 26
targetSdk 35
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.0')
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.3-rc1')
ndk { abiFilters abi }
}
}
@@ -33,7 +34,8 @@ def metadata = providers.exec {
workingDir workspace
commandLine 'cargo', 'metadata', '--locked', '--format-version', '1', '--filter-platform', 'aarch64-linux-android'
}.standardOutput.asText.get()
def verifier = new JsonSlurper().parseText(metadata).packages.find { it.name == 'rustls-platform-verifier-android' }
def cargoMetadata = new JsonSlurper().parseText(metadata)
def verifier = cargoMetadata.packages.find { it.name == 'rustls-platform-verifier-android' }
repositories {
maven {
url new File(new File(verifier.manifest_path).parent, 'maven')
@@ -43,7 +45,11 @@ repositories {
google()
mavenCentral()
}
dependencies { implementation "rustls:rustls-platform-verifier:${verifier.version}" }
dependencies {
implementation "rustls:rustls-platform-verifier:${verifier.version}"
androidTestImplementation 'androidx.test:runner:1.5.2'
androidTestImplementation 'junit:junit:4.13.2'
}
abstract class BuildRust extends Exec {
@OutputDirectory abstract DirectoryProperty getJniLibs()
@@ -63,4 +69,20 @@ androidComponents.onVariants(androidComponents.selector().all()) { variant ->
if (mode == 'release') args '--release'
}
variant.sources.jniLibs.addGeneratedSourceDirectory(nativeBuild) { it.jniLibs }
if (variant.androidTest != null) {
def probe = tasks.register('cargoVpnSourceProbe', BuildRust) {
workingDir workspace
jniLibs.set(layout.buildDirectory.dir('generated/rust/vpnSourceTest'))
inputs.files(nativeBuild.map { it.inputs.files }, fileTree("${workspace}/crates/tsunagi-android/examples"))
commandLine 'cargo', 'ndk', '--target', abi, '--platform', '26',
'build', '--locked', '--example', 'vpn_source_probe', '-p', 'tsunagi-android'
doLast {
project.copy {
from "${cargoMetadata.target_directory}/aarch64-linux-android/debug/examples/libvpn_source_probe.so"
into jniLibs.dir(abi)
}
}
}
variant.androidTest.sources.jniLibs.addGeneratedSourceDirectory(probe) { it.jniLibs }
}
}
@@ -0,0 +1,52 @@
package cy.hexor.tsunagi
import android.content.Context
import android.content.ContextWrapper
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.VpnService
import android.os.ParcelFileDescriptor
import android.os.SystemClock
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Test
class VpnSourceTest {
private external fun checkSockets(fd: Int, networkCount: Int)
@Test fun udpAndPingReceiveFromBothNetworksAfterAddingTheSecond() {
System.loadLibrary("vpn_source_probe")
val context = InstrumentationRegistry.getInstrumentation().targetContext
check(VpnService.prepare(context) == null) { "Grant VPN consent on the test emulator first" }
val connectivity = context.getSystemService(ConnectivityManager::class.java)
// Android requires the manifest-declared service class. Attach it under the
// application UID without starting the agent and binding this process to the underlay.
val vpn = MeshVpn()
ContextWrapper::class.java.getDeclaredMethod("attachBaseContext", Context::class.java)
.apply { isAccessible = true }.invoke(vpn, context)
MeshVpn::class.java.getDeclaredField("upstream").apply { isAccessible = true }
.set(vpn, connectivity.activeNetwork)
val hosts = listOf("198.18.234.1/24", "198.19.234.1/24")
val routes = listOf("198.18.234.0/24", "198.19.234.0/24")
fun establish(count: Int): ParcelFileDescriptor {
val fd = vpn.establishTun(hosts.take(count).joinToString(","),
routes.take(count).joinToString(","), "", 1280, false)
check(fd >= 0) { "VPN establishment failed" }
return ParcelFileDescriptor.adoptFd(fd)
}
fun checkVpn(fd: ParcelFileDescriptor, count: Int) {
val deadline = SystemClock.elapsedRealtime() + 5000
while (true) {
val active = connectivity.activeNetwork
if (connectivity.getNetworkCapabilities(active)?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true
&& connectivity.getLinkProperties(active)?.linkAddresses?.size == count) break
check(SystemClock.elapsedRealtime() < deadline) { "Timed out waiting for VPN routes" }
SystemClock.sleep(25)
}
checkSockets(ParcelFileDescriptor.dup(fd.fileDescriptor).detachFd(), count)
}
establish(1).use { first ->
checkVpn(first, 1)
establish(2).use { both -> checkVpn(both, 2) }
}
}
}
+6 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-android"
version = "1.0.0"
version = "1.0.3-rc1"
description = "Android VPN client and egui views for tsunagi."
edition.workspace = true
rust-version.workspace = true
@@ -11,8 +11,12 @@ publish = false
[lib]
crate-type = ["cdylib", "rlib"]
[[example]]
name = "vpn_source_probe"
crate-type = ["cdylib"]
[dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.0" }
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.3-rc1" }
tsunagi-ui = { path = "../tsunagi-ui" }
tsunagi-core = { path = "../tsunagi-core" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
@@ -0,0 +1,142 @@
//! Peer for the Android instrumentation test. Only the test APK packages it.
#![cfg(target_os = "android")]
use jni::{JNIEnv, objects::JObject};
use std::{
fs::File,
io,
net::Ipv4Addr,
os::fd::{FromRawFd, OwnedFd},
process::Command,
time::Duration,
};
use tsunagi::overlay::{Cidr, TunDevice, TunFactory, TunRequest};
use tsunagi_android::{dns::Resolver, tun::AndroidTun};
#[allow(unsafe_code)]
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_VpnSourceTest_checkSockets(
mut env: JNIEnv,
_: JObject,
fd: i32,
count: i32,
) {
// SAFETY: the instrumentation test transfers a duplicate with detachFd().
let file = File::from(unsafe { OwnedFd::from_raw_fd(fd) });
let result = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.and_then(|rt| rt.block_on(check(file, count)));
if let Err(error) = result {
let _ = env.throw_new("java/lang/AssertionError", error.to_string());
}
}
async fn check(file: File, count: i32) -> io::Result<()> {
let factory = AndroidTun::new(
Resolver::new(|_| None),
move |_| file.try_clone(),
|_, _| Ok(()),
);
let locals = [
Ipv4Addr::new(198, 18, 234, 1),
Ipv4Addr::new(198, 19, 234, 1),
];
let mut req = TunRequest::bare("vpn", 1280);
for &local in locals.iter().take(count as usize) {
req.addresses
.push(Cidr::new(local.into(), 24).map_err(io::Error::other)?);
}
let tun = factory.create(req).await.map_err(io::Error::other)?;
for &local in locals.iter().take(count as usize) {
let mut octets = local.octets();
octets[3] = 2;
let remote = Ipv4Addr::from(octets);
let exchange = async {
udp(tun.as_ref(), local, remote).await?;
ping(tun.as_ref(), local, remote).await
};
tokio::time::timeout(Duration::from_secs(8), exchange)
.await
.map_err(|_| io::Error::other(format!("echo timed out on network {local}")))??;
}
Ok(())
}
async fn echo(
tun: &dyn TunDevice,
local: Ipv4Addr,
remote: Ipv4Addr,
protocol: u8,
) -> io::Result<()> {
use smoltcp::wire::{Icmpv4Message, Icmpv4Packet};
loop {
let mut pkt = tun
.recv()
.await
.ok_or_else(|| io::Error::other("VPN closed"))?
.to_vec();
if pkt.len() < 28 || pkt[0] != 0x45 || pkt[9] != protocol || pkt[16..20] != remote.octets()
{
continue;
}
if protocol == 17 {
if pkt[22..24] != 45678u16.to_be_bytes() || &pkt[28..] != b"mesh probe" {
continue;
}
// Swapping ports preserves the UDP checksum.
pkt[20..24].rotate_left(2);
} else {
let mut icmp = Icmpv4Packet::new_checked(&mut pkt[20..]).map_err(io::Error::other)?;
if icmp.msg_type() != Icmpv4Message::EchoRequest {
continue;
}
icmp.set_msg_type(Icmpv4Message::EchoReply);
icmp.fill_checksum();
}
if pkt[12..16] != local.octets() {
return Err(io::Error::other(format!(
"peer {remote} saw source {:?}, expected {local}",
&pkt[12..16]
)));
}
// Swapping addresses preserves the IPv4 checksum and the pseudo-header sum.
pkt[12..20].rotate_left(4);
return tun.send(pkt.into()).await.map_err(io::Error::other);
}
}
async fn udp(tun: &dyn TunDevice, local: Ipv4Addr, remote: Ipv4Addr) -> io::Result<()> {
let socket = tokio::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await?;
socket.connect((remote, 45678)).await?;
socket.send(b"mesh probe").await?;
echo(tun, local, remote, 17).await?;
let mut reply = [0; 64];
let n = socket.recv(&mut reply).await?;
if &reply[..n] != b"mesh probe" {
return Err(io::Error::other("UDP echo payload changed"));
}
Ok(())
}
async fn ping(tun: &dyn TunDevice, local: Ipv4Addr, remote: Ipv4Addr) -> io::Result<()> {
let command = async {
let output = tokio::task::spawn_blocking(move || {
Command::new("/system/bin/ping")
.args(["-n", "-c", "1", "-w", "4"])
.arg(remote.to_string())
.output()
})
.await??;
if !output.status.success() {
return Err(io::Error::other(format!(
"ping {remote} failed: {}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
)));
}
Ok(())
};
tokio::try_join!(command, echo(tun, local, remote, 1))?;
Ok(())
}
+3 -1
View File
@@ -178,8 +178,10 @@ pub async fn report(
dns: &crate::dns::Resolver,
) -> tsunagi::Result<StatusReport> {
let status = agent.status().await?;
let overlay = agent.overlay();
Ok(StatusReport {
networks: tsunagi_runtime::report::networks(&status, agent.overlay().as_ref(), wg),
networks: tsunagi_runtime::report::networks(&status, overlay.as_ref(), wg),
overlay_config_error: overlay.and_then(|state| state.address_error),
dns: Some(dns.refresh(&status.networks)),
endpoint_id: status.endpoint_id.to_string(),
hostname: status.hostname,
+71 -15
View File
@@ -6,7 +6,7 @@ use std::{
fmt,
fs::File,
io::{self, Read, Write},
sync::Arc,
sync::{Arc, Mutex as StdMutex},
};
use tokio::{
io::unix::AsyncFd,
@@ -20,6 +20,7 @@ use tsunagi::{
BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, ExitHostPlan,
ExitHostReport, ExitHostRules, RuleOutcome,
},
source::{SourceFlows, SourceMode},
},
};
@@ -30,6 +31,17 @@ struct Attachment {
device: Arc<AsyncFd<File>>,
addresses: Vec<std::net::IpAddr>,
dns: DnsPort,
packets: StdMutex<Option<PacketState>>,
}
struct PacketState {
flows: SourceFlows,
// At most one reassembled IPv4 datagram's worth of remaining fragments.
pending: std::vec::IntoIter<Bytes>,
}
impl Attachment {
fn packets(&self) -> std::sync::MutexGuard<'_, Option<PacketState>> {
self.packets.lock().unwrap_or_else(|err| err.into_inner())
}
}
type Descriptor = Option<Arc<Attachment>>;
@@ -76,7 +88,7 @@ impl AndroidTun {
return Ok(());
}
let dns_address = next.dns_address();
let fd = if next.addresses.is_empty() {
let device = if next.addresses.is_empty() {
None
} else {
let address = dns_address.ok_or_else(|| OverlayError::Unavailable(
@@ -92,12 +104,37 @@ impl AndroidTun {
self.0.resolver.clone(),
file.clone(),
);
Some(Arc::new(Attachment {
Some((file, dns))
};
// Only retire the old descriptor once establishing its replacement succeeds.
let previous = self
.0
.current
.borrow()
.clone()
.and_then(|fd| fd.packets().take());
let fd = device.map(|(file, dns)| {
let aliases = next.addresses_in_order();
let exit = match (next.full_tunnel, next.exit) {
(true, Some(std::net::IpAddr::V4(source))) => Some(source),
_ => None,
};
let flows = if let Some(mut previous) = previous {
previous.flows.reconfigure(&aliases, exit, next.mtu);
previous.flows
} else {
SourceFlows::new(&aliases, exit, next.mtu, SourceMode::Primary)
};
Arc::new(Attachment {
device: file,
addresses: next.addresses.iter().map(|a| a.addr).collect(),
dns,
}))
};
packets: StdMutex::new(Some(PacketState {
flows,
pending: Vec::new().into_iter(),
})),
})
});
self.0.current.send_replace(fd);
self.0.resolver.publish(dns_address);
*applied = next;
@@ -122,10 +159,14 @@ impl TunDevice for Device {
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
Box::pin(async move {
let mut rx = self.tun.0.current.subscribe();
let mut buffer = vec![0; self.mtu as usize + 1];
let mut buffer = Vec::new();
loop {
let fd = rx.borrow_and_update().clone();
if let Some(fd) = fd {
if let Some(packet) = fd.packets().as_mut().and_then(|p| p.pending.next()) {
return Some(packet);
}
buffer.resize(self.mtu as usize + 1, 0);
let result = tokio::select! {
biased;
_ = rx.changed() => continue,
@@ -136,7 +177,14 @@ impl TunDevice for Device {
continue;
}
buffer.truncate(len);
return Some(buffer.into());
if let Some(state) = fd.packets().as_mut() {
let frames = state.flows.outbound(std::mem::take(&mut buffer).into());
state.pending = frames.into_iter();
if let Some(packet) = state.pending.next() {
return Some(packet);
}
}
continue;
}
}
// No networks yet, last one left, or Android revoked this fd.
@@ -152,14 +200,22 @@ impl TunDevice for Device {
.borrow_and_update()
.clone()
.ok_or_else(|| OverlayError::Unavailable("VPN has no addresses".into()))?;
let len = tokio::select! {
biased;
_ = rx.changed() => return Err(OverlayError::Unavailable("VPN was reconfigured".into())),
write = fd.device.async_io(tokio::io::Interest::WRITABLE, |mut file| file.write(&packet)) =>
write.map_err(|e| OverlayError::Other(e.to_string()))?,
};
if len != packet.len() {
return Err(OverlayError::Other("short VPN datagram write".into()));
let packets = fd
.packets()
.as_mut()
.ok_or_else(|| OverlayError::Unavailable("VPN was reconfigured".into()))?
.flows
.inbound(packet);
for packet in packets {
let len = tokio::select! {
biased;
_ = rx.changed() => return Err(OverlayError::Unavailable("VPN was reconfigured".into())),
write = fd.device.async_io(tokio::io::Interest::WRITABLE, |mut file| file.write(&packet)) =>
write.map_err(|e| OverlayError::Other(e.to_string()))?,
};
if len != packet.len() {
return Err(OverlayError::Other("short VPN datagram write".into()));
}
}
Ok(())
})
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-awg"
version = "1.0.0"
version = "1.0.3-rc1"
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
edition.workspace = true
rust-version.workspace = true
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-core"
version = "1.0.0"
version = "1.0.3-rc1"
description = "Small private mesh networks: persistent agent identity, deterministic network spaces, an iroh control plane, signed state and a local DNS view."
readme = "../../README.md"
keywords = ["mesh", "p2p", "iroh", "networking"]
@@ -59,6 +59,8 @@ rand = "0.10"
# zone logic is ours and a full server framework would be a large dependency
# for answering A records from memory.
simple-dns = "0.12"
# IPv4 packet and checksum codecs shared by the Android VPN and Wintun.
smoltcp = { version = "0.12", default-features = false, features = ["std", "proto-ipv4"] }
# The IANA top-level domain list, compiled in: one function, no
# dependencies, no network. Used only to warn that a zone name shadows a
# real public domain, never to refuse one.
+45 -61
View File
@@ -104,7 +104,7 @@ struct Inner {
networks: RwLock<HashMap<NetworkId, NetworkHandle>>,
shutdown: Shutdown,
/// Serialises start, stop, switching and conflict cleanup, including teardown.
lifecycle: Mutex<()>,
lifecycle: Arc<Mutex<()>>,
range_changed: watch::Sender<()>,
range_task: std::sync::Mutex<Option<JoinHandle<()>>>,
accept_task: std::sync::Mutex<Option<JoinHandle<()>>>,
@@ -135,7 +135,9 @@ impl Inner {
.await
{
Ok(interface) => {
self.adapter.exclude_interface(interface.name());
if interface.on_host() {
self.adapter.exclude_interface(interface.name());
}
for carrier in &self.config.carriers {
carrier.on_interface_ready(interface.name());
}
@@ -448,7 +450,7 @@ impl Agent {
events,
networks: RwLock::new(HashMap::new()),
shutdown: Shutdown::new(),
lifecycle: Mutex::new(()),
lifecycle: Arc::new(Mutex::new(())),
range_changed,
range_task: std::sync::Mutex::new(None),
accept_task: std::sync::Mutex::new(None),
@@ -643,6 +645,7 @@ impl Agent {
on_host: interface.on_host(),
mtu: interface.mtu(),
addresses: interface.wanted_addresses(),
address_error: interface.address_error(),
counters: interface.counters(),
broadcast_rules: interface.broadcast_rules(),
})
@@ -794,47 +797,27 @@ impl Agent {
/// choice in the others. The member has to be connected and offering
/// to be an exit node. Remembered across restarts.
pub async fn set_exit_via(&self, network_id: NetworkId, via: Option<EndpointId>) -> Result<()> {
let active = self.is_active(network_id).await;
if via.is_some() && !active {
return Err(Error::NetworkNotActive(network_id));
}
if active {
let (reply, receive) = oneshot::channel();
self.command(network_id, NetCommand::SetExitVia { via, reply })
.await?;
receive
.await
.map_err(|_| Error::Stopped)?
.map_err(|reason| Error::Rejected { reason })?;
}
self.inner
.storage
.set_exit_via(network_id, via.map(|peer| *peer.as_bytes()))
.await?;
if via.is_some() {
// One default route: whatever the other networks were doing, they
// are not any more.
let others: Vec<NetworkId> = self
.inner
.networks
.read()
.await
.keys()
.copied()
.filter(|other| *other != network_id)
.collect();
for other in others {
let (reply, receive) = oneshot::channel();
if self
.command(other, NetCommand::SetExitVia { via: None, reply })
.await
.is_ok()
{
let _ = receive.await;
}
let lifecycle = self.inner.lifecycle.clone().lock_owned().await;
if !self.is_active(network_id).await {
if via.is_some() {
return Err(Error::NetworkNotActive(network_id));
}
return self.inner.storage.set_exit_via(network_id, None).await;
}
Ok(())
// The actor owns the guard through validation, persistence and routing,
// even if the requesting IPC client disconnects halfway through.
let (reply, receive) = oneshot::channel();
self.command(
network_id,
NetCommand::SetExitVia {
via,
lifecycle,
reply,
},
)
.await?;
receive.await.map_err(|_| Error::Stopped)?
}
/// Changes a network's local broadcast policy now and after restart.
@@ -958,6 +941,13 @@ impl Agent {
)?;
}
let range = self.desired_range(network_id).await?;
let exit = crate::overlay::ExitPolicy {
offer: stored.as_ref().is_some_and(|s| s.exit_node),
via: stored
.as_ref()
.and_then(|s| s.exit_via)
.and_then(|bytes| EndpointId::from_bytes(&bytes).ok()),
};
if let Some(range) = range {
let conflicts = self.inner.routes.overlapping_networks(network_id, range);
if !conflicts.is_empty() {
@@ -967,19 +957,20 @@ impl Agent {
conflicts: conflicts.into_iter().map(|(id, _)| id).collect(),
});
}
self.inner
.routes
.set_network(
network_id,
crate::overlay::NetworkRoutes {
range: Some(range),
..Default::default()
},
)
.map_err(|err| Error::Rejected {
reason: err.to_string(),
})?;
}
self.inner
.routes
.set_network(
network_id,
crate::overlay::NetworkRoutes {
range,
exit,
..Default::default()
},
)
.map_err(|err| Error::Rejected {
reason: err.to_string(),
})?;
let mut backends = Vec::new();
if let Some(discovery) = &self.inner.config.discovery {
backends.push(discovery.clone());
@@ -1003,17 +994,10 @@ impl Agent {
if !plugins.is_empty() {
self.inner.ensure_interface().await;
}
let exit_offer = stored.as_ref().is_some_and(|stored| stored.exit_node);
let exit_via = stored
.as_ref()
.and_then(|stored| stored.exit_via)
.and_then(|bytes| EndpointId::from_bytes(&bytes).ok());
let handle = network::spawn(RuntimeParams {
vips,
retirements,
broadcast,
exit_offer,
exit_via,
keys,
adapter: self.inner.adapter.clone(),
storage: self.inner.storage.clone(),
+254 -85
View File
@@ -39,6 +39,8 @@ use super::status::{
NetworkStatus, PeerStatus,
};
mod selection;
/// An inbound connection that already passed the handshake.
#[derive(Debug)]
pub(crate) struct InboundSession {
@@ -94,7 +96,8 @@ pub(crate) enum NetCommand {
/// Send this device's internet traffic through a member, or stop.
SetExitVia {
via: Option<EndpointId>,
reply: oneshot::Sender<std::result::Result<(), String>>,
lifecycle: tokio::sync::OwnedMutexGuard<()>,
reply: oneshot::Sender<Result<()>>,
},
/// Resend this agent's announcement to every peer of this network.
Reannounce,
@@ -175,10 +178,6 @@ pub(crate) struct RuntimeParams {
pub(crate) vips: crate::vip::VipSet,
pub(crate) retirements: Vec<SignedRetirement>,
pub(crate) broadcast: bool,
/// This agent offers itself as an exit node here.
pub(crate) exit_offer: bool,
/// The member this device's internet traffic goes through.
pub(crate) exit_via: Option<EndpointId>,
pub(crate) keys: NetworkKeys,
pub(crate) adapter: EndpointAdapter,
pub(crate) storage: Storage,
@@ -237,6 +236,54 @@ struct DialState {
source: CandidateSource,
}
/// Keep only paths that this runtime verified, long enough to reconnect when
/// a session goes away while the host sends its default traffic into the mesh.
#[derive(Default)]
struct VerifiedUnderlay {
peers: HashMap<EndpointId, (Instant, Vec<PathAddr>)>,
}
impl VerifiedUnderlay {
fn record(
&mut self,
peer: EndpointId,
paths: impl IntoIterator<Item = PathAddr>,
now: Instant,
limit: usize,
) {
let paths: Vec<_> = paths
.into_iter()
.filter(|p| {
matches!(
p,
PathAddr::Ip(std::net::SocketAddr::V4(_)) | PathAddr::Relay(_)
)
})
.take(limit)
.collect();
if !paths.is_empty() {
self.peers.insert(peer, (now, paths));
}
}
fn prune(&mut self, now: Instant, limit: usize, retired: impl Fn(EndpointId) -> bool) {
self.peers.retain(|peer, (seen, _)| {
!retired(*peer) && now.duration_since(*seen) < Duration::from_secs(120)
});
if self.peers.len() > limit {
let mut oldest: Vec<_> = self
.peers
.iter()
.map(|(peer, (seen, _))| (*seen, *peer))
.collect();
oldest.sort_unstable();
for (_, peer) in oldest.into_iter().take(self.peers.len() - limit) {
self.peers.remove(&peer);
}
}
}
}
impl DialState {
fn new(source: CandidateSource) -> Self {
Self {
@@ -314,6 +361,7 @@ struct Runtime {
local_id: EndpointId,
shutdown: Shutdown,
sessions: HashMap<EndpointId, Session>,
verified_underlay: VerifiedUnderlay,
dial_states: HashMap<EndpointId, DialState>,
candidate_addrs: HashMap<EndpointId, iroh::EndpointAddr>,
metrics: NetworkMetrics,
@@ -327,6 +375,7 @@ struct Runtime {
/// peer, which outlives any particular path.
links: HashMap<(EndpointId, String), Arc<HealthLink>>,
pending_health: HashMap<(EndpointId, String), HealthSettings>,
comparisons: HashMap<EndpointId, selection::Schedule>,
last_failed_protocol: HashMap<EndpointId, String>,
/// Every data link of this network, and what is reached through what.
hub: Arc<crate::dataplane::relay::RelayHub>,
@@ -441,6 +490,7 @@ impl Runtime {
local_id,
shutdown,
sessions: HashMap::new(),
verified_underlay: VerifiedUnderlay::default(),
dial_states: HashMap::new(),
candidate_addrs: HashMap::new(),
metrics: NetworkMetrics::default(),
@@ -450,6 +500,7 @@ impl Runtime {
dial_results_rx,
links: HashMap::new(),
pending_health: HashMap::new(),
comparisons: HashMap::new(),
last_failed_protocol: HashMap::new(),
hub,
reachable: HashMap::new(),
@@ -685,25 +736,24 @@ impl Runtime {
let _ = reply.send(());
}
NetCommand::SetExitOffer { enabled, reply } => {
self.params.exit_offer = enabled;
self.params
.routes
.update_exit(self.network_id, |exit| exit.offer = enabled);
self.apply_exit().await;
self.reannounce();
let _ = reply.send(());
}
NetCommand::SetExitVia { via, reply } => {
let outcome = match via {
Some(peer) if !self.exit_node_online(peer) => Err(
"that member is not connected or does not offer to be an exit node"
.to_string(),
),
_ => Ok(()),
};
if outcome.is_ok() {
self.params.exit_via = via;
self.exit_via_was_online = via.is_some();
NetCommand::SetExitVia {
via,
lifecycle,
reply,
} => {
let result = self.select_exit(via).await;
drop(lifecycle);
if result.is_ok() {
self.apply_exit().await;
}
let _ = reply.send(outcome);
let _ = reply.send(result);
}
NetCommand::Recheck => self.discovery_round().await,
NetCommand::Reannounce => {
@@ -902,23 +952,49 @@ impl Runtime {
/// on: the verified direct IPv4 paths of every control connection, and
/// the relays in use. Only hosts that cannot exempt the agent from an
/// exit node's default route read it.
async fn refresh_underlay(&self) {
let Some(interface) = self.params.interface.clone() else {
async fn refresh_underlay(&mut self) {
let Some(interface) = self
.params
.interface
.as_ref()
.filter(|i| i.needs_underlay_targets())
else {
return;
};
let mut addresses = Vec::new();
let mut hosts = Vec::new();
for session in self.sessions.values() {
for path in snapshot_connection(&session.conn).paths {
match path.remote {
PathAddr::Ip(std::net::SocketAddr::V4(socket)) => addresses.push(*socket.ip()),
PathAddr::Relay(url) => hosts.extend(relay_host(&url)),
_ => {}
}
let now = Instant::now();
for (peer, session) in &self.sessions {
let mut paths = snapshot_connection(&session.conn).paths;
paths.sort_by_key(|path| !path.is_selected);
self.verified_underlay.record(
*peer,
paths.into_iter().map(|p| p.remote),
now,
self.params.limits.max_hints_per_peer,
);
}
self.verified_underlay
.prune(now, self.params.limits.max_sessions_per_network, |peer| {
self.state.is_retired(&peer)
});
for path in self
.verified_underlay
.peers
.values()
.flat_map(|(_, paths)| paths)
{
match path {
PathAddr::Ip(std::net::SocketAddr::V4(socket)) => addresses.push(*socket.ip()),
PathAddr::Relay(url) => hosts.extend(relay_host(url)),
_ => {}
}
}
for url in self.params.adapter.snapshot().relay_urls {
hosts.extend(relay_host(&url));
// The endpoint stops advertising a disconnected relay, but still
// attempts to reconnect to it through the physical network.
use iroh::Watcher;
for relay in self.params.adapter.endpoint().home_relay_status().get() {
hosts.extend(relay_host(relay.url().as_str()));
}
interface
.set_underlay(self.network_id, addresses, hosts)
@@ -1304,7 +1380,7 @@ impl Runtime {
"the node is online; only offline history can be forgotten".into(),
));
}
if self.params.exit_via == Some(peer) {
if self.exit_policy().via == Some(peer) {
return Err(Error::ForgetNode(
"stop using this exit node before forgetting it".into(),
));
@@ -1766,20 +1842,36 @@ impl Runtime {
}
fn exit_policy(&self) -> crate::overlay::ExitPolicy {
crate::overlay::ExitPolicy {
offer: self.params.exit_offer,
via: self.params.exit_via,
self.params
.routes
.exit_settings(self.network_id)
.map(|(policy, _)| policy)
.unwrap_or_default()
}
async fn select_exit(&mut self, via: Option<EndpointId>) -> Result<()> {
if via.is_some_and(|peer| !self.exit_node_online(peer)) {
return Err(Error::Rejected {
reason: "that member is not connected or does not offer to be an exit node".into(),
});
}
self.params
.storage
.set_exit_via(self.network_id, via.map(|peer| *peer.as_bytes()))
.await?;
self.params
.routes
.update_exit(self.network_id, |exit| exit.via = via);
self.exit_via_was_online = via.is_some();
Ok(())
}
/// Whether this agent offers to be an exit node and can really be one.
fn exit_ready(&self) -> bool {
self.params.exit_offer
&& self
.params
.interface
.as_ref()
.is_some_and(|interface| interface.exit_offer_ready(self.network_id))
self.params
.interface
.as_ref()
.is_some_and(|interface| interface.exit_offer_ready(self.network_id))
}
/// Whether a member is connected and says it is an exit node.
@@ -1789,15 +1881,12 @@ impl Runtime {
.is_some_and(|session| session.exit_node)
}
/// Puts the exit settings into the routing table and the host rules.
/// Reconciles the host rules with the shared routing table.
///
/// The routes and the rules stay as they are when the exit node in use
/// goes away: dropping them would send the traffic out the old way, in
/// the clear, without anyone having asked.
async fn apply_exit(&mut self) {
self.params
.routes
.set_exit(self.network_id, self.exit_policy());
if let Some(interface) = self.params.interface.clone() {
interface.sync_exit_rules().await;
}
@@ -1810,7 +1899,7 @@ impl Runtime {
/// Says so, once, when the exit node in use is lost or comes back.
fn watch_exit_via(&mut self) {
let Some(via) = self.params.exit_via else {
let Some(via) = self.exit_policy().via else {
return;
};
let online = self.exit_node_online(via);
@@ -1861,7 +1950,7 @@ impl Runtime {
// a packet for ourselves does not go over a tunnel.
let local = self.state.address_of(&self.local_id);
let routes = crate::overlay::NetworkRoutes {
exit: self.exit_policy(),
exit: Default::default(),
broadcast: self.broadcast_policy(),
range: Some(range),
local,
@@ -1874,7 +1963,7 @@ impl Runtime {
if self
.params
.routes
.set_network(self.network_id, routes)
.update_allocations(self.network_id, routes)
.is_err()
{
self.range_blocked
@@ -2024,24 +2113,29 @@ impl Runtime {
}
}
for (peer, protocol) in dead {
let reason = self
.links
.remove(&(peer, protocol.clone()))
.map(|link| {
let reason = link
.failure_reason()
.unwrap_or_else(|| "link closed".into());
link.close();
reason
})
.unwrap_or_else(|| "link closed".into());
let Some(link) = self.links.remove(&(peer, protocol.clone())) else {
continue;
};
let planned = self
.comparisons
.get(&peer)
.is_some_and(|s| s.retiring(link.profile_id()));
let reason = if planned {
"retired after carrier comparison".into()
} else {
let reason = link
.failure_reason()
.unwrap_or_else(|| "link closed".into());
self.data_errors
.insert(peer, format!("{protocol}: {reason}"));
self.record_protocol_failure(peer, &protocol);
reason
};
link.close();
// Only the direct path is gone. Whether the peer is still
// reachable through somebody is decided below; the protocol's
// link stays either way.
self.hub.clear_direct(peer, &protocol);
self.data_errors
.insert(peer, format!("{protocol}: {reason}"));
self.record_protocol_failure(peer, &protocol);
self.emit(Event::DataLinkDown {
network: self.network_id,
peer,
@@ -2050,17 +2144,23 @@ impl Runtime {
});
}
// Choose the highest priority mutually supported protocol for each peer.
// If a direct data link is already open or opening, do not dial another.
// If a protocol recently failed, fall back to other mutually supported
// protocols according to backoff cooldown.
// Foreground recovery always precedes optional comparisons.
self.review_comparisons();
let now = std::time::Instant::now();
let mut wanted: Vec<(EndpointId, String)> = Vec::new();
let mut interrupted = Vec::new();
for session in self.sessions.values() {
let peer = session.peer;
if self.links.keys().any(|(p, _)| *p == peer)
|| self.opening.iter().any(|(p, _)| *p == peer)
{
if self.links.keys().any(|(p, _)| *p == peer) {
continue;
}
let opening = self.opening.iter().find(|(id, _)| *id == peer);
if opening.is_some_and(|(_, protocol)| {
!self
.comparisons
.get(&peer)
.is_some_and(|s| s.is_trial(protocol))
}) {
continue;
}
if self.no_direct_data(peer) {
@@ -2087,27 +2187,41 @@ impl Runtime {
continue;
}
let start = next_protocol_index(
&supported,
self.last_failed_protocol.get(&peer).map(String::as_str),
);
let last_failed = self.last_failed_protocol.get(&peer);
let start = next_protocol_index(&supported, last_failed.map(String::as_str));
let chosen = supported
.iter()
.cycle()
.skip(start)
.take(supported.len())
.find(
|proto| match self.protocol_dial_states.get(&(peer, (*proto).clone())) {
Some(state) => state.cooldown_until <= now,
None => true,
},
);
.find(|proto| {
opening.is_none_or(|(_, kind)| kind != *proto && last_failed != Some(*proto))
&& self
.protocol_dial_states
.get(&(peer, (*proto).clone()))
.is_none_or(|state| state.cooldown_until <= now)
});
if let Some(proto) = chosen {
wanted.push((peer, proto.clone()));
if let Some(key) = opening {
interrupted.push(key.clone());
}
}
}
// A trial can still recover a two-carrier peer. Cancel it only for a
// third eligible carrier, preserving the failure order and cooldowns.
for key in interrupted {
self.opening.remove(&key);
self.link_attempts.remove(&key);
if let Some(task) = self.link_tasks.remove(&key) {
task.abort();
}
self.finish_comparison(key.0);
}
let trial = self.next_comparison(&served, now);
wanted.extend(trial.iter().cloned());
for (peer, protocol) in wanted {
let key = (peer, protocol.clone());
if self.links.contains_key(&key) || self.opening.contains(&key) {
@@ -2119,6 +2233,7 @@ impl Runtime {
let transport = Arc::clone(&transport);
let network = self.network_id;
let shutdown = self.shutdown.clone();
let background = trial.as_ref() == Some(&key);
self.next_link_attempt = self.next_link_attempt.wrapping_add(1);
let generation = self.next_link_attempt;
self.link_attempts.insert(key.clone(), generation);
@@ -2126,8 +2241,16 @@ impl Runtime {
let result = tokio::select! {
biased;
_ = shutdown.wait() => Err("network deactivated".to_string()),
result = transport.open(network, peer, &protocol) => {
result.map_err(|err| err.to_string())
result = async {
let dial = transport.open(network, peer, &protocol);
if background {
tokio::time::timeout(Duration::from_secs(30), dial).await
.map_err(|_| "carrier comparison timed out".to_owned())?
} else {
dial.await
}.map_err(|err| err.to_string())
} => {
result
}
};
let _ = results
@@ -2475,6 +2598,10 @@ impl Runtime {
self.pending_health.remove(&key)
};
let link = HealthLink::new(link, self.local_id, settings);
if let Some(primary) = self.hub.direct_kinds(peer).first() {
self.hub.prefer_direct(peer, primary);
}
self.link_installed(peer);
let path = link.path_description();
let max_datagram = link.max_datagram_size();
if let Some(old) = self.links.insert(key, Arc::clone(&link)) {
@@ -2512,6 +2639,7 @@ impl Runtime {
/// Retire only the data plane; authenticated membership and topology remain.
fn reset_peer_data(&mut self, peer: EndpointId, reason: &str) {
self.comparisons.remove(&peer);
self.data_errors.remove(&peer);
self.link_attempts.retain(|(id, _), _| *id != peer);
self.opening.retain(|(id, _)| *id != peer);
@@ -2604,6 +2732,9 @@ impl Runtime {
let snapshot = snapshot_connection(&conn);
self.sessions.insert(peer, session);
// An exit may be selected as soon as the peer advertises it, before
// the next discovery tick. Keep this transport on its physical path.
self.refresh_underlay().await;
if let Some(worker) = &self.discovery_worker {
worker.set_connected(true);
}
@@ -2661,6 +2792,9 @@ impl Runtime {
reason,
});
}
if self.params.carriers.len() > 1 {
capabilities.push(selection::capability());
}
capabilities.truncate(self.params.limits.max_capabilities);
self.local_capabilities = capabilities
.iter()
@@ -2802,6 +2936,10 @@ impl Runtime {
fn dispatch_message(&mut self, peer: EndpointId, message: ControlMessage) {
match &message {
ControlMessage::Transport { protocol, payload } => {
if protocol == selection::PROTOCOL {
self.receive_choice(peer, payload.as_bytes());
return;
}
if protocol == "link-health" {
// Only the elected initiator supplies a profile, for an enabled,
// mutually supported physical protocol in this authenticated session.
@@ -3079,6 +3217,7 @@ impl Runtime {
.iter()
.filter(|cap| {
cap.enabled
&& cap.protocol != selection::PROTOCOL
&& self
.params
.tunnel
@@ -3106,7 +3245,17 @@ impl Runtime {
.values()
.map(|session| {
let snapshot = snapshot_connection(&session.conn);
let selected = self
.hub
.direct_kinds(session.peer)
.into_iter()
.next()
.and_then(|kind| self.links.get(&(session.peer, kind)));
PeerStatus {
data_rtt: selected
.and_then(|link| link.quality())
.map(|quality| quality.rtt),
data_transport_detail: selected.map(|link| link.path_description()),
broadcast: session.broadcast,
exit_node: session.exit_node,
endpoint_id: session.peer,
@@ -3185,6 +3334,7 @@ impl Runtime {
members.sort_by(|a, b| a.endpoint_id.as_bytes().cmp(b.endpoint_id.as_bytes()));
members.dedup_by(|a, b| a.endpoint_id == b.endpoint_id);
let exit = self.exit_policy();
NetworkStatus {
vips: self.params.routes.vips.statuses(self.network_id),
protocols: self
@@ -3195,12 +3345,9 @@ impl Runtime {
.collect(),
auto_start: true,
broadcast: self.params.broadcast,
exit_offer: self.params.exit_offer,
exit_via: self.params.exit_via,
exit_via_online: self
.params
.exit_via
.is_some_and(|via| self.exit_node_online(via)),
exit_offer: exit.offer,
exit_via: exit.via,
exit_via_online: exit.via.is_some_and(|via| self.exit_node_online(via)),
exit_rules: self
.params
.interface
@@ -3358,6 +3505,28 @@ mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn verified_reconnect_paths_expire_and_are_replaced_without_admitting_candidates() {
let peer = crate::identity::DeviceIdentity::generate().endpoint_id();
let addr = |last| PathAddr::Ip(([192, 0, 2, last], 7777).into());
let now = Instant::now();
let mut paths = VerifiedUnderlay::default();
paths.record(peer, [addr(1), addr(2)], now, 1);
assert_eq!(paths.peers[&peer].1, [addr(1)]);
paths.record(peer, [addr(3)], now, 1);
paths.prune(now + Duration::from_secs(30), 1, |_| false);
assert_eq!(paths.peers[&peer].1, [addr(3)]);
let other = crate::identity::DeviceIdentity::generate().endpoint_id();
paths.record(other, [addr(4)], now + Duration::from_secs(31), 1);
paths.prune(now + Duration::from_secs(32), 1, |_| false);
assert!(!paths.peers.contains_key(&peer));
paths.prune(now + Duration::from_secs(32), 1, |p| p == other);
assert!(paths.peers.is_empty());
paths.record(peer, [addr(5)], now, 1);
paths.prune(now + Duration::from_secs(121), 1, |_| false);
assert!(paths.peers.is_empty());
}
#[test]
fn underlay_hints_exclude_overlay_subnets_but_preserve_lan_and_relay_candidates() {
let peer = crate::identity::DeviceIdentity::generate().endpoint_id();
@@ -0,0 +1,359 @@
//! Compare one alternative per peer while normal traffic stays on the incumbent.
//! The elected dialler chooses for both directions. Each decision names the
//! exact two health profiles, so delayed messages cannot retire a reopened link.
use super::{ControlMessage, EndpointId, Event, PacketLink, PluginCapability, Runtime};
use crate::dataplane::transport::{LinkQuality, TransportPayload};
use std::time::{Duration, Instant};
pub(super) const PROTOCOL: &str = "link-choice";
const RETRY: Duration = Duration::from_secs(3);
const NEXT_TRIAL: Duration = Duration::from_secs(120);
const MIN_WINDOW: Duration = Duration::from_secs(6);
// Allow a full rolling health window to replace probes sent before the
// responder installed its profile. Persistent loss still disqualifies a trial.
const MAX_WINDOW: Duration = Duration::from_secs(30);
pub(super) fn capability() -> PluginCapability {
PluginCapability {
protocol: PROTOCOL.into(),
version: 1,
enabled: true,
data: Vec::new(),
}
}
fn supports_choice(caps: &[PluginCapability]) -> bool {
caps.iter()
.any(|c| c.enabled && c.protocol == PROTOCOL && c.version == 1)
}
/// None keeps measuring on the alternative while user traffic stays on the incumbent.
fn promotion_decision(age: Duration, measured: Option<(LinkQuality, LinkQuality)>) -> Option<bool> {
if age < MIN_WINDOW {
return None;
}
let Some((current, alternative)) = measured.filter(|(current, alternative)| {
current.samples >= 5 && alternative.samples >= 5 && alternative.losses == 0
}) else {
return (age >= MAX_WINDOW).then_some(false);
};
let gain = current.rtt.saturating_sub(alternative.rtt);
Some(gain >= (current.rtt / 5).max(Duration::from_millis(5)))
}
/// Fixed-size identifiers from the two privately negotiated health profiles.
/// The responder echoes this value after accepting a decision.
#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
struct Choice {
keep: [u8; 16],
retire: [u8; 16],
}
struct Trial {
protocol: String,
started: Instant,
decision: Option<Choice>,
retry_at: Instant,
}
pub(super) struct Schedule {
next: Instant,
cursor: usize,
trial: Option<Trial>,
}
impl Schedule {
pub(super) fn is_trial(&self, protocol: &str) -> bool {
self.trial
.as_ref()
.is_some_and(|trial| trial.protocol == protocol)
}
/// The responder can close the losing link before its acknowledgement
/// arrives. Only an exact generation match makes this a planned closure.
pub(super) fn retiring(&self, profile: Option<[u8; 16]>) -> bool {
self.trial
.as_ref()
.and_then(|trial| trial.decision)
.is_some_and(|choice| Some(choice.retire) == profile)
}
}
impl Runtime {
pub(super) fn link_installed(&mut self, peer: EndpointId) {
if self.local_id.as_bytes() >= peer.as_bytes() || self.params.carriers.len() < 2 {
return;
}
let now = Instant::now();
let jitter = (peer.as_bytes()[0] ^ self.network_id.as_bytes()[0]) % 6;
let schedule = self.comparisons.entry(peer).or_insert(Schedule {
next: now + Duration::from_secs(12 + u64::from(jitter)),
cursor: 0,
trial: None,
});
if let Some(trial) = &mut schedule.trial {
// Any replacement invalidates an outstanding decision naming the
// previous pair of profiles. Compare both current links afresh.
trial.decision = None;
trial.started = now;
trial.retry_at = now;
}
}
/// At most two alternatives per network are opened or measured at once.
/// Waiting for a peer to acknowledge a decision uses no measurement slot. Old peers
/// keep the original single-carrier behaviour without a wire upgrade.
pub(super) fn next_comparison(
&mut self,
served: &[(String, u16)],
now: Instant,
) -> Option<(EndpointId, String)> {
if !supports_choice(&self.local_capabilities)
|| self
.comparisons
.values()
.filter_map(|s| s.trial.as_ref())
.filter(|trial| trial.decision.is_none())
.count()
>= 2
{
return None;
}
let (peer, index) =
self.comparisons
.iter()
.filter_map(|(peer, schedule)| {
if schedule.next > now
|| schedule.trial.is_some()
|| self.no_direct_data(*peer)
|| self.opening.iter().any(|(id, _)| id == peer)
{
return None;
}
let session = self.sessions.get(peer)?;
if !supports_choice(&session.capabilities)
|| self.hub.direct_kinds(*peer).len() != 1
{
return None;
}
let index = (0..served.len())
.map(|n| (n + schedule.cursor) % served.len())
.find(|i| {
let (name, version) = &served[*i];
let key = (*peer, name.clone());
!self.links.contains_key(&key)
&& self
.protocol_dial_states
.get(&key)
.is_none_or(|s| s.cooldown_until <= now)
&& session.capabilities.iter().any(|c| {
c.enabled && &c.protocol == name && &c.version == version
})
})?;
Some((schedule.next, *peer, index))
})
.min()
.map(|(_, peer, index)| (peer, index))?;
let schedule = self.comparisons.get_mut(&peer)?;
let protocol = served[index].0.clone();
schedule.cursor = index + 1;
schedule.trial = Some(Trial {
protocol: protocol.clone(),
started: now,
decision: None,
retry_at: now,
});
Some((peer, protocol))
}
pub(super) fn finish_comparison(&mut self, peer: EndpointId) {
if let Some(schedule) = self.comparisons.get_mut(&peer) {
schedule.trial = None;
schedule.next = Instant::now() + NEXT_TRIAL;
}
}
pub(super) fn review_comparisons(&mut self) {
let peers: Vec<_> = self
.comparisons
.iter()
.filter(|(_, s)| s.trial.is_some())
.map(|(peer, _)| *peer)
.collect();
for peer in peers {
self.review_trial(peer);
}
}
fn review_trial(&mut self, peer: EndpointId) {
let Some(trial) = self.comparisons.get(&peer).and_then(|s| s.trial.as_ref()) else {
return;
};
let key = (peer, trial.protocol.clone());
if self.opening.contains(&key) {
return;
}
let kinds = self.hub.direct_kinds(peer);
if kinds.len() < 2 || !self.links.contains_key(&key) {
self.finish_comparison(peer);
return;
}
let now = Instant::now();
if now < trial.retry_at {
return;
}
let choice = if let Some(choice) = trial.decision {
choice
} else {
let Some(other) = kinds.iter().find(|kind| **kind != trial.protocol) else {
return;
};
let Some(current) = self.links.get(&(peer, other.clone())) else {
return;
};
let Some(candidate) = self.links.get(&key) else {
return;
};
let age = now.duration_since(trial.started);
let measured = current.quality().zip(candidate.quality());
let Some(promote) = promotion_decision(age, measured) else {
return;
};
tracing::debug!(peer = %peer.fmt_short(), incumbent = %other, candidate = %trial.protocol, ?measured, promote, "compared data carriers");
let (winner, loser) = if promote {
(candidate, current)
} else {
(current, candidate)
};
let (Some(keep), Some(retire)) = (winner.profile_id(), loser.profile_id()) else {
return;
};
self.hub
.prefer_direct(peer, if promote { &trial.protocol } else { other });
Choice { keep, retire }
};
if let Some(trial) = self
.comparisons
.get_mut(&peer)
.and_then(|s| s.trial.as_mut())
{
trial.decision = Some(choice);
trial.retry_at = now + RETRY;
}
self.send_choice(peer, choice);
}
fn send_choice(&mut self, peer: EndpointId, choice: Choice) {
if let Ok(bytes) = postcard::to_stdvec(&choice) {
let _ = self.send_to(
peer,
ControlMessage::Transport {
protocol: PROTOCOL.into(),
payload: TransportPayload::new(bytes),
},
);
}
}
pub(super) fn receive_choice(&mut self, peer: EndpointId, payload: &[u8]) {
if payload.len() != 32 {
return;
}
let Ok(choice) = postcard::from_bytes::<Choice>(payload) else {
return;
};
if choice.keep == choice.retire
|| !supports_choice(&self.local_capabilities)
|| !self
.sessions
.get(&peer)
.is_some_and(|s| supports_choice(&s.capabilities))
{
return;
}
let dialler = self.local_id.as_bytes() < peer.as_bytes();
if dialler
&& self
.comparisons
.get(&peer)
.and_then(|s| s.trial.as_ref())
.and_then(|t| t.decision)
!= Some(choice)
{
return;
}
let find = |profile| {
self.links
.iter()
.find(|((id, _), link)| {
*id == peer && !link.is_closed() && link.profile_id() == Some(profile)
})
.map(|((_, kind), _)| kind.clone())
};
let Some(winner) = find(choice.keep) else {
return;
};
let loser = find(choice.retire);
self.hub.prefer_direct(peer, &winner);
if let Some(kind) = loser {
self.hub.clear_direct(peer, &kind);
if let Some(link) = self.links.remove(&(peer, kind.clone())) {
link.close();
self.emit(Event::DataLinkDown {
network: self.network_id,
peer,
protocol: kind,
reason: format!("carrier comparison kept {winner}"),
});
}
}
if dialler {
self.finish_comparison(peer);
} else {
self.send_choice(peer, choice);
}
self.announce_reach(false);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn measurement(ms: u64, samples: usize, losses: usize) -> LinkQuality {
LinkQuality {
rtt: Duration::from_millis(ms),
samples,
losses,
observed_at: Instant::now(),
}
}
#[test]
fn a_loss_during_profile_installation_can_age_out_before_deciding() {
let observed =
|samples, losses| Some((measurement(200, 20, 0), measurement(30, samples, losses)));
assert_eq!(promotion_decision(MIN_WINDOW, observed(5, 1)), None);
assert_eq!(
promotion_decision(Duration::from_secs(24), observed(20, 0)),
Some(true)
);
assert_eq!(promotion_decision(MAX_WINDOW, observed(18, 2)), Some(false));
assert_eq!(promotion_decision(MAX_WINDOW, observed(4, 0)), Some(false));
assert_eq!(promotion_decision(MIN_WINDOW / 2, observed(5, 0)), None);
}
#[test]
fn promote_only_a_sampled_reliable_and_materially_faster_path() {
let better = |current: &LinkQuality, candidate: &LinkQuality| {
promotion_decision(MAX_WINDOW, Some((*current, *candidate))) == Some(true)
};
let current = measurement(350, 20, 1);
assert!(better(&current, &measurement(60, 6, 0)));
assert!(!better(&current, &measurement(60, 1, 0)));
assert!(!better(&current, &measurement(60, 6, 2)));
assert!(!better(&measurement(61, 20, 0), &measurement(59, 10, 0)));
assert!(!better(&measurement(10, 20, 0), &measurement(7, 10, 0)));
assert!(!better(&measurement(8, 2, 0), &measurement(1, 6, 0)));
}
}
+6
View File
@@ -51,6 +51,8 @@ pub struct OverlayStatus {
pub mtu: u32,
/// The addresses it should be carrying.
pub addresses: Vec<crate::overlay::Cidr>,
/// Last error applying addresses or subnet routes on the shared interface.
pub address_error: Option<String>,
/// What has happened on it.
pub counters: crate::overlay::Counters,
/// The route and firewall allowance installed for LAN broadcast, when
@@ -168,6 +170,10 @@ pub struct PeerStatus {
pub transport: TransportKind,
/// RTT of the selected path, when iroh reported one.
pub rtt: Option<Duration>,
/// Recent RTT of the selected direct data link, measured by authenticated probes.
pub data_rtt: Option<Duration>,
/// The selected direct data carrier's own description of its underlying path.
pub data_transport_detail: Option<String>,
/// Per-connection counters.
pub connection: ConnectionCounters,
/// Control messages sent on this session.
+31 -1
View File
@@ -208,6 +208,7 @@ struct State {
/// Transport kinds, best first. A neighbour with several links is
/// reached over the first of these it has.
priority: Vec<String>,
preferred: HashMap<PeerId, String>,
graph: HashMap<PeerId, Vec<PeerId>>,
members: HashSet<PeerId>,
raw: HashMap<PeerId, Vec<RawLink>>,
@@ -229,7 +230,14 @@ impl State {
.get(peer)
.map(|links| links.iter().collect())
.unwrap_or_default();
links.sort_by_key(|raw| (self.rank(&raw.kind), raw.kind.clone()));
let preferred = self.preferred.get(peer);
links.sort_by_key(|raw| {
(
preferred != Some(&raw.kind),
self.rank(&raw.kind),
&raw.kind,
)
});
links
}
@@ -326,6 +334,7 @@ impl RelayHub {
tally: tally.clone(),
}),
priority: Vec::new(),
preferred: HashMap::new(),
graph: HashMap::new(),
members: HashSet::new(),
raw: HashMap::new(),
@@ -350,6 +359,23 @@ impl RelayHub {
}
}
/// Selects an already open carrier for this neighbour. The existing
/// immutable forwarding snapshot handles packet delivery and fallback.
pub(crate) fn prefer_direct(&self, peer: EndpointId, kind: &str) {
let mut state = self.state();
let id = peer.as_bytes();
if state.preferred.get(id).map(String::as_str) != Some(kind)
&& state.raw.get(id).is_some_and(|links| {
links
.iter()
.any(|raw| raw.kind == kind && !raw.link.is_closed())
})
{
state.preferred.insert(*id, kind.to_owned());
state.publish();
}
}
/// Wakes the control loop promptly when a transport reader ends.
pub async fn changed(&self) {
self.changed.notified().await;
@@ -477,6 +503,9 @@ impl RelayHub {
/// Removes one physical link without tearing down end-to-end protocol state.
pub fn clear_direct(&self, peer: EndpointId, kind: &str) {
let mut state = self.state();
if state.preferred.get(peer.as_bytes()).map(String::as_str) == Some(kind) {
state.preferred.remove(peer.as_bytes());
}
let mut changed = false;
if let Some(links) = state.raw.get_mut(peer.as_bytes()) {
if let Some(position) = links.iter().position(|known| known.kind == kind) {
@@ -495,6 +524,7 @@ impl RelayHub {
/// Retires data channels without removing an authenticated peer's topology.
pub fn clear_peer_links(&self, peer: EndpointId) {
let mut state = self.state();
state.preferred.remove(peer.as_bytes());
if let Some(links) = state.raw.remove(peer.as_bytes()) {
for raw in links {
raw.link.close();
@@ -20,6 +20,32 @@ fn tag() -> u64 {
envelope::protocol_tag("ip")
}
#[tokio::test]
async fn measuring_an_alternative_preserves_the_active_link_until_promotion() {
let hub = RelayHub::new(network(), peer(1));
hub.set_priority(vec!["first".into(), "second".into()]);
let first = Wire::new(2, true);
let second = Wire::new(2, true);
hub.set_direct(peer(2), "second", second.clone());
hub.prefer_direct(peer(2), "second");
hub.set_direct(peer(2), "first", first.clone());
let logical = hub.link(peer(2), "ip");
logical.send(Bytes::from_static(b"while testing")).unwrap();
assert_eq!(second.take().len(), 1);
assert!(first.take().is_empty());
hub.prefer_direct(peer(2), "first");
logical
.send(Bytes::from_static(b"after switching"))
.unwrap();
assert_eq!(first.take().len(), 1);
first.dead.store(true, Ordering::Relaxed);
logical.send(Bytes::from_static(b"fallback")).unwrap();
assert_eq!(second.take().len(), 1);
hub.clear_direct(peer(2), "first");
hub.set_direct(peer(2), "first", Wire::new(2, true));
assert!(Arc::ptr_eq(&logical, &hub.link(peer(2), "ip")));
}
#[derive(Debug)]
struct Wire {
peer: EndpointId,
@@ -1,6 +1,6 @@
//! Authenticated probes of the actual data link, independent of control RTT.
//! Keys are negotiated privately for each physical link. No fixed wire magic.
use super::{PacketLink, SharedLink, TransportError};
use super::{LinkQuality, PacketLink, SharedLink, TransportError};
use crate::{BoxFuture, NetworkId};
use bytes::Bytes;
use hmac::{Hmac, KeyInit, Mac};
@@ -32,40 +32,74 @@ impl std::fmt::Debug for Settings {
}
struct Samples {
pending: VecDeque<(u64, Instant)>,
recent: VecDeque<bool>,
recent: VecDeque<Option<Duration>>,
last_reply: Option<Instant>,
}
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
const WINDOW: usize = 20;
impl Samples {
fn new() -> Self {
Self {
pending: VecDeque::new(),
recent: VecDeque::new(),
last_reply: None,
}
}
fn sent(&mut self, seq: u64, now: Instant) {
self.pending.push_back((seq, now));
}
fn acknowledge(&mut self, seq: u64) {
if let Some(i) = self.pending.iter().position(|(n, _)| *n == seq) {
self.pending.remove(i);
self.recent.push_back(true);
fn record(&mut self, rtt: Option<Duration>) {
if self.recent.len() == WINDOW {
self.recent.pop_front();
}
self.recent.push_back(rtt);
}
fn acknowledge(&mut self, seq: u64, now: Instant) {
if let Some(i) = self.pending.iter().position(|(n, _)| *n == seq)
&& let Some((_, sent)) = self.pending.remove(i)
{
let rtt = now.saturating_duration_since(sent);
let success = rtt < PROBE_TIMEOUT;
self.record(success.then_some(rtt));
if success {
self.last_reply = Some(now);
}
}
}
fn expire(&mut self, now: Instant) {
while self
.pending
.front()
.is_some_and(|(_, at)| now.duration_since(*at) >= Duration::from_secs(3))
.is_some_and(|(_, at)| now.duration_since(*at) >= PROBE_TIMEOUT)
{
self.pending.pop_front();
self.recent.push_back(false);
}
while self.recent.len() > 20 {
self.recent.pop_front();
self.record(None);
}
}
fn degraded(&self) -> bool {
self.recent.len() >= 15
&& self.recent.iter().filter(|ok| !**ok).count() * 100 >= self.recent.len() * 60
&& self.recent.iter().filter(|rtt| rtt.is_none()).count() * 100
>= self.recent.len() * 60
}
fn quality(&self) -> Option<LinkQuality> {
let observed_at = self.last_reply?;
let mut delays = [Duration::ZERO; WINDOW];
let mut samples = 0;
for rtt in self.recent.iter().flatten() {
delays[samples] = *rtt;
samples += 1;
}
if samples == 0 {
return None;
}
delays[..samples].sort_unstable();
let rtt = (delays[(samples - 1) / 2] + delays[samples / 2]) / 2;
Some(LinkQuality {
rtt,
samples,
losses: self.recent.len() - samples,
observed_at,
})
}
}
/// A monitored physical link. It forwards application bytes unchanged.
@@ -75,6 +109,7 @@ pub(crate) struct HealthLink {
rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
stop: watch::Sender<bool>,
reason: Mutex<Option<String>>,
quality: Mutex<Option<([u8; 16], LinkQuality)>>,
}
impl std::fmt::Debug for HealthLink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -99,6 +134,7 @@ impl HealthLink {
rx: tokio::sync::Mutex::new(rx),
stop,
reason: Mutex::new(None),
quality: Mutex::new(None),
});
let weak = Arc::downgrade(&link);
let mut stopped = link.stop.subscribe();
@@ -117,6 +153,7 @@ impl HealthLink {
let Some(link)=weak.upgrade()else{break;};let Some(settings)=lock(&link.settings).clone()else{continue;};
if marker != Some(settings.marker) { marker = Some(settings.marker); samples = Samples::new(); since = None; }
let start=*since.get_or_insert_with(Instant::now);let now=Instant::now();samples.expire(now);
*lock(&link.quality) = samples.quality().map(|q| (settings.marker, q));
if now.duration_since(start)>=Duration::from_secs(20) && samples.degraded() {
*lock(&link.reason)=Some("data delivery checks: at least 60% loss over the last 20 probes".into());break;
}
@@ -132,7 +169,10 @@ impl HealthLink {
if let Some(settings)=settings && packet.starts_with(&settings.marker) {
if let Some((kind,seq))=verify(&settings,raw.peer(),&packet) {
if kind==1 {let _=raw.send(probe(&settings,local,2,seq,packet.len()));}
else if kind==2 {samples.acknowledge(seq);}
else if kind==2 && marker == Some(settings.marker) {
samples.acknowledge(seq, Instant::now());
*lock(&link.quality) = samples.quality().map(|q| (settings.marker, q));
}
}
} else {let _=tx.try_send(packet);}
}
@@ -149,6 +189,11 @@ impl HealthLink {
pub(crate) fn configure(&self, settings: Settings) {
*lock(&self.settings) = Some(settings);
}
pub(crate) fn profile_id(&self) -> Option<[u8; 16]> {
lock(&self.settings)
.as_ref()
.map(|settings| settings.marker)
}
}
fn probe(settings: &Settings, sender: EndpointId, kind: u8, seq: u64, size: usize) -> Bytes {
let mut bytes = vec![0; size.max(57)];
@@ -236,6 +281,15 @@ impl PacketLink for HealthLink {
.clone()
.or_else(|| self.raw.failure_reason())
}
fn quality(&self) -> Option<LinkQuality> {
if self.is_closed() {
return None;
}
let current = self.profile_id()?;
lock(&self.quality)
.filter(|(profile, quality)| *profile == current && quality.is_fresh(Instant::now()))
.map(|(_, quality)| quality)
}
fn path_description(&self) -> String {
self.raw.path_description()
}
@@ -251,6 +305,35 @@ impl Drop for HealthLink {
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn quality_uses_matched_fresh_replies_and_keeps_losses_in_the_window() {
let mut samples = Samples::new();
let start = Instant::now();
assert!(samples.quality().is_none());
for (seq, delay) in [(1, 10), (2, 30), (3, 250)] {
samples.sent(seq, start);
samples.acknowledge(seq, start + Duration::from_millis(delay));
}
samples.acknowledge(1, start + Duration::from_secs(1));
samples.sent(4, start);
samples.expire(start + Duration::from_secs(3));
samples.acknowledge(4, start + Duration::from_secs(4));
let measured = samples.quality().unwrap();
assert_eq!(measured.rtt, Duration::from_millis(30));
assert_eq!((measured.samples, measured.losses), (3, 1));
assert!(measured.is_fresh(start + Duration::from_secs(4)));
assert!(!measured.is_fresh(start + Duration::from_secs(6)));
for seq in 5..25 {
let sent = start + Duration::from_secs(seq);
samples.sent(seq, sent);
samples.acknowledge(seq, sent + Duration::from_millis(80));
}
let recovered = samples.quality().unwrap();
assert_eq!(recovered.rtt, Duration::from_millis(80));
assert_eq!((recovered.samples, recovered.losses), (20, 0));
}
#[test]
fn no_false_failure_before_window_but_persistent_loss_is_detected() {
let mut samples = Samples::new();
@@ -258,7 +341,7 @@ mod tests {
for seq in 0..20 {
samples.sent(seq, now);
if seq % 5 == 0 {
samples.acknowledge(seq);
samples.acknowledge(seq, now);
}
}
assert!(!samples.degraded());
@@ -266,7 +349,7 @@ mod tests {
assert!(samples.degraded());
for seq in 20..40 {
samples.sent(seq, now);
samples.acknowledge(seq);
samples.acknowledge(seq, now);
}
samples.expire(now + Duration::from_secs(4));
assert!(!samples.degraded());
@@ -37,6 +37,7 @@ pub mod carrier;
pub use carrier::{DataCarrier, SharedCarrier};
use std::sync::Arc;
use std::time::{Duration, Instant};
use bytes::Bytes;
use iroh::EndpointId;
@@ -73,6 +74,25 @@ pub enum TransportError {
Other(String),
}
/// Recent observations from authenticated round trips over a physical data link.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LinkQuality {
/// Median round-trip time of successful probes in the window.
pub rtt: Duration,
/// Successful probes in the window.
pub samples: usize,
/// Timed-out probes in the same window.
pub losses: usize,
/// Receipt time of the latest successful probe.
pub observed_at: Instant,
}
impl LinkQuality {
pub(crate) fn is_fresh(&self, now: Instant) -> bool {
now.saturating_duration_since(self.observed_at) <= Duration::from_secs(5)
}
}
/// An authenticated datagram channel to one peer, for one plugin protocol.
///
/// Dropping the link closes it.
@@ -125,6 +145,11 @@ pub trait PacketLink: Send + Sync + std::fmt::Debug + 'static {
None
}
/// Fresh measurements from this physical link's own authenticated probes.
fn quality(&self) -> Option<LinkQuality> {
None
}
/// A short description of the path in use, for diagnostics.
///
/// Reports what the transport actually knows. It must not invent a value.
+8 -2
View File
@@ -614,6 +614,8 @@ pub struct LeftReport {
/// Everything the agent is doing, in one snapshot.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatusReport {
/// Last error applying the shared overlay interface's host addresses and routes.
pub overlay_config_error: Option<String>,
/// Data-plane protocols this agent can enable at runtime.
pub available_protocols: Vec<ProtocolReport>,
/// This device's persistent endpoint id.
@@ -837,8 +839,12 @@ pub struct PeerReport {
/// How the connection reaches the peer: `direct`, `relay` or `unknown`,
/// as the transport reports it.
pub transport: String,
/// Round-trip time in milliseconds, when a path is selected.
/// Round-trip time of the control connection in milliseconds.
pub rtt_ms: Option<u64>,
/// Fresh median RTT of the selected direct data link, in milliseconds.
pub data_rtt_ms: Option<u64>,
/// Underlying path reported by the selected direct data carrier.
pub data_transport_detail: Option<String>,
/// The peer offers itself as an exit node in this network.
pub exit_node: bool,
/// How packets reach it.
@@ -1135,7 +1141,7 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
///
/// Bump it whenever [`Request`], [`Response`] or anything they contain
/// changes shape.
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 23]);
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 24]);
/// Reads one request off an accepted stream, answers it, writes the response.
///
+5 -3
View File
@@ -364,7 +364,9 @@ mod tests {
});
assert!(!is_serving(&path).await, "nothing serves the pipe yet");
let control = ControlSocket::bind(&path, source).await.unwrap();
let control = ControlSocket::bind(&path, source, ControlSocketAccess::Private)
.await
.unwrap();
assert!(is_serving(&path).await, "the agent serves it now");
let answer = exchange(&path, &Request::Status, EXCHANGE_TIMEOUT)
@@ -439,10 +441,10 @@ mod tests {
Box::pin(async { StatusReport::default() })
});
let first = ControlSocket::bind(&path, Arc::clone(&source))
let first = ControlSocket::bind(&path, Arc::clone(&source), ControlSocketAccess::Private)
.await
.unwrap();
let second = ControlSocket::bind(&path, source).await;
let second = ControlSocket::bind(&path, source, ControlSocketAccess::Private).await;
assert!(
matches!(second, Err(Error::StateLocked { .. })),
"{second:?}"
+113 -11
View File
@@ -222,16 +222,13 @@ fn local_addr_string(addr: &iroh::endpoint::LocalTransportAddr) -> Option<String
#[derive(Debug, Clone)]
pub struct EndpointAdapter {
endpoint: Endpoint,
owned_interface: Arc<std::sync::RwLock<String>>,
owned_interface: Arc<std::sync::OnceLock<String>>,
}
impl EndpointAdapter {
/// Excludes the real name after interface creation (macOS assigns utunN).
pub(crate) fn exclude_interface(&self, name: &str) {
*self
.owned_interface
.write()
.unwrap_or_else(|p| p.into_inner()) = name.to_lowercase();
let _ = self.owned_interface.set(name.to_owned());
}
/// Binds an endpoint according to `config`, reusing the persistent device key.
@@ -250,16 +247,40 @@ impl EndpointAdapter {
TransportPolicy::N0Defaults => builder.preset(presets::N0),
};
let owned_interface =
Arc::new(std::sync::RwLock::new(config.interface_name.to_lowercase()));
let owned_interface = Arc::new(std::sync::OnceLock::<String>::new());
{
let monitor_interface = Arc::clone(&owned_interface);
#[cfg(windows)]
let adapter_id = std::sync::OnceLock::<String>::new();
builder = builder.network_change_filter(move |previous, current| {
let Some(name) = monitor_interface.get() else {
return true;
};
// Wintun gives us its friendly name. netwatch keys Windows
// interfaces by GUID. Enumeration can lag adapter creation,
// so cache a successful lookup and retry a miss on later events.
#[cfg(windows)]
let Some(name) = adapter_id.get().or_else(|| {
let id = netdev::get_interfaces()
.into_iter()
.find(|iface| {
iface
.friendly_name
.as_deref()
.is_some_and(|alias| alias.eq_ignore_ascii_case(name))
})?
.name;
Some(adapter_id.get_or_init(|| id))
}) else {
return true;
};
!only_owned_interface_changed(previous, current, name)
});
let interface_filter = Arc::clone(&owned_interface);
let requested = config.interface_name.clone();
let factory = config.tun_factory.clone();
let filter = iroh::address_lookup::AddrFilter::new(move |addrs| {
let owned_interface = interface_filter
.read()
.unwrap_or_else(|p| p.into_inner())
.clone();
let owned_interface = interface_filter.get().unwrap_or(&requested).to_lowercase();
let mut overlay_ips = std::collections::HashSet::new();
if let Some(factory) = &factory {
overlay_ips.extend(factory.assigned_addresses());
@@ -493,3 +514,84 @@ impl EndpointAdapter {
self.endpoint.close().await;
}
}
/// netwatch treats every new unicast prefix as a link change. A second overlay
/// prefix on the same TUN cannot affect the paths carrying those tunnels.
pub(crate) fn only_owned_interface_changed(
previous: &netwatch::netmon::State,
current: &netwatch::netmon::State,
name: &str,
) -> bool {
if previous.default_route_interface != current.default_route_interface
|| current.default_route_interface.as_deref() == Some(name)
|| previous.last_unsuspend != current.last_unsuspend
|| previous.is_expensive != current.is_expensive
{
return false;
}
// Interface equality in netwatch covers identity and flags. Compare
// addresses separately, including family, prefix and IPv6 address flags.
let same_interface = |a: &netwatch::interfaces::Interface,
b: &netwatch::interfaces::Interface| {
a == b && a.addrs().eq(b.addrs())
};
let old_tun = previous.interfaces.get(name);
let new_tun = current.interfaces.get(name);
match (old_tun, new_tun) {
(None, None) => return false,
(Some(a), Some(b)) if same_interface(a, b) => return false,
_ => {}
}
// have_v4, have_v6 and local_addresses are derived from these interfaces
// and can all change when only the TUN changes.
let old_count = previous.interfaces.len() - usize::from(old_tun.is_some());
let new_count = current.interfaces.len() - usize::from(new_tun.is_some());
old_count == new_count
&& previous.interfaces.iter().all(|(iface, old)| {
iface == name
|| current
.interfaces
.get(iface)
.is_some_and(|new| same_interface(old, new))
})
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use netwatch::netmon::State;
#[test]
fn tun_address_changes_leave_existing_underlay_connections_alone() {
let before = State::fake();
let mut after = before.clone();
// netwatch keys interfaces by their OS name. Its fixture provides a
// unicast address, precisely the kind of change it classifies as major.
let tun = State::fake().interfaces.remove("wifi0").unwrap();
let address = tun.addrs().next().unwrap().addr();
after.interfaces.insert("utun7".into(), tun);
after.local_addresses.regular.push(address);
assert!(after.is_major_change(&before));
assert!(only_owned_interface_changed(&before, &after, "utun7"));
assert!(only_owned_interface_changed(&after, &before, "utun7"));
assert!(!only_owned_interface_changed(&before, &after, "utun6"));
// An update to the real underlay can arrive in the same notification.
let mut lost_wifi = after.clone();
lost_wifi.interfaces.remove("wifi0");
assert!(!only_owned_interface_changed(&before, &lost_wifi, "utun7"));
let mut changed_route = after.clone();
changed_route.default_route_interface = Some("utun7".to_owned());
assert!(!only_owned_interface_changed(
&before,
&changed_route,
"utun7"
));
let mut resumed = after;
resumed.last_unsuspend = Some(std::time::Instant::now().into());
assert!(!only_owned_interface_changed(&before, &resumed, "utun7"));
}
}
@@ -24,7 +24,7 @@
//! Policy routing, with no `/1` routes and nothing in the main table:
//!
//! ```text
//! table 0x7473: default dev <if>
//! table 0x7473: default dev <if> src <selected overlay address>
//! 5205: from all fwmark 0x40000000/0x40000000 lookup main
//! 5206: from all uidrange <euid>-<euid> lookup main
//! 5290: from all lookup main suppress_prefixlength 0
@@ -45,6 +45,7 @@
use crate::BoxFuture;
use crate::state::Ipv4Range;
use std::net::Ipv4Addr;
use super::RuleOutcome;
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules, exit_tag, exit_tag_prefix};
@@ -441,7 +442,7 @@ impl LinuxHostRules {
.map_err(|err| format!("the task failed: {err}"))
}
async fn apply_client(&self, interface: &str) -> RuleOutcome {
async fn apply_client(&self, interface: &str, source: Option<Ipv4Addr>) -> RuleOutcome {
let xdg = std::env::var("XDG_RUNTIME_DIR").ok();
if let Some(reason) = client_refusal(xdg.as_deref()) {
// Whatever an earlier run left must not stay in force.
@@ -461,7 +462,15 @@ impl LinuxHostRules {
.as_ref()
.is_some_and(|(name, _, routed)| name == interface && *routed);
if installed {
// A failed socket refresh must never remove an active exit route.
// A different network can now supply the exit on this same TUN.
// Preserve the policy rules and underlay protection during the switch.
let route = self.route.clone();
let name = interface.to_string();
match Self::blocking(move || route.update_exit_source(&name, source)).await {
Ok(Ok(())) => {}
Ok(Err(err)) => return RuleOutcome::Failed(err.to_string()),
Err(reason) => return RuleOutcome::Failed(reason),
}
return self
.refresh_sockets(interface)
.await
@@ -492,7 +501,8 @@ impl LinuxHostRules {
}
let route = self.route.clone();
let name = interface.to_string();
let outcome = match Self::blocking(move || route.set_exit_client(&name, euid)).await {
let outcome = match Self::blocking(move || route.set_exit_client(&name, euid, source)).await
{
Ok(Ok(())) => RuleOutcome::Applied,
Ok(Err(err)) => RuleOutcome::Failed(err.to_string()),
Err(reason) => RuleOutcome::Failed(reason),
@@ -616,7 +626,7 @@ impl ExitHostRules for LinuxHostRules {
forwarding_state(read_sysctl, &interface)
};
let client = if plan.client {
Some(self.apply_client(&interface).await)
Some(self.apply_client(&interface, plan.client_source).await)
} else {
if let Err(reason) = self.clear_client(&interface).await {
tracing::warn!(%reason, "cannot remove exit-client rules");
@@ -217,7 +217,9 @@ fn client() {
ip(&["-6", "route", "add", "throw", prefix, "table", "52"]);
}
let mut passive = spawn_listener("listener");
route.set_exit_client("tsun0", 990).unwrap();
route
.set_exit_client("tsun0", 990, Some("10.99.0.1".parse().unwrap()))
.unwrap();
// uid bypass alone cannot protect reverse lookups, reproducing the bug.
run_probes("blocked");
install(&run_firewall, "tsun0", 990, true).unwrap();
@@ -248,6 +250,25 @@ for family,source,target in [(socket.AF_INET,'198.51.100.2','192.0.2.1'),(socket
install(&run_firewall, "tsun0", 990, true).unwrap();
run_probes("pass");
assert!(ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]).contains("dev tsun0"));
// Check our own default table without the foreign VPN's higher-priority default.
ip(&["-4", "rule", "del", "priority", "5270"]);
for (destination, source) in [
("10.13.37.2", "10.13.37.1"),
("10.99.0.2", "10.99.0.1"),
("198.51.100.2", "10.99.0.1"),
] {
let result = ip(&["-4", "route", "get", destination, "uid", "991"]);
assert!(
result.contains("dev tsun0") && result.contains(&format!("src {source}")),
"{result}"
);
}
route
.update_exit_source("tsun0", Some("10.13.37.1".parse().unwrap()))
.unwrap();
assert!(ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]).contains("src 10.13.37.1"));
assert!(ip(&["-4", "route", "get", "10.99.0.2", "uid", "991"]).contains("src 10.99.0.1"));
ip(&["-4", "rule", "add", "priority", "5270", "table", "52"]);
let blocked = Command::new("ip")
.args(["-6", "route", "get", "2001:db8:2::2", "uid", "991"])
.output()
@@ -384,6 +405,15 @@ fn strict_firewall_preserves_underlay_and_application_exit_routing() {
"tsun0",
]);
ip(&["-n", &client_name, "link", "set", "tsun0", "up"]);
ip(&[
"-n",
&client_name,
"addr",
"add",
"10.99.0.1/24",
"dev",
"tsun0",
]);
let echo_code = r#"import socket,selectors,sys
selector=selectors.DefaultSelector()
for family in [socket.AF_INET,socket.AF_INET6]:
@@ -19,10 +19,10 @@
use crate::BoxFuture;
use std::sync::{Arc, Mutex};
use std::sync::Arc;
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules};
use super::macos_exit::{apply_plan, clear_all, run_tool};
use super::macos_exit::{HostState, apply_plan, clear_all, refresh_client, run_tool};
use super::{BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, RuleOutcome};
/// The limited-broadcast destination routed through the overlay interface.
@@ -68,17 +68,25 @@ fn firewall_todo(plan: &BroadcastRulesPlan) -> String {
/// `pf` plus `route` for exit nodes (see [`super::macos_exit`]).
#[derive(Debug, Default)]
pub struct MacosHostRules {
/// The reference `pfctl -E` handed out, held while exit-node rules need
/// `pf` on and released when they are removed.
pub(super) pf_token: Arc<Mutex<Option<String>>>,
/// The PF reference and the physical routes owned by this agent.
state: Arc<HostState>,
}
impl MacosHostRules {
/// Creates the host rules.
/// Creates host rules with process-lifetime ownership. System services
/// use [`Self::with_state_dir`] for recovery after abrupt termination.
pub fn new() -> Self {
Self::default()
}
/// Tie crash recovery to this agent's state directory, even when macOS
/// assigns its utun a different number on the next run.
pub fn with_state_dir(dir: &std::path::Path) -> Self {
Self {
state: Arc::new(HostState::with_state_dir(dir)),
}
}
/// Installs the route, replacing one this agent added earlier so the call
/// can be repeated. The delete is best effort: a route that is not there
/// is the state the add then reaches anyway.
@@ -95,7 +103,7 @@ impl ExitHostRules for MacosHostRules {
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
Box::pin(async move {
let job_plan = plan.clone();
let token = Arc::clone(&self.pf_token);
let token = Arc::clone(&self.state);
tokio::task::spawn_blocking(move || apply_plan(&run_tool, &token, &job_plan))
.await
.unwrap_or_else(|err| {
@@ -113,10 +121,23 @@ impl ExitHostRules for MacosHostRules {
})
}
fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
Box::pin(async move {
if !plan.client {
return None;
}
let state = Arc::clone(&self.state);
let plan = plan.clone();
tokio::task::spawn_blocking(move || refresh_client(&run_tool, &state, &plan))
.await
.unwrap_or_else(|err| Some(RuleOutcome::Failed(err.to_string())))
})
}
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
Box::pin(async move {
let name = interface.to_string();
let token = Arc::clone(&self.pf_token);
let token = Arc::clone(&self.state);
let _ = tokio::task::spawn_blocking(move || clear_all(&run_tool, &token, &name)).await;
})
}
@@ -16,9 +16,8 @@
//! evaluates `nat-anchor "com.apple/*"` and `anchor "com.apple/*"`, so the
//! rules take effect without editing the user's ruleset. `pf` cannot say
//! "every interface but one" in a translation address, so the egress is the
//! interface of the default route **when the rules are applied**; after the
//! default route moves (Wi-Fi to Ethernet) the rules are re-applied by
//! switching the exit node off and on, or restarting the agent.
//! interface of the physical default route. An active exit client refreshes
//! the rules when this egress changes.
//!
//! The kernel's `net.inet.ip.forwarding` is only read, never written: it
//! changes how the whole host behaves, which is the owner's decision.
@@ -29,21 +28,32 @@
//! Linux scheme does not carry over. Instead:
//!
//! ```text
//! route add -net 0.0.0.0/1 -interface <if>
//! route add -net 128.0.0.0/1 -interface <if>
//! route add -net 0.0.0.0/1 <gateway> -ifscope <egress>
//! route add -net 128.0.0.0/1 <gateway> -ifscope <egress>
//! route add -net 0.0.0.0/1 -interface <if> -ifa <selected overlay address>
//! route add -net 128.0.0.0/1 -interface <if> -ifa <selected overlay address>
//! pass out quick on <if> route-to (<egress> <gateway>) inet proto { tcp udp }
//! from any to ! <overlay ranges> user <agent uid>
//! nat on <egress> inet from (<if>) to any -> (<egress>)
//! from any to ! <overlay ranges> user <agent uid> tag <underlay> no state
//! nat on <egress> inet from (<if>) to any tagged <underlay> -> (<egress>) static-port
//! pass out quick on <egress> reply-to (lo0 127.0.0.1) inet proto { tcp udp }
//! from any to any flags any tagged <underlay> keep state (if-bound)
//! ```
//!
//! The two halves outrank the default route without replacing it, and every
//! more specific route (LAN, another VPN) keeps working. The `route-to` rule
//! The scoped routes preserve the physical path for sockets that already
//! use its source address. The unscoped halves capture ordinary internet
//! traffic. More specific routes (LAN and active meshes) keep working. The `route-to` rule
//! sends the *agent's own* traffic — QUIC, relay, DHT, which would otherwise
//! loop into the tunnel it carries — back out the physical interface, and the
//! translation gives it that interface's address, since an unbound socket
//! picked the overlay address when the route pointed at the overlay. Like the
//! Linux exemption this is by user id, so anything else running as root also
//! bypasses the tunnel.
//! picked the overlay address when the route pointed at the overlay. The
//! first pass is stateless: a floating `route-to` state would match again
//! on physical egress before PF could apply the translation. Only the egress
//! pass tracks the connection and reverses NAT on replies there. Once NAT
//! restores the socket's utun address, macOS's default hybrid end-system
//! model would discard the reply arriving over the physical interface.
//! `reply-to` delivers that state's replies locally through loopback. Like
//! the Linux exemption this is by user id, so anything else running as root
//! also bypasses the tunnel.
//!
//! IPv6 is blocked while an exit node is in use, as on Linux: `::/1` and
//! `8000::/1` are rejecting routes, so applications fall back to IPv4 at once
@@ -60,6 +70,13 @@ use crate::state::Ipv4Range;
use super::RuleOutcome;
use super::exit::{ExitHostPlan, ExitHostReport};
#[cfg(all(test, target_os = "macos", feature = "tun-device"))]
#[path = "macos_exit_kernel.rs"]
mod kernel;
#[path = "macos_scoped.rs"]
mod scoped;
use scoped::ScopedRoutes;
/// The programs this module runs, always by absolute path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Tool {
@@ -104,6 +121,7 @@ pub(super) fn run_tool(tool: Tool, args: &[String], stdin: Option<&str>) -> Ran
let mut command = Command::new(tool.path());
command
.env("LC_ALL", "C")
.args(args)
.stdin(if stdin.is_some() {
Stdio::piped()
@@ -162,12 +180,27 @@ fn anchor_name(interface: &str) -> Result<String, String> {
}
/// The default route as `route -n get default` reports it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(super) struct DefaultRoute {
pub interface: String,
pub gateway: Option<Ipv4Addr>,
}
#[derive(Debug, Default)]
pub(super) struct HostState {
token: Mutex<Option<String>>,
routes: Mutex<ScopedRoutes>,
}
impl HostState {
pub(super) fn with_state_dir(dir: &std::path::Path) -> Self {
Self {
routes: Mutex::new(ScopedRoutes::with_journal(dir.join("macos-exit-routes"))),
..Self::default()
}
}
}
/// Reads `interface:` and `gateway:` out of `route -n get default`.
fn parse_default_route(text: &str) -> Option<DefaultRoute> {
let field = |name: &str| {
@@ -206,8 +239,8 @@ fn run_ok(
Ran::Exited {
success: true,
stdout,
..
} => Ok(stdout),
stderr,
} if tool != Tool::Route || stderr.is_empty() => Ok(stdout),
Ran::Exited { stderr, stdout, .. } => Err(format!(
"{} {} failed: {}",
tool.path(),
@@ -276,16 +309,11 @@ fn pf_rules(
let out = &egress.interface;
let mut nat = Vec::new();
let mut filter = Vec::new();
for range in offer {
nat.push(format!("nat on {out} inet from {range} to any -> ({out})"));
filter.push(format!(
"pass in quick on {interface} inet from {range} to ! {range}"
));
}
let mut tables = Vec::new();
if let Some(client) = client {
let tag = format!("tsng_underlay_{interface}");
nat.push(format!(
"nat on {out} inet from ({interface}) to any -> ({out})"
"nat on {out} inet from ({interface}) to any tagged {tag} -> ({out}) static-port"
));
let target = if client.overlay.is_empty() {
"any".to_string()
@@ -305,9 +333,23 @@ fn pf_rules(
};
filter.push(format!(
"pass out quick on {interface} route-to {via} inet proto {{ tcp udp }} \
from any to {target} user {}",
from any to {target} user {} tag {tag} no state",
client.uid
));
// A relay TCP stream may already be established when exit routing changes.
// Only responses to tagged underlay traffic get local loopback delivery.
filter.push(format!(
"pass out quick on {out} reply-to (lo0 127.0.0.1) inet proto {{ tcp udp }} \
from any to any flags any tagged {tag} keep state (if-bound)"
));
}
for range in offer {
// PF takes the first matching NAT rule. Preserve the transport's source
// port even when its overlay source falls inside one of our own offers.
nat.push(format!("nat on {out} inet from {range} to any -> ({out})"));
filter.push(format!(
"pass in quick on {interface} inet from {range} to ! {range}"
));
}
tables
.into_iter()
@@ -367,10 +409,6 @@ fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
}
}
fn flush_args(anchor: &str) -> Vec<String> {
owned(&["-q", "-a", anchor, "-F", "all"])
}
fn load_args(anchor: &str) -> Vec<String> {
owned(&["-q", "-a", anchor, "-f", "-"])
}
@@ -380,8 +418,33 @@ const HALVES: [&str; 2] = ["0.0.0.0/1", "128.0.0.0/1"];
/// The IPv6 halves, made unreachable.
const HALVES_V6: [&str; 2] = ["::/1", "8000::/1"];
fn route_add_args(half: &str, interface: &str) -> Vec<String> {
owned(&["-q", "-n", "add", "-net", half, "-interface", interface])
/// A scoped route is available to sockets already using this egress. It
/// coexists with the unscoped route for ordinary applications.
fn scoped_args(action: &str, prefix: &str, egress: &DefaultRoute) -> Vec<String> {
let mut args = owned(&["-q", "-n", action, "-net", prefix]);
if let Some(gateway) = egress.gateway {
args.push(gateway.to_string());
} else {
args.extend(owned(&["-interface", &egress.interface]));
}
args.extend(owned(&["-ifscope", &egress.interface]));
if action != "delete" {
args.push("-proto2".into());
}
args
}
fn route_set_args(
action: &str,
half: &str,
interface: &str,
source: Option<Ipv4Addr>,
) -> Vec<String> {
let mut args = owned(&["-q", "-n", action, "-net", half, "-interface", interface]);
if let Some(source) = source {
args.extend(["-ifa".into(), source.to_string()]);
}
args
}
fn route_del_args(half: &str, interface: &str) -> Vec<String> {
@@ -396,46 +459,146 @@ fn route_del_v6_args(half: &str) -> Vec<String> {
owned(&["-q", "-n", "delete", "-inet6", "-net", half, "::1"])
}
fn captures_half(run: Run<'_>, half: &str, interface: &str) -> bool {
run_ok(run, Tool::Route, &owned(&["-n", "get", "-net", half]), None).is_ok_and(|text| {
scoped::field(&text, "mask") == Some("128.0.0.0")
&& scoped::field(&text, "interface") == Some(interface)
&& !scoped::flag(&text, "IFSCOPE")
})
}
/// Takes away the overlay default routes. Best effort: what is not there is
/// the state wanted.
fn clear_routes(run: Run<'_>, interface: &str) {
for half in HALVES {
let _ = run(Tool::Route, &route_del_args(half, interface), None);
}
for half in HALVES_V6 {
let _ = run(Tool::Route, &route_del_v6_args(half), None);
if captures_half(run, half, interface) {
let _ = run(Tool::Route, &route_del_args(half, interface), None);
}
}
}
fn set_routes(run: Run<'_>, interface: &str) -> Result<(), String> {
clear_routes(run, interface);
fn ipv6_reject(run: Run<'_>, half: &str) -> Result<Option<String>, String> {
let args = owned(&["-n", "get", "-inet6", "-net", half]);
match run_ok(run, Tool::Route, &args, None) {
Ok(text)
if scoped::flag(&text, "REJECT") && scoped::field(&text, "gateway") == Some("::1") =>
{
Ok(Some(text))
}
Ok(_) => Ok(None),
Err(why)
if why.contains("not in table")
|| why.contains("No such process")
|| why.contains("Address family not supported") =>
{
Ok(None)
}
Err(why) => Err(why),
}
}
fn clear_v6(run: Run<'_>, scoped: &mut ScopedRoutes) -> Result<(), String> {
let Some(marker) = scoped.ipv6_marker() else {
return Ok(());
};
for half in HALVES_V6 {
if ipv6_reject(run, half)?.is_some_and(|text| {
scoped::flag(&text, "PROTO2") && scoped::marker(&text) == Some(marker)
}) {
run_ok(run, Tool::Route, &route_del_v6_args(half), None)?;
}
}
scoped.record_ipv6(false).map(|_| ())
}
/// Installs a split default, or changes its source in place when the route
/// already belongs to this utun. Returns whether this call added it.
fn set_half(
run: Run<'_>,
half: &str,
interface: &str,
source: Option<Ipv4Addr>,
) -> Result<bool, String> {
match run_ok(
run,
Tool::Route,
&route_set_args("add", half, interface, source),
None,
) {
Ok(_) if captures_half(run, half, interface) => Ok(true),
Ok(_) => Err(format!(
"the unscoped route for {half} does not use {interface}"
)),
Err(why) if why.contains("File exists") => {
if !captures_half(run, half, interface) {
return Err(why);
}
run_ok(
run,
Tool::Route,
&route_set_args("change", half, interface, source),
None,
)?;
Ok(false)
}
Err(why) => Err(why),
}
}
fn set_routes(
run: Run<'_>,
interface: &str,
source: Option<Ipv4Addr>,
scoped: &mut ScopedRoutes,
) -> Result<(), String> {
let already_using_v6 = scoped.ipv6_marker().is_some();
let marker = scoped.record_ipv6(true)?;
let mut added = Vec::new();
for half in HALVES {
if let Err(why) = run_ok(run, Tool::Route, &route_add_args(half, interface), None) {
clear_routes(run, interface);
return Err(why);
match set_half(run, half, interface, source) {
Ok(true) => added.push(half),
Ok(false) => {}
Err(why) => {
for half in added {
let _ = run(Tool::Route, &route_del_args(half, interface), None);
}
if !already_using_v6 {
scoped.record_ipv6(false)?;
}
return Err(why);
}
}
}
for half in HALVES_V6 {
// A host without IPv6 has nothing to block; not a failure.
if let Err(why) = run_ok(run, Tool::Route, &route_add_v6_args(half), None) {
tracing::debug!(%why, "cannot block IPv6 for the exit node");
let mut args = route_add_v6_args(half);
args.extend(["-proto2".into(), "-hopcount".into(), marker.to_string()]);
if let Err(why) = run_ok(run, Tool::Route, &args, None) {
if why.contains("Address family not supported")
|| (why.contains("File exists")
&& ipv6_reject(run, half).is_ok_and(|route| route.is_some()))
{
continue;
}
for half in added {
let _ = run(Tool::Route, &route_del_args(half, interface), None);
}
if !already_using_v6 {
clear_v6(run, scoped)?;
}
return Err(why);
}
}
Ok(())
}
/// Makes the host match the plan.
pub(super) fn apply_plan(
run: Run<'_>,
token: &Mutex<Option<String>>,
plan: &ExitHostPlan,
) -> ExitHostReport {
pub(super) fn apply_plan(run: Run<'_>, state: &HostState, plan: &ExitHostPlan) -> ExitHostReport {
let forwarding = if plan.offer.is_empty() {
None
} else {
forwarding_state(run)
};
let outcome = apply_rules(run, token, plan);
let outcome = apply_rules(run, state, plan, None);
let verdict = |ok: bool, why: &str| {
if ok {
RuleOutcome::Applied
@@ -467,12 +630,16 @@ pub(super) fn apply_plan(
fn apply_rules(
run: Run<'_>,
token: &Mutex<Option<String>>,
state: &HostState,
plan: &ExitHostPlan,
checked_egress: Option<DefaultRoute>,
) -> Result<(), String> {
let interface = plan.interface.as_str();
let anchor = anchor_name(interface)?;
let egress = default_route(run, interface)?;
let egress = match checked_egress {
Some(egress) => egress,
None => default_route(run, interface)?,
};
let uid = if plan.client {
Some(agent_uid(run)?)
} else {
@@ -484,30 +651,99 @@ fn apply_rules(
});
let rules = pf_rules(interface, &egress, &plan.offer, client.as_ref());
acquire_pf(run, token)?;
let mut scoped = lock(&state.routes);
scoped.load()?;
acquire_pf(run, &state.token)?;
run_ok(run, Tool::Pfctl, &load_args(&anchor), Some(&rules))
.map_err(|why| format!("cannot load the pf rules: {why}"))?;
// The routes come after the rules that keep the agent's own traffic off
// them: the other order would loop for as long as it takes.
if plan.client {
set_routes(run, interface)?;
let previous = scoped.previous();
let wanted = ScopedRoutes::desired(&egress);
let result = scoped
.ensure(run, &wanted)
.and_then(|()| set_routes(run, interface, plan.client_source, &mut scoped));
if let Err(reason) = result {
// A same-interface gateway change may already have updated one
// scoped route. Restore the former gateway before dropping new adds.
if let Err(cleanup) = scoped
.ensure(run, &previous)
.and_then(|()| scoped.retain(run, &previous))
{
return Err(format!(
"{reason}; restoring prior scoped routes failed: {cleanup}"
));
}
return Err(reason);
}
scoped.retain(run, &wanted)?;
scoped.active = Some(egress);
} else {
clear_routes(run, interface);
clear_v6(run, &mut scoped)?;
scoped.retain(run, &[])?;
scoped.active = None;
}
Ok(())
}
/// Removes everything this agent put there for the interface.
pub(super) fn clear_all(run: Run<'_>, token: &Mutex<Option<String>>, interface: &str) {
pub(super) fn clear_all(run: Run<'_>, state: &HostState, interface: &str) {
let mut scoped = lock(&state.routes);
clear_routes(run, interface);
if let Err(why) = scoped
.load()
.and_then(|()| clear_v6(run, &mut scoped))
.and_then(|()| scoped.retain(run, &[]))
{
tracing::warn!(%why, "cannot remove scoped exit routes");
}
scoped.active = None;
if let Ok(anchor) = anchor_name(interface) {
// Flushing an anchor nothing was ever loaded into is not an error
// worth reporting.
if let Err(why) = run_ok(run, Tool::Pfctl, &flush_args(&anchor), None) {
if let Err(why) = run_ok(run, Tool::Pfctl, &load_args(&anchor), Some("")) {
tracing::debug!(%why, "cannot flush the exit node pf anchor");
}
}
release_pf(run, token);
release_pf(run, &state.token);
}
/// The logical plan can be unchanged while Wi-Fi changes gateway or moves
/// to Ethernet. Rebuild both PF and physical scope against that new egress.
pub(super) fn refresh_client(
run: Run<'_>,
state: &HostState,
plan: &ExitHostPlan,
) -> Option<RuleOutcome> {
if !plan.client || !lock(&state.routes).check_due(std::time::Instant::now()) {
return None;
}
let egress = match default_route(run, &plan.interface) {
Ok(egress) => egress,
Err(reason) => return Some(RuleOutcome::Failed(reason)),
};
{
let mut routes = lock(&state.routes);
if routes.active.as_ref() == Some(&egress) {
// A physical link may reconnect with the same name and gateway
// after the kernel has discarded that interface's scoped routes.
if let Err(reason) = routes.ensure(run, &ScopedRoutes::desired(&egress)) {
return Some(RuleOutcome::Failed(reason));
}
if HALVES
.iter()
.all(|half| captures_half(run, half, &plan.interface))
{
return None;
}
}
}
Some(match apply_rules(run, state, plan, Some(egress)) {
Ok(()) => RuleOutcome::Applied,
Err(reason) => RuleOutcome::Failed(reason),
})
}
#[cfg(test)]
@@ -545,6 +781,10 @@ destination: default\n\
pf_missing: bool,
pf_load_fails: bool,
route_add_fails: bool,
half_interface: Option<&'static str>,
v6: RefCell<std::collections::BTreeMap<String, u32>>,
capture: RefCell<std::collections::BTreeMap<String, String>>,
scoped: RefCell<std::collections::BTreeMap<(String, String), String>>,
pf_enable_output: &'static str,
}
@@ -558,6 +798,10 @@ destination: default\n\
pf_missing: false,
pf_load_fails: false,
route_add_fails: false,
half_interface: None,
v6: RefCell::default(),
capture: RefCell::default(),
scoped: RefCell::default(),
pf_enable_output: "pf enabled\nToken : 4242\n",
}
}
@@ -581,14 +825,101 @@ destination: default\n\
match tool {
Tool::Id => ok("0\n", ""),
Tool::Sysctl => ok(self.forwarding, ""),
Tool::Route if args.iter().any(|a| a == "-inet6") => {
let half = args[args.iter().position(|a| a == "-net").unwrap() + 1].clone();
let mut table = self.v6.borrow_mut();
if args.iter().any(|a| a == "get") {
return table.get(&half).map_or_else(|| fail("not in table"),|marker|
ok(&format!("gateway: ::1\nflags: <UP,REJECT,PROTO2>\nhopcount mtu\n{marker} 16384\n"),""));
}
if args.iter().any(|a| a == "delete") {
table.remove(&half);
} else if let std::collections::btree_map::Entry::Vacant(entry) =
table.entry(half)
{
entry.insert(args.last().unwrap().parse().unwrap());
} else {
return fail("File exists");
}
ok("", "")
}
Tool::Route if args.iter().any(|a| a == "-ifscope") => {
let after = |name: &str| {
args.iter()
.position(|a| a == name)
.map(|i| args[i + 1].clone())
};
let scope = after("-ifscope").unwrap();
let prefix = after("-net").unwrap();
let key = (scope.clone(), prefix.clone());
let mut table = self.scoped.borrow_mut();
if args.iter().any(|a| a == "get") {
return table
.get(&key)
.map_or_else(|| fail("not in table"), |text| ok(text, ""));
}
if args.iter().any(|a| a == "delete") {
table.remove(&key);
} else {
let gateway = args
.iter()
.find(|a| a.parse::<Ipv4Addr>().is_ok())
.cloned()
.unwrap_or_default();
let marker = after("-hopcount").unwrap();
table.insert(key, format!("destination: {}\nmask: 128.0.0.0\ninterface: {scope}\ngateway: {gateway}\nflags: <UP,PROTO2,IFSCOPE>\nhopcount mtu\n{marker} 1500\n", prefix.split('/').next().unwrap()));
}
ok("", "")
}
Tool::Route
if args.iter().any(|arg| arg == "get")
&& args.iter().any(|arg| arg == "-net") =>
{
let half = args.last().unwrap();
match self
.capture
.borrow()
.get(half)
.map(String::as_str)
.or(self.half_interface)
{
Some(name) => ok(&format!("mask: 128.0.0.0\ninterface: {name}\n"), ""),
None => fail("not in table"),
}
}
Tool::Route if args.first().map(String::as_str) == Some("-n") => {
match &self.default_route {
Some(text) => ok(text, ""),
None => fail("route: writing to routing socket: not in table"),
}
}
Tool::Route if args.contains(&"add".to_string()) && self.route_add_fails => {
fail("route: writing to routing socket: File exists")
Tool::Route
if args.contains(&"add".to_string())
&& ((self.route_add_fails && args.iter().any(|a| a == HALVES[1]))
|| args.iter().any(|a| self.capture.borrow().contains_key(a))
|| (self.half_interface.is_some()
&& HALVES.iter().any(|half| args.iter().any(|a| a == half)))) =>
{
// Darwin route can return success after a routing-socket write failed.
ok("", "route: writing to routing socket: File exists")
}
Tool::Route if args.iter().any(|a| a == "-interface") => {
let half = args
.iter()
.position(|a| a == "-net")
.map(|i| args[i + 1].clone())
.unwrap();
let iface = args
.iter()
.position(|a| a == "-interface")
.map(|i| args[i + 1].clone())
.unwrap();
if args.iter().any(|a| a == "delete") {
self.capture.borrow_mut().remove(&half);
} else {
self.capture.borrow_mut().insert(half, iface);
}
ok("", "")
}
Tool::Route => ok("", ""),
Tool::Pfctl if self.pf_missing => Ran::Missing,
@@ -669,7 +1000,27 @@ destination: default\n\
}
#[test]
fn using_sends_the_agents_own_traffic_back_out_the_physical_interface() {
fn the_agents_tagged_nat_precedes_any_general_masquerade_for_offered_ranges() {
let ranges = [range()];
let client = ClientRules {
uid: 0,
overlay: &ranges,
};
let text = pf_rules("utun5", &egress(), &ranges, Some(&client));
let mut nat = text.lines().filter(|line| line.starts_with("nat "));
assert!(
nat.next()
.unwrap()
.ends_with("tagged tsng_underlay_utun5 -> (en0) static-port")
);
assert_eq!(
nat.next(),
Some("nat on en0 inet from 10.13.37.0/24 to any -> (en0)")
);
}
#[test]
fn using_keeps_the_reroute_and_the_physical_nat_in_separate_pf_passes() {
let other: Ipv4Range = "10.99.0.0/16".parse().unwrap();
let overlay = [range(), other];
let client = ClientRules {
@@ -683,19 +1034,17 @@ destination: default\n\
),
"{text}"
);
assert!(
text.contains("nat on en0 inet from (utun5) to any -> (en0)\n"),
"{text}"
);
assert!(
text.contains(
let rules: Vec<_> = text.lines().skip(1).collect();
assert_eq!(
rules,
[
"nat on en0 inet from (utun5) to any tagged tsng_underlay_utun5 -> (en0) static-port",
"pass out quick on utun5 route-to (en0 192.168.1.1) inet proto { tcp udp } \
from any to ! <tsunagi_overlay_utun5> user 0\n"
),
"{text}"
from any to ! <tsunagi_overlay_utun5> user 0 tag tsng_underlay_utun5 no state",
"pass out quick on en0 reply-to (lo0 127.0.0.1) inet proto { tcp udp } from any to any flags any \
tagged tsng_underlay_utun5 keep state (if-bound)",
]
);
// Only the agent's user, and only what is not the overlay.
assert!(!text.contains("from any to any"));
let direct = DefaultRoute {
interface: "ppp0".into(),
@@ -718,7 +1067,11 @@ destination: default\n\
#[test]
fn the_overlay_default_routes_are_halves_and_ipv6_is_rejected() {
assert_eq!(
route_add_args("0.0.0.0/1", "utun5").join(" "),
scoped_args("add", "128.0.0.0/1", &egress()).join(" "),
"-q -n add -net 128.0.0.0/1 192.168.1.1 -ifscope en0 -proto2"
);
assert_eq!(
route_set_args("add", "0.0.0.0/1", "utun5", None).join(" "),
"-q -n add -net 0.0.0.0/1 -interface utun5"
);
assert_eq!(
@@ -746,7 +1099,7 @@ destination: default\n\
#[test]
fn offering_loads_the_anchor_and_reads_but_never_writes_forwarding() {
let fake = Fake::new();
let token = Mutex::new(None);
let token = HostState::default();
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
assert_eq!(report.offer, vec![(range(), RuleOutcome::Applied)]);
assert_eq!(report.forwarding, Some(true));
@@ -773,14 +1126,14 @@ destination: default\n\
);
// No client routes were added for an offer alone.
assert_eq!(fake.count(" add "), 0);
assert_eq!(token.lock().unwrap().as_deref(), Some("4242"));
assert_eq!(token.token.lock().unwrap().as_deref(), Some("4242"));
}
#[test]
fn forwarding_off_is_reported_and_unreadable_is_none() {
let mut fake = Fake::new();
fake.forwarding = "0\n";
let token = Mutex::new(None);
let token = HostState::default();
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
assert_eq!(report.forwarding, Some(false));
fake.forwarding = "junk";
@@ -791,12 +1144,18 @@ destination: default\n\
#[test]
fn the_client_rules_are_loaded_before_the_routes_that_need_them() {
let fake = Fake::new();
let token = Mutex::new(None);
let token = HostState::default();
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(false, true));
assert_eq!(report.client, Some(RuleOutcome::Applied));
assert!(report.offer.is_empty());
let load = fake.position("-f -").unwrap();
let add = fake.position(" add -net 0.0.0.0/1").unwrap();
let scoped = fake
.position(" add -net 128.0.0.0/1 192.168.1.1 -ifscope en0")
.unwrap();
let add = fake
.position(" add -net 0.0.0.0/1 -interface utun5")
.unwrap();
assert!(load < scoped && scoped < add);
assert!(load < add, "{:?}", fake.calls());
assert!(fake.position("add -net 128.0.0.0/1").is_some());
assert!(fake.position("-inet6 -net ::/1 ::1 -reject").is_some());
@@ -805,11 +1164,151 @@ destination: default\n\
assert!(fake.position("-n get default").unwrap() < add);
}
#[test]
fn both_exit_halves_use_the_selected_networks_address_on_a_shared_utun() {
let fake = Fake::new();
let token = HostState::default();
let mut selected = plan(false, true);
selected.overlay.push("10.99.0.0/24".parse().unwrap());
for (action, source) in [("add", "10.99.0.17"), ("change", "10.13.37.34")] {
selected.client_source = Some(source.parse().unwrap());
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &selected);
assert_eq!(report.client, Some(RuleOutcome::Applied));
for half in HALVES {
assert!(
fake.position(&format!(
"{action} -net {half} -interface utun5 -ifa {source}"
))
.is_some()
);
}
}
}
#[test]
fn changing_the_active_exit_keeps_both_halves_routed_through_its_utun() {
let mut selected = plan(false, true);
selected.client_source = Some("10.99.0.17".parse().unwrap());
let mut fake = Fake::new();
fake.half_interface = Some("utun5");
let report = apply_plan(
&|t, a, s| fake.run(t, a, s),
&HostState::default(),
&selected,
);
assert_eq!(report.client, Some(RuleOutcome::Applied));
for half in HALVES {
assert!(
fake.position(&format!(
"change -net {half} -interface utun5 -ifa 10.99.0.17"
))
.is_some()
);
}
assert_eq!(fake.count(" delete "), 0);
let mut foreign = Fake::new();
foreign.half_interface = Some("utun9");
let report = apply_plan(
&|t, a, s| foreign.run(t, a, s),
&HostState::default(),
&selected,
);
assert!(matches!(report.client, Some(RuleOutcome::Failed(_))));
assert_eq!(foreign.count(" change "), 0);
assert!(
foreign.scoped.borrow().is_empty(),
"new scoped routes were rolled back"
);
assert_eq!(foreign.count("delete -net 0.0.0.0/1 -interface utun9"), 0);
}
#[test]
fn restart_cleans_scoped_routes_by_journal_and_kernel_marker_even_on_a_new_utun() {
let fake = Fake::new();
let dir = tempfile::tempdir().unwrap();
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
let state = HostState::with_state_dir(dir.path());
assert_eq!(
apply_plan(&run, &state, &plan(false, true)).client,
Some(RuleOutcome::Applied)
);
assert_eq!(fake.scoped.borrow().len(), 2);
// An administrator replaces one of the two routes before we restart.
for ((_, half), listing) in fake.scoped.borrow_mut().iter_mut() {
if half == HALVES[0] {
*listing = listing.replace("PROTO2", "STATIC");
}
}
drop(state);
clear_all(&run, &HostState::with_state_dir(dir.path()), "utun9");
assert_eq!(fake.scoped.borrow().len(), 1);
assert!(
fake.scoped
.borrow()
.contains_key(&("en0".into(), HALVES[0].into()))
);
assert!(!dir.path().join("macos-exit-routes").exists());
}
#[test]
fn cleanup_preserves_an_ipv6_reject_installed_by_another_owner() {
let fake = Fake::new();
fake.v6.borrow_mut().insert("::/1".into(), 0);
let dir = tempfile::tempdir().unwrap();
let state = HostState::with_state_dir(dir.path());
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
assert_eq!(
apply_plan(&run, &state, &plan(false, true)).client,
Some(RuleOutcome::Applied)
);
assert_eq!(fake.v6.borrow().len(), 2);
clear_all(&run, &HostState::with_state_dir(dir.path()), "utun9");
assert_eq!(
fake.v6.borrow().keys().cloned().collect::<Vec<_>>(),
["::/1"]
);
}
#[test]
fn refreshing_a_changed_gateway_updates_pf_and_replaces_only_our_previous_scope() {
let mut fake = Fake::new();
let state = HostState::default();
let plan = plan(false, true);
assert_eq!(
apply_plan(&|t, a, s| fake.run(t, a, s), &state, &plan).client,
Some(RuleOutcome::Applied)
);
fake.default_route = Some(
DEFAULT_ROUTE
.replace("en0", "en1")
.replace("192.168.1.1", "10.0.0.1"),
);
assert_eq!(
refresh_client(&|t, a, s| fake.run(t, a, s), &state, &plan),
Some(RuleOutcome::Applied)
);
assert_eq!(fake.scoped.borrow().len(), 2);
assert!(
fake.scoped
.borrow()
.keys()
.all(|(interface, _)| interface == "en1")
);
assert!(
fake.stdins
.borrow()
.last()
.unwrap()
.contains("route-to (en1 10.0.0.1)")
);
}
#[test]
fn no_routes_are_added_when_the_rules_did_not_load() {
let mut fake = Fake::new();
fake.pf_load_fails = true;
let token = Mutex::new(None);
let token = HostState::default();
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, true));
let Some(RuleOutcome::Failed(why)) = report.client else {
panic!("{report:?}");
@@ -826,7 +1325,7 @@ destination: default\n\
fn a_failing_route_is_a_failure_and_leaves_nothing_behind() {
let mut fake = Fake::new();
fake.route_add_fails = true;
let token = Mutex::new(None);
let token = HostState::default();
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(false, true));
let Some(RuleOutcome::Failed(why)) = report.client else {
panic!("{report:?}");
@@ -849,7 +1348,7 @@ destination: default\n\
fn a_missing_pfctl_or_default_route_says_what_is_wrong() {
let mut fake = Fake::new();
fake.pf_missing = true;
let token = Mutex::new(None);
let token = HostState::default();
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
let RuleOutcome::Failed(why) = &report.offer[0].1 else {
panic!("{report:?}");
@@ -870,7 +1369,7 @@ destination: default\n\
fn a_default_route_through_the_overlay_is_refused() {
let mut fake = Fake::new();
fake.default_route = Some("gateway: 10.13.37.1\ninterface: utun5\n".into());
let token = Mutex::new(None);
let token = HostState::default();
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
let RuleOutcome::Failed(why) = &report.offer[0].1 else {
panic!("{report:?}");
@@ -881,7 +1380,7 @@ destination: default\n\
#[test]
fn pf_is_enabled_once_and_released_once_on_clear() {
let fake = Fake::new();
let token = Mutex::new(None);
let token = HostState::default();
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
apply_plan(&run, &token, &plan(true, false));
apply_plan(&run, &token, &plan(true, true));
@@ -889,15 +1388,12 @@ destination: default\n\
clear_all(&run, &token, "utun5");
assert_eq!(fake.count("Pfctl -X 4242"), 1);
assert!(
fake.position("-a com.apple/tsunagi-exit-utun5 -F all")
.is_some()
);
assert_eq!(fake.stdins.borrow().last().map(String::as_str), Some(""));
assert!(
fake.position("delete -net 0.0.0.0/1 -interface utun5")
.is_some()
);
assert_eq!(*token.lock().unwrap(), None);
assert_eq!(*token.token.lock().unwrap(), None);
// A second clear has nothing to release and still succeeds.
clear_all(&run, &token, "utun5");
assert_eq!(fake.count("Pfctl -X"), 1);
@@ -906,10 +1402,15 @@ destination: default\n\
#[test]
fn dropping_the_client_removes_its_routes() {
let fake = Fake::new();
let token = Mutex::new(None);
let token = HostState::default();
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
assert_eq!(
apply_plan(&run, &token, &plan(false, true)).client,
Some(RuleOutcome::Applied)
);
let adds = fake.count(" add ");
apply_plan(&run, &token, &plan(true, false));
assert!(fake.position("delete -net 0.0.0.0/1").is_some());
assert_eq!(fake.count(" add "), 0);
assert_eq!(fake.count(" add "), adds);
}
}
@@ -0,0 +1,339 @@
//! Privileged macOS regression. Both ends are throwaway utuns; only a /30
//! inside the simulated uplink is captured when switching the exit on.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::net::Ipv4Addr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use bytes::Bytes;
use smoltcp::wire::{IpProtocol, Ipv4Packet, Ipv4Repr, TcpPacket, TcpSeqNumber, UdpPacket};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpStream, UdpSocket};
use tokio::time::timeout;
use super::*;
use crate::overlay::Cidr;
use crate::overlay::provision::{InterfacePlan, InterfaceProvisioner, UtunProvisioner};
use crate::overlay::tun::TunDevice;
const UPLINK: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 1);
const REMOTE: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 6);
const CAPTURE: &str = "192.0.2.4/30";
const FIRST: Ipv4Addr = Ipv4Addr::new(198, 18, 222, 1);
const SECOND: Ipv4Addr = Ipv4Addr::new(198, 19, 222, 1);
const WAIT: Duration = Duration::from_secs(5);
async fn utun(addresses: &[Ipv4Addr]) -> Arc<dyn TunDevice> {
let cidrs = addresses
.iter()
.map(|ip| Cidr::new((*ip).into(), 28).unwrap())
.collect();
UtunProvisioner::new()
.unwrap()
.reconcile(&InterfacePlan::new("test", 1280, cidrs))
.await
.unwrap()
.device
.unwrap()
}
struct Capture<'a> {
overlay: &'a str,
uplink: DefaultRoute,
anchor: String,
token: Mutex<Option<String>>,
added_route: bool,
added_scoped: bool,
}
impl Drop for Capture<'_> {
fn drop(&mut self) {
if self.added_route {
let _ = run_tool(Tool::Route, &route_del_args(CAPTURE, self.overlay), None);
}
if self.added_scoped {
let _ = run_tool(
Tool::Route,
&scoped_args("delete", CAPTURE, &self.uplink),
None,
);
}
// Loading an empty ruleset removes just this temporary anchor's rules.
let _ = run_tool(Tool::Pfctl, &load_args(&self.anchor), Some(""));
release_pf(&run_tool, &self.token);
}
}
impl Capture<'_> {
fn enable(&mut self) {
let ranges = [FIRST, SECOND]
.map(|ip| Ipv4Range::new(Ipv4Addr::from(u32::from(ip) & !0xf), 28).unwrap());
let rules = pf_rules(
self.overlay,
&self.uplink,
&[],
Some(&ClientRules {
uid: 0,
overlay: &ranges,
}),
);
acquire_pf(&run_tool, &self.token).unwrap();
run_ok(
&run_tool,
Tool::Pfctl,
&load_args(&self.anchor),
Some(&rules),
)
.unwrap();
run_ok(
&run_tool,
Tool::Route,
&scoped::marked_args("add", CAPTURE, &self.uplink, 114275),
None,
)
.unwrap();
self.added_scoped = true;
run_ok(
&run_tool,
Tool::Route,
&route_set_args("add", CAPTURE, self.overlay, Some(SECOND)),
None,
)
.unwrap();
self.added_route = true;
}
}
/// Ignore interface housekeeping and pure TCP ACKs while waiting for our packet.
async fn packet(
device: &dyn TunDevice,
destination: Ipv4Addr,
protocol: IpProtocol,
port: u16,
payload: &[u8],
) -> Bytes {
timeout(WAIT, async {
loop {
let raw = device.recv().await.expect("utun closed");
let Ok(ip) = Ipv4Packet::new_checked(&raw[..]) else {
continue;
};
if ip.version() != 4 || ip.dst_addr() != destination || ip.next_header() != protocol {
continue;
}
let matches = match protocol {
IpProtocol::Udp => UdpPacket::new_checked(ip.payload())
.is_ok_and(|udp| udp.dst_port() == port && udp.payload() == payload),
IpProtocol::Tcp => TcpPacket::new_checked(ip.payload()).is_ok_and(|tcp| {
tcp.dst_port() == port
&& tcp.payload() == payload
&& (tcp.syn() || !payload.is_empty())
}),
_ => false,
};
if matches {
return raw;
}
}
})
.await
.unwrap_or_else(|_| {
panic!(
"no {protocol} packet for {destination}:{port} on {}",
device.name()
)
})
}
fn reply(request: &[u8]) -> Bytes {
let ip = Ipv4Packet::new_checked(request).unwrap();
let tcp_request = (ip.next_header() == IpProtocol::Tcp)
.then(|| TcpPacket::new_checked(ip.payload()).unwrap());
// Acknowledge TCP SYNs and echo data so the test observes return traffic
// on the very socket that originated each flow.
let reply_ip = Ipv4Repr {
src_addr: ip.dst_addr(),
dst_addr: ip.src_addr(),
next_header: ip.next_header(),
payload_len: tcp_request
.as_ref()
.map_or(ip.payload().len(), |tcp| 20 + tcp.payload().len()),
hop_limit: 64,
};
let mut bytes = vec![0; reply_ip.buffer_len() + reply_ip.payload_len];
let mut out = Ipv4Packet::new_unchecked(&mut bytes[..]);
reply_ip.emit(&mut out, &Default::default());
let src = reply_ip.src_addr.into();
let dst = reply_ip.dst_addr.into();
if let Some(incoming) = tcp_request {
let mut tcp = TcpPacket::new_unchecked(out.payload_mut());
tcp.set_header_len(20);
tcp.set_src_port(incoming.dst_port());
tcp.set_dst_port(incoming.src_port());
tcp.set_syn(incoming.syn());
tcp.set_ack(true);
tcp.set_seq_number(if incoming.syn() {
TcpSeqNumber(100)
} else {
incoming.ack_number()
});
tcp.set_ack_number(incoming.seq_number() + incoming.segment_len());
tcp.set_window_len(8192);
tcp.payload_mut().copy_from_slice(incoming.payload());
tcp.fill_checksum(&src, &dst);
} else {
out.payload_mut().copy_from_slice(ip.payload());
let mut udp = UdpPacket::new_unchecked(out.payload_mut());
let (src_port, dst_port) = (udp.dst_port(), udp.src_port());
udp.set_src_port(src_port);
udp.set_dst_port(dst_port);
udp.fill_checksum(&src, &dst);
}
bytes.into()
}
async fn open_tcp(uplink: &dyn TunDevice, port: u16) -> TcpStream {
let connect = TcpStream::connect((REMOTE, port));
let peer = async {
let syn = packet(uplink, REMOTE, IpProtocol::Tcp, port, &[]).await;
assert_eq!(
Ipv4Packet::new_checked(&syn[..]).unwrap().src_addr(),
UPLINK
);
uplink.send(reply(&syn)).await.unwrap();
};
let (stream, ()) = tokio::join!(timeout(WAIT, connect), peer);
stream.expect("SYN-ACK did not reach socket").unwrap()
}
fn check_capture_routes(overlay: &str, uplink: &str) {
for (scope, expected) in [(vec![], overlay), (owned(&["-ifscope", uplink]), uplink)] {
let mut args = owned(&["-n", "get"]);
args.extend(scope);
args.extend(owned(&["-net", CAPTURE]));
let output = run_ok(&run_tool, Tool::Route, &args, None).unwrap();
eprintln!("route {}:\n{output}", args.join(" "));
let actual = output
.lines()
.find_map(|line| line.trim().strip_prefix("interface: "));
assert_eq!(actual, Some(expected));
assert_eq!(output.contains("PROTO2"), expected == uplink);
assert_eq!(output.contains("IFSCOPE"), expected == uplink);
assert_eq!(
output.split_whitespace().any(|s| s == "114275"),
expected == uplink
);
}
}
async fn udp_round_trip(uplink: &dyn TunDevice, socket: &UdpSocket, stage: &str) {
let port = socket.peer_addr().unwrap().port();
eprintln!("{stage}: UDP {}", socket.local_addr().unwrap());
socket
.send(b"QUIC path")
.await
.unwrap_or_else(|e| panic!("{stage}: sending UDP: {e}"));
let raw = packet(uplink, REMOTE, IpProtocol::Udp, port, b"QUIC path").await;
let ip = Ipv4Packet::new_checked(&raw[..]).unwrap();
assert_eq!(ip.src_addr(), UPLINK);
assert_eq!(
UdpPacket::new_checked(ip.payload()).unwrap().src_port(),
socket.local_addr().unwrap().port()
);
uplink.send(reply(&raw)).await.unwrap();
let mut buf = [0; 64];
let len = timeout(WAIT, socket.recv(&mut buf))
.await
.expect("UDP reply did not reach socket")
.unwrap();
assert_eq!(&buf[..len], b"QUIC path");
}
#[tokio::test]
#[ignore = "requires root, the stock Apple PF anchor, and a disposable macOS runner"]
async fn exit_preserves_underlay_and_both_meshes() {
assert_eq!(agent_uid(&run_tool).unwrap(), 0);
let uplink = utun(&[UPLINK]).await;
let overlay = utun(&[FIRST, SECOND]).await;
let mut relay = open_tcp(&*uplink, 8001).await;
let existing_quic = UdpSocket::bind((UPLINK, 0)).await.unwrap();
existing_quic.connect((REMOTE, 8006)).await.unwrap();
udp_round_trip(&*uplink, &existing_quic, "before exit").await;
let mut capture = Capture {
overlay: overlay.name(),
uplink: DefaultRoute {
interface: uplink.name().to_owned(),
gateway: Some(Ipv4Addr::new(192, 0, 2, 2)),
},
anchor: anchor_name(overlay.name()).unwrap(),
token: Mutex::new(None),
added_route: false,
added_scoped: false,
};
capture.enable();
check_capture_routes(overlay.name(), uplink.name());
udp_round_trip(&*uplink, &existing_quic, "existing socket after exit").await;
// An already established relay must preserve its address and port.
relay.write_all(b"established relay").await.unwrap();
let established = packet(
&*uplink,
REMOTE,
IpProtocol::Tcp,
8001,
b"established relay",
)
.await;
let ip = Ipv4Packet::new_checked(&established[..]).unwrap();
let tcp = TcpPacket::new_checked(ip.payload()).unwrap();
assert_eq!(ip.src_addr(), UPLINK);
assert_eq!(tcp.src_port(), relay.local_addr().unwrap().port());
uplink.send(reply(&established)).await.unwrap();
let mut echo = [0; b"established relay".len()];
timeout(WAIT, relay.read_exact(&mut echo))
.await
.expect("established TCP reply did not reach socket")
.unwrap();
assert_eq!(&echo, b"established relay");
// The kernel selects the overlay source on new wildcard sockets. Real
// replies to the translated address must reach those same sockets.
let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap();
socket.connect((REMOTE, 8002)).await.unwrap();
assert_eq!(socket.local_addr().unwrap().ip(), SECOND);
udp_round_trip(&*uplink, &socket, "new socket after exit").await;
let new_relay = open_tcp(&*uplink, 8003).await;
assert_eq!(new_relay.local_addr().unwrap().ip(), SECOND);
// Same destination, ordinary UID: external traffic must enter the exit.
let program = "import socket, sys\nsocket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(b'ordinary', (sys.argv[1], 8004))";
let mut child = tokio::process::Command::new("/usr/bin/python3");
child
.uid(65534)
.gid(65534)
.args(["-I", "-c", program, &REMOTE.to_string()])
.kill_on_drop(true);
assert!(
timeout(WAIT, child.status())
.await
.unwrap()
.unwrap()
.success()
);
let ordinary = packet(&*overlay, REMOTE, IpProtocol::Udp, 8004, b"ordinary").await;
assert_eq!(
Ipv4Packet::new_checked(&ordinary[..]).unwrap().src_addr(),
SECOND
);
// Root traffic to either mesh also stays on the overlay with its own alias.
let mesh = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap();
for local in [FIRST, SECOND] {
let peer = Ipv4Addr::from(u32::from(local) + 1);
mesh.send_to(b"mesh", (peer, 8005)).await.unwrap();
let raw = packet(&*overlay, peer, IpProtocol::Udp, 8005, b"mesh").await;
assert_eq!(Ipv4Packet::new_checked(&raw[..]).unwrap().src_addr(), local);
}
}
@@ -0,0 +1,309 @@
//! Route ownership survives the process that installed the scoped physical
//! routes. A pre-existing compatible route may be used, never adopted.
use super::*;
use std::fs;
use std::io::{Read, Write};
use std::path::PathBuf;
use std::time::{Duration, Instant};
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(super) struct ScopedHalf {
half: u8,
egress: DefaultRoute,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct Journal {
marker: u32,
routes: Vec<ScopedHalf>,
ipv6: bool,
}
#[derive(Debug)]
pub(super) struct ScopedRoutes {
journal: Option<PathBuf>,
loaded: bool,
owned: Journal,
pub(super) active: Option<DefaultRoute>,
checked: Option<Instant>,
}
impl Default for ScopedRoutes {
fn default() -> Self {
Self {
journal: None,
loaded: false,
owned: Journal {
marker: rand::random_range(1..i32::MAX as u32),
routes: Vec::new(),
ipv6: false,
},
active: None,
checked: None,
}
}
}
pub(super) fn marked_args(
action: &str,
prefix: &str,
egress: &DefaultRoute,
marker: u32,
) -> Vec<String> {
let mut args = scoped_args(action, prefix, egress);
// Darwin exposes this otherwise unused route metric through RTM_GET.
// The nonce separates routes made by independent agents on the same uplink.
args.extend(["-hopcount".into(), marker.to_string()]);
args
}
pub(super) fn field<'a>(text: &'a str, key: &str) -> Option<&'a str> {
text.lines()
.filter_map(|l| l.trim().split_once(':'))
.find_map(|(k, v)| (k == key).then(|| v.trim()))
}
pub(super) fn flag(text: &str, name: &str) -> bool {
field(text, "flags").is_some_and(|v| v.trim_matches(['<', '>']).split(',').any(|f| f == name))
}
pub(super) fn marker(text: &str) -> Option<u32> {
let mut lines = text.lines();
while let Some(line) = lines.next() {
if let Some(i) = line.split_whitespace().position(|v| v == "hopcount") {
return lines.next()?.split_whitespace().nth(i)?.parse().ok();
}
}
None
}
/// A scoped lookup can return an unscoped LAN route or a default. Only an
/// exact scoped /1 on the requested interface can be ours.
fn inspect(
run: Run<'_>,
route: &ScopedHalf,
) -> Result<Option<(DefaultRoute, Option<u32>)>, String> {
let args = owned(&[
"-n",
"get",
"-ifscope",
&route.egress.interface,
"-net",
HALVES[route.half as usize],
]);
let text = match run_ok(run, Tool::Route, &args, None) {
Ok(text) => text,
Err(err)
if err.contains("not in table")
|| err.contains("No such process")
|| err.contains("bad interface name") =>
{
return Ok(None);
}
Err(err) => return Err(err),
};
let destination = field(&text, "destination");
let correct_half = match route.half {
0 => matches!(destination, Some("default" | "0.0.0.0")),
_ => destination == Some("128.0.0.0"),
};
if !correct_half || field(&text, "mask") != Some("128.0.0.0") || !flag(&text, "IFSCOPE") {
return Ok(None);
}
let actual = parse_default_route(&text).ok_or("could not read scoped route interface")?;
if actual.interface != route.egress.interface {
return Ok(None);
}
let mark = flag(&text, "PROTO2").then(|| marker(&text)).flatten();
Ok(Some((actual, mark)))
}
impl ScopedRoutes {
pub(super) fn with_journal(path: PathBuf) -> Self {
Self {
journal: Some(path),
..Self::default()
}
}
pub(super) fn load(&mut self) -> Result<(), String> {
if self.loaded {
return Ok(());
}
if let Some(path) = &self.journal {
match fs::File::open(path) {
Ok(file) => {
let mut bytes = Vec::new();
file.take(4097)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
if bytes.len() > 4096 {
return Err("oversized macOS exit route journal".into());
}
let data: Journal = postcard::from_bytes(&bytes)
.map_err(|e| format!("invalid macOS exit route journal: {e}"))?;
if data.marker == 0
|| data.routes.len() > 8
|| data
.routes
.iter()
.any(|r| r.half > 1 || !safe_name(&r.egress.interface))
{
return Err("invalid macOS exit route ownership".into());
}
self.owned = data;
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => return Err(err.to_string()),
}
}
self.loaded = true;
Ok(())
}
fn save(&self) -> Result<(), String> {
let Some(path) = &self.journal else {
return Ok(());
};
if self.owned.routes.is_empty() && !self.owned.ipv6 {
return match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e.to_string()),
};
}
let tmp = path.with_extension(format!("{}.tmp", rand::random::<u64>()));
let mut options = fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let bytes = postcard::to_allocvec(&self.owned).map_err(|err| err.to_string())?;
let mut file = options.open(&tmp).map_err(|err| err.to_string())?;
let result = file.write_all(&bytes).and_then(|()| fs::rename(&tmp, path));
if result.is_err() {
let _ = fs::remove_file(tmp);
}
result.map_err(|e| e.to_string())
}
pub(super) fn previous(&self) -> Vec<ScopedHalf> {
self.owned.routes.clone()
}
pub(super) fn ipv6_marker(&self) -> Option<u32> {
self.owned.ipv6.then_some(self.owned.marker)
}
pub(super) fn record_ipv6(&mut self, active: bool) -> Result<u32, String> {
if self.owned.ipv6 != active {
self.owned.ipv6 = active;
if let Err(why) = self.save() {
self.owned.ipv6 = !active;
return Err(why);
}
}
Ok(self.owned.marker)
}
pub(super) fn desired(egress: &DefaultRoute) -> Vec<ScopedHalf> {
[0, 1]
.map(|half| ScopedHalf {
half,
egress: egress.clone(),
})
.into()
}
pub(super) fn check_due(&mut self, now: Instant) -> bool {
if self
.checked
.is_some_and(|last| now.duration_since(last) < Duration::from_secs(15))
{
return false;
}
self.checked = Some(now);
true
}
pub(super) fn ensure(&mut self, run: Run<'_>, wanted: &[ScopedHalf]) -> Result<(), String> {
for route in wanted {
let current = inspect(run, route)?;
let action = match current {
Some((actual, tag))
if actual == route.egress
&& (tag.is_none()
|| tag == Some(self.owned.marker)
&& self.owned.routes.contains(route)) =>
{
continue;
}
Some((actual, Some(tag)))
if tag == self.owned.marker
&& self.owned.routes.contains(&ScopedHalf {
half: route.half,
egress: actual.clone(),
}) =>
{
"change"
}
Some(_) => {
return Err(format!(
"scoped route {} on {} already belongs to another route owner",
HALVES[route.half as usize], route.egress.interface
));
}
None => "add",
};
if !self.owned.routes.contains(route) {
if self.owned.routes.len() >= 8 {
return Err("too many unreconciled scoped exit routes".into());
}
self.owned.routes.push(route.clone());
if let Err(reason) = self.save() {
self.owned.routes.pop();
return Err(reason);
}
}
run_ok(
run,
Tool::Route,
&marked_args(
action,
HALVES[route.half as usize],
&route.egress,
self.owned.marker,
),
None,
)?;
if inspect(run, route)? != Some((route.egress.clone(), Some(self.owned.marker))) {
return Err(format!(
"the scoped route for {} on {} failed ownership verification",
HALVES[route.half as usize], route.egress.interface
));
}
}
Ok(())
}
pub(super) fn retain(&mut self, run: Run<'_>, keep: &[ScopedHalf]) -> Result<(), String> {
for route in self.previous() {
if keep.contains(&route) {
continue;
}
if inspect(run, &route)? == Some((route.egress.clone(), Some(self.owned.marker))) {
run_ok(
run,
Tool::Route,
&scoped_args("delete", HALVES[route.half as usize], &route.egress),
None,
)?;
}
self.owned.routes.retain(|r| r != &route);
if let Err(reason) = self.save() {
self.owned.routes.push(route);
return Err(reason);
}
}
Ok(())
}
}
@@ -28,6 +28,10 @@
#![cfg_attr(not(target_os = "windows"), allow(dead_code))]
use crate::BoxFuture;
use std::collections::{BTreeMap, HashMap};
use std::net::Ipv4Addr;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules};
use super::windows_exit;
@@ -119,7 +123,7 @@ fn run_powershell(script: &str) -> Result<(), String> {
}
/// Runs a script and returns what it printed, or what it said on failure.
fn run_powershell_output(script: &str) -> Result<String, String> {
pub(super) fn run_powershell_output(script: &str) -> Result<String, String> {
let output = std::process::Command::new(powershell_path())
.args([
"-NoProfile",
@@ -153,12 +157,61 @@ async fn step(what: &'static str, script: String) -> RuleOutcome {
/// The Windows implementation, through PowerShell.
#[derive(Debug, Default)]
pub struct WindowsHostRules;
pub struct WindowsHostRules {
relay_cache: Arc<Mutex<RelayCache>>,
}
impl WindowsHostRules {
/// Creates it. Nothing is run until [`BroadcastHostRules::apply`].
pub fn new() -> Self {
Self
Self::default()
}
}
const REFRESH_INTERVAL: Duration = Duration::from_secs(30);
const DNS_GRACE: Duration = Duration::from_secs(120);
const MAX_RELAY_ADDRESSES: usize = 16;
/// DNS may rotate while the old relay connection is still carrying packets.
/// Keep recent answers for the relays still in use, with a fixed expiry and cap.
#[derive(Debug, Default)]
struct RelayCache {
hosts: HashMap<String, BTreeMap<Ipv4Addr, Instant>>,
last_refresh: Option<Instant>,
}
impl RelayCache {
fn lookup(
&mut self,
hosts: &[String],
now: Instant,
resolve: windows_exit::Resolve<'_>,
) -> HashMap<String, Vec<Ipv4Addr>> {
self.hosts.retain(|host, _| hosts.contains(host));
let due = self
.last_refresh
.is_none_or(|last| now.duration_since(last) >= REFRESH_INTERVAL);
for host in hosts {
let known = self.hosts.entry(host.clone()).or_default();
known.retain(|_, seen| now.duration_since(*seen) < DNS_GRACE);
if due || known.is_empty() {
for address in resolve(host).into_iter().take(MAX_RELAY_ADDRESSES) {
known.insert(address, now);
}
while known.len() > MAX_RELAY_ADDRESSES {
if let Some((&oldest, _)) = known.iter().min_by_key(|(_, seen)| **seen) {
known.remove(&oldest);
}
}
}
}
if due {
self.last_refresh = Some(now);
}
self.hosts
.iter()
.map(|(host, addresses)| (host.clone(), addresses.keys().copied().collect()))
.collect()
}
}
@@ -173,6 +226,7 @@ fn resolve_host(host: &str) -> Vec<std::net::Ipv4Addr> {
IpAddr::V4(ip) => Some(ip),
IpAddr::V6(_) => None,
})
.take(MAX_RELAY_ADDRESSES)
.collect()
})
.unwrap_or_default()
@@ -186,10 +240,16 @@ impl ExitHostRules for WindowsHostRules {
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
Box::pin(async move {
let job = plan.clone();
let cache = Arc::clone(&self.relay_cache);
tokio::task::spawn_blocking(move || {
let hosts = cache.lock().unwrap_or_else(|p| p.into_inner()).lookup(
&job.bypass_hosts,
Instant::now(),
&resolve_host,
);
windows_exit::apply_plan(
&|script| run_powershell_output(script),
&resolve_host,
&|host| hosts.get(host).cloned().unwrap_or_default(),
&job,
)
})
@@ -209,10 +269,46 @@ impl ExitHostRules for WindowsHostRules {
})
}
fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
Box::pin(async move {
if !plan.client {
return None;
}
let job = plan.clone();
let cache = Arc::clone(&self.relay_cache);
tokio::task::spawn_blocking(move || {
let now = Instant::now();
let mut cache = cache.lock().unwrap_or_else(|p| p.into_inner());
if cache
.last_refresh
.is_some_and(|last| now.duration_since(last) < REFRESH_INTERVAL)
{
return None;
}
let hosts = cache.lookup(&job.bypass_hosts, now, &resolve_host);
drop(cache);
Some(
match windows_exit::refresh_bypass(
&run_powershell_output,
&|host| hosts.get(host).cloned().unwrap_or_default(),
&job,
) {
Ok(()) => RuleOutcome::Applied,
Err(reason) => RuleOutcome::Failed(reason),
},
)
})
.await
.unwrap_or_else(|err| Some(RuleOutcome::Failed(format!("the task failed: {err}"))))
})
}
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
Box::pin(async move {
let name = interface.to_string();
let cache = Arc::clone(&self.relay_cache);
let _ = tokio::task::spawn_blocking(move || {
*cache.lock().unwrap_or_else(|p| p.into_inner()) = RelayCache::default();
windows_exit::clear_all(&|script| run_powershell_output(script), &name)
})
.await;
@@ -258,6 +354,29 @@ mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn relay_dns_survives_a_transient_failure_and_retires_rotated_addresses() {
use std::time::{Duration, Instant};
let mut cache = RelayCache::default();
let hosts = vec!["relay.example".into()];
let old = [192, 0, 2, 1].into();
let new = [192, 0, 2, 2].into();
let now = Instant::now();
assert_eq!(cache.lookup(&hosts, now, &|_| vec![old])[&hosts[0]], [old]);
let later = |secs| now + Duration::from_secs(secs);
assert_eq!(
cache.lookup(&hosts, later(32), &|_| Vec::new())[&hosts[0]],
[old]
);
let rotated = cache.lookup(&hosts, later(64), &|_| vec![new]);
assert!(rotated[&hosts[0]].contains(&old) && rotated[&hosts[0]].contains(&new));
assert_eq!(
cache.lookup(&hosts, later(121), &|_| vec![new])[&hosts[0]],
[new]
);
assert!(cache.lookup(&[], later(122), &|_| Vec::new()).is_empty());
}
use std::net::Ipv4Addr;
fn plan() -> BroadcastRulesPlan {
@@ -108,8 +108,8 @@ fn forwarding_script(interface: &str) -> String {
)
}
/// Prints `<interface index> <next hop>` of the best default route that is
/// not through the overlay interface.
/// Prints the physical default and the more specific routes that already
/// outrank the split defaults. Ignore our own host routes when refreshing.
fn gateway_script(interface: &str) -> String {
let alias = ps_literal(interface);
format!(
@@ -121,7 +121,11 @@ fn gateway_script(interface: &str) -> String {
(Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }} | \
Select-Object -First 1\n\
if (-not $best) {{ throw 'the host has no default gateway outside the overlay' }}\n\
\"$($best.InterfaceIndex) $($best.NextHop)\"\n"
\"$($best.InterfaceIndex) $($best.NextHop)\"\n\
Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore | Where-Object {{ \
$_.InterfaceAlias -ne $alias -and $_.State -ne 'Dead' -and \
-not ($_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32')) }} | \
Select-Object -ExpandProperty DestinationPrefix\n"
)
}
@@ -141,13 +145,18 @@ fn bypass_script(index: u32, gateway: Ipv4Addr, addresses: &[Ipv4Addr]) -> Strin
.collect();
format!(
"$ErrorActionPreference = 'Stop'\n\
$keep = @(@({}) | ForEach-Object {{ \"$_/32\" }})\n\
foreach ($p in $keep) {{\n\
if (-not (Get-NetRoute -DestinationPrefix $p -InterfaceIndex {index} -NextHop '{gateway}' \
-PolicyStore ActiveStore -ErrorAction SilentlyContinue)) {{\n\
New-NetRoute -DestinationPrefix $p -InterfaceIndex {index} -NextHop '{gateway}' \
-RouteMetric {BYPASS_METRIC} -PolicyStore ActiveStore | Out-Null\n\
}}\n\
}}\n\
Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore -ErrorAction SilentlyContinue | \
Where-Object {{ $_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32') }} | \
Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n\
foreach ($ip in @({})) {{\n\
New-NetRoute -DestinationPrefix \"$ip/32\" -InterfaceIndex {index} -NextHop '{gateway}' \
-RouteMetric {BYPASS_METRIC} -PolicyStore ActiveStore -ErrorAction SilentlyContinue | Out-Null\n\
}}\n",
Where-Object {{ $_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32') -and \
($keep -notcontains $_.DestinationPrefix -or $_.InterfaceIndex -ne {index} -or $_.NextHop -ne '{gateway}') }} | \
Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n",
list.join(", ")
)
}
@@ -159,14 +168,14 @@ fn halves_script(interface: &str) -> String {
"$ErrorActionPreference = 'Stop'\n\
$alias = {alias}\n\
foreach ($p in '0.0.0.0/1', '128.0.0.0/1') {{\n\
Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -PolicyStore ActiveStore \
-ErrorAction SilentlyContinue | Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n\
if (Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '0.0.0.0' \
-PolicyStore ActiveStore -ErrorAction SilentlyContinue) {{ continue }}\n\
New-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '0.0.0.0' \
-RouteMetric 1 -PolicyStore ActiveStore | Out-Null\n\
}}\n\
foreach ($p in '::/1', '8000::/1') {{\n\
Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -PolicyStore ActiveStore \
-ErrorAction SilentlyContinue | Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n\
if (Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '::' \
-PolicyStore ActiveStore -ErrorAction SilentlyContinue) {{ continue }}\n\
New-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '::' \
-RouteMetric 1 -PolicyStore ActiveStore -ErrorAction SilentlyContinue | Out-Null\n\
}}\n"
@@ -197,27 +206,60 @@ fn bypass_addresses(
resolve: Resolve<'_>,
addresses: &[Ipv4Addr],
hosts: &[String],
overlay: &[Ipv4Range],
) -> Vec<Ipv4Addr> {
let mut all: std::collections::BTreeSet<Ipv4Addr> = addresses.iter().copied().collect();
for host in hosts {
all.extend(resolve(host));
}
all.into_iter()
.filter(|a| !a.is_loopback() && !a.is_unspecified() && !a.is_multicast())
.filter(|a| {
!a.is_loopback()
&& !a.is_unspecified()
&& !a.is_multicast()
&& !a.is_link_local()
&& !a.is_broadcast()
&& !overlay.iter().any(|range| range.contains(*a))
})
.collect()
}
pub(super) fn refresh_bypass(
run: RunScript<'_>,
resolve: Resolve<'_>,
plan: &ExitHostPlan,
) -> Result<(), String> {
let interface = plan.interface.as_str();
let gateway = run(&gateway_script(interface))?;
let mut lines = gateway.lines();
let first = lines.next().unwrap_or_default();
let (index, hop) = parse_gateway(first)
.ok_or_else(|| format!("cannot read the default gateway from `{first}`"))?;
let mut addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts, &plan.overlay);
for line in lines {
let prefix = line.trim();
let (network, bits) = prefix
.split_once('/')
.and_then(|(address, bits)| {
Some((address.parse::<Ipv4Addr>().ok()?, bits.parse::<u8>().ok()?))
})
.filter(|(_, bits)| *bits <= 32)
.ok_or_else(|| format!("cannot read physical route prefix `{prefix}`"))?;
if bits > 1 {
let mask = u32::MAX << (32 - bits);
addresses.retain(|addr| u32::from(*addr) & mask != u32::from(network) & mask);
}
}
run(&bypass_script(index, hop, &addresses)).map(|_| ())
}
fn apply_client(
run: RunScript<'_>,
resolve: Resolve<'_>,
plan: &ExitHostPlan,
) -> Result<(), String> {
let interface = plan.interface.as_str();
let gateway = run(&gateway_script(interface))?;
let (index, hop) = parse_gateway(&gateway)
.ok_or_else(|| format!("cannot read the default gateway from `{}`", gateway.trim()))?;
let addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts);
run(&bypass_script(index, hop, &addresses))?;
refresh_bypass(run, resolve, plan)?;
let interface = &plan.interface;
if let Err(why) = run(&halves_script(interface)) {
// Do not leave a half-installed set: bypass routes alone are harmless
// but the next apply starts clean.
@@ -399,6 +441,58 @@ mod tests {
Vec::new()
}
/// Run the real refresh against the Windows ActiveStore. The fixture
/// only permits its TEST-NET /32 and refuses to prune pre-existing routes.
#[cfg(windows)]
#[test]
#[ignore = "requires an elevated disposable Windows runner with a physical default gateway"]
fn windows_refresh_installs_only_the_external_test_address() {
use super::super::windows::run_powershell_output;
let target = Ipv4Addr::new(198, 51, 100, 207);
let inventory = run_powershell_output(&gateway_script("tsng-native-test")).unwrap();
let (index, gateway) = parse_gateway(inventory.lines().next().unwrap()).unwrap();
let plan = ExitHostPlan {
interface: "tsng-native-test".into(),
bypass: vec![gateway, target],
client: true,
..Default::default()
};
let run = |script: &str| {
if script == gateway_script(&plan.interface) {
return Ok(inventory.clone());
}
// Catch a failure to recognize the gateway's connected LAN before
// executing a script which might create a route to the gateway.
assert!(script.contains(&format!("$keep = @(@('{target}') |")));
let guarded = format!(
r#"$ErrorActionPreference = 'Stop'
$prefix = '{target}/32'
$before = @(Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore | Where-Object {{
$_.DestinationPrefix -eq $prefix -or ($_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32'))
}})
if ($before.Count) {{ throw 'fixture requires an unused test prefix and no pre-existing bypass routes' }}
try {{
{script}
$actual = @(Get-NetRoute -DestinationPrefix $prefix -PolicyStore ActiveStore -ErrorAction Stop)
if ($actual.Count -ne 1 -or $actual[0].InterfaceIndex -ne {index} -or
$actual[0].NextHop -ne '{gateway}' -or $actual[0].RouteMetric -ne {BYPASS_METRIC}) {{
throw 'unexpected physical bypass route'
}}
}} finally {{
Get-NetRoute -DestinationPrefix $prefix -InterfaceIndex {index} -NextHop '{gateway}' -PolicyStore ActiveStore -ErrorAction SilentlyContinue |
Where-Object {{ $_.RouteMetric -eq {BYPASS_METRIC} }} | Remove-NetRoute -Confirm:$false
}}
if (Get-NetRoute -DestinationPrefix $prefix -PolicyStore ActiveStore -ErrorAction SilentlyContinue) {{
throw 'test route still present after cleanup'
}}
exit 0"#
);
run_powershell_output(&guarded)
};
refresh_bypass(&run, &no_names, &plan).unwrap();
}
fn client_plan() -> ExitHostPlan {
ExitHostPlan {
interface: "tsun0".into(),
@@ -437,8 +531,10 @@ mod tests {
assert!(script.contains("-InterfaceIndex 12 -NextHop '192.168.1.1'"));
assert!(script.contains("-RouteMetric 7373"));
assert!(script.contains("-PolicyStore ActiveStore"));
// Stale marked routes go first, and only /32 ones with our metric.
assert!(script.find("Remove-NetRoute").unwrap() < script.find("New-NetRoute").unwrap());
// Install missing routes before pruning stale entries. Existing paths
// continue carrying the tunnel throughout another network's update.
assert!(script.find("New-NetRoute").unwrap() < script.find("Remove-NetRoute").unwrap());
assert!(script.contains("$keep -notcontains $_.DestinationPrefix"));
assert!(script.contains("RouteMetric -eq 7373"));
assert!(script.contains("EndsWith('/32')"));
}
@@ -446,6 +542,10 @@ mod tests {
#[test]
fn the_halves_go_through_the_overlay_and_ipv6_is_blackholed() {
let script = halves_script("tsun0");
assert!(
!script.contains("Remove-NetRoute"),
"reapplying must keep existing split defaults: {script}"
);
assert!(script.contains("'0.0.0.0/1', '128.0.0.0/1'"));
assert!(script.contains("-InterfaceAlias $alias -NextHop '0.0.0.0'"));
assert!(script.contains("'::/1', '8000::/1'"));
@@ -473,6 +573,7 @@ mod tests {
Ipv4Addr::UNSPECIFIED,
],
&["relay.example".into(), "gone.example".into()],
&[],
);
assert_eq!(
all,
@@ -505,12 +606,77 @@ mod tests {
);
}
#[test]
fn relay_dns_cannot_install_a_host_route_over_either_overlay() {
let mut plan = client_plan();
plan.overlay.push("10.99.0.0/24".parse().unwrap());
let resolve = |_: &str| {
["10.13.37.4", "10.99.0.6", "9.9.9.9"]
.map(|ip| ip.parse().unwrap())
.to_vec()
};
let calls = RefCell::new(Vec::new());
let run = |script: &str| {
calls.borrow_mut().push(script.to_string());
Ok("12 192.168.1.1".to_string())
};
apply_client(&run, &resolve, &plan).unwrap();
let calls = calls.borrow();
let bypass = calls
.iter()
.find(|c| c.contains("-RouteMetric 7373"))
.unwrap();
assert!(bypass.contains("'9.9.9.9'") && bypass.contains("'138.201.61.182'"));
assert!(!bypass.contains("'10.13.37.4'") && !bypass.contains("'10.99.0.6'"));
}
#[test]
fn a_connected_lan_and_an_existing_host_route_stay_on_their_own_paths() {
let mut plan = client_plan();
for addr in ["192.168.1.11", "198.51.100.7", "198.51.100.9"] {
plan.bypass.push(addr.parse().unwrap());
}
let calls = RefCell::new(Vec::new());
let run = |script: &str| {
calls.borrow_mut().push(script.to_string());
Ok("12 192.168.1.1\n192.168.1.0/24\n198.51.100.7/32\n".into())
};
apply_client(&run, &no_names, &plan).unwrap();
let calls = calls.borrow();
let bypass = calls.iter().find(|s| s.contains("New-NetRoute")).unwrap();
assert!(!bypass.contains("'192.168.1.11'"));
assert!(!bypass.contains("'198.51.100.7'"));
assert!(bypass.contains("'198.51.100.9'"));
}
#[test]
fn refreshing_uses_the_new_physical_gateway_without_touching_the_exit_routes() {
let plan = client_plan();
let routes = RefCell::new(Vec::new());
for gateway in ["12 192.168.1.1", "17 10.0.0.1"] {
let run = |script: &str| {
if script.contains("Select-Object -First 1") {
Ok(gateway.into())
} else {
routes.borrow_mut().push(script.to_owned());
Ok(String::new())
}
};
refresh_bypass(&run, &no_names, &plan).unwrap();
}
let routes = routes.into_inner();
assert_eq!(routes.len(), 2);
assert!(routes[0].contains("-InterfaceIndex 12 -NextHop '192.168.1.1'"));
assert!(routes[1].contains("-InterfaceIndex 17 -NextHop '10.0.0.1'"));
assert!(routes.iter().all(|s| !s.contains("'0.0.0.0/1'")));
}
#[test]
fn nothing_goes_through_the_overlay_when_the_bypass_cannot_be_written() {
let run = |script: &str| -> Result<String, String> {
if script.contains("Select-Object -First 1") {
Ok("12 192.168.1.1".to_string())
} else if script.contains("-RouteMetric 7373") && script.contains("foreach ($ip") {
} else if script.contains("-RouteMetric 7373") && script.contains("New-NetRoute") {
Err("Access is denied".to_string())
} else {
assert!(!script.contains("-NextHop '0.0.0.0'"), "{script}");
+194 -32
View File
@@ -35,7 +35,7 @@ use super::hostrules::{
RuleOutcome, offer_detail,
};
use super::packet::IpHeader;
use super::router::{Route, RoutingTable};
use super::router::{PacketSource, Route, RoutingTable};
use super::tun::{TunDevice, TunFactory, TunRequest};
use super::{Cidr, OverlayError};
@@ -153,9 +153,7 @@ pub struct Interface {
routes: Arc<RoutingTable>,
carrier: Arc<dyn PacketCarrier>,
tally: Arc<Tally>,
/// What was last applied to the host, so an unchanged table is not
/// re-applied on every pass.
applied: std::sync::Mutex<Vec<Cidr>>,
addresses: std::sync::Mutex<AddressState>,
task: std::sync::Mutex<Option<JoinHandle<()>>>,
vip_task: std::sync::Mutex<Option<JoinHandle<()>>>,
sync_lock: Arc<tokio::sync::Mutex<()>>,
@@ -171,6 +169,13 @@ pub struct Interface {
underlay: std::sync::Mutex<std::collections::HashMap<NetworkId, Underlay>>,
}
/// Addresses and subnet routes are applied together. A partial change
/// invalidates the cached plan until the whole interface reconciles again.
struct AddressState {
applied: Option<Vec<Cidr>>,
last_error: Option<String>,
}
/// Underlay destinations one network's runtime currently depends on.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct Underlay {
@@ -336,7 +341,10 @@ impl Interface {
routes,
carrier,
tally,
applied: std::sync::Mutex::new(Vec::new()),
addresses: std::sync::Mutex::new(AddressState {
applied: Some(Vec::new()),
last_error: None,
}),
task: std::sync::Mutex::new(Some(task)),
vip_task: std::sync::Mutex::new(Some(vip_task)),
sync_lock: Arc::new(tokio::sync::Mutex::new(())),
@@ -420,6 +428,9 @@ impl Interface {
ranges.sort_by_key(|range| (range.base, range.prefix_len));
ranges.dedup();
let (client, client_source) = self.routes.exit_client();
#[cfg(windows)]
self.device
.set_exit_source(&self.wanted_addresses(), client_source);
let overlay = self.routes.overlay_ranges();
let (bypass, bypass_hosts) = if client && exit.needs_bypass() {
self.underlay_targets(&overlay)
@@ -513,6 +524,14 @@ impl Interface {
state.report = Some(report);
}
/// Whether the host routes its own transport by destination.
pub(crate) fn needs_underlay_targets(&self) -> bool {
self.host_rules
.as_ref()
.and_then(|rules| rules.exit_rules())
.is_some_and(|exit| exit.needs_bypass())
}
/// Tells the interface where a network's runtime reaches peers and
/// relays outside the overlay. When the host needs those kept out of the
/// exit node's default route and the set changed, the rules follow.
@@ -537,13 +556,7 @@ impl Interface {
map.insert(network, new.clone()) != Some(new)
}
};
let needed = changed
&& self.routes.exit_via().is_some()
&& self
.host_rules
.as_ref()
.and_then(|rules| rules.exit_rules())
.is_some_and(|exit| exit.needs_bypass());
let needed = changed && self.routes.exit_via().is_some() && self.needs_underlay_targets();
if needed {
self.sync_exit_rules().await;
}
@@ -700,13 +713,13 @@ impl Interface {
let _guard = self.sync_lock.lock().await;
let wanted = self.wanted_addresses();
{
let applied = match self.applied.lock() {
Ok(guard) => guard.clone(),
Err(poisoned) => poisoned.into_inner().clone(),
};
if applied == wanted {
let mut addresses = self.addresses.lock().unwrap_or_else(|e| e.into_inner());
if addresses.applied.as_ref() == Some(&wanted) {
return Ok(());
}
// A failed or cancelled reconfiguration can leave some aliases or
// routes installed. Even a return to the previous plan must retry.
addresses.applied = None;
}
// Every address this agent holds, in every network it is in. The
@@ -717,12 +730,25 @@ impl Interface {
addresses: wanted.clone(),
mtu: self.mtu,
};
self.factory.reconfigure(request).await?;
match self.applied.lock() {
Ok(mut guard) => *guard = wanted,
Err(poisoned) => *poisoned.into_inner() = wanted,
let result = self.factory.reconfigure(request).await;
let mut addresses = self.addresses.lock().unwrap_or_else(|e| e.into_inner());
match &result {
Ok(()) => {
addresses.applied = Some(wanted);
addresses.last_error = None;
}
Err(err) => addresses.last_error = Some(format!("{}: {err}", self.name)),
}
Ok(())
result
}
/// Last error applying the shared interface's addresses and subnet routes.
pub fn address_error(&self) -> Option<String> {
self.addresses
.lock()
.unwrap_or_else(|e| e.into_inner())
.last_error
.clone()
}
/// The interface name the operating system gave.
@@ -810,12 +836,19 @@ impl Interface {
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::WrongFamily);
};
if !self.routes.may_send_from(network, peer, source) {
let Some(origin) = self.routes.packet_source(network, peer, source) else {
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::WrongSource);
}
let broadcast = match header.destination() {
IpAddr::V4(destination) if self.routes.is_broadcast(destination) => {
};
let broadcast = match (origin, header.destination()) {
(PacketSource::ExitReply { local: Some(local) }, IpAddr::V4(destination))
if destination == local =>
{
false
}
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_broadcast(destination) =>
{
if !super::broadcast::valid_udp(&packet)
|| !self.routes.accepts_broadcast(network, peer, destination)
{
@@ -824,12 +857,10 @@ impl Interface {
}
true
}
IpAddr::V4(destination) if self.routes.is_local_destination(network, destination) => {
false
}
// This agent is an exit node of this network: a member's packet
// for the internet goes to the host, which masquerades it.
IpAddr::V4(destination) if self.routes.accepts_exit_traffic(network, destination) => {
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_local_destination(network, destination)
|| self.routes.accepts_exit_traffic(network, destination) =>
{
false
}
_ => {
@@ -1244,6 +1275,83 @@ mod tests {
);
}
#[tokio::test]
async fn dropping_a_network_after_partial_provisioning_removes_its_alias() {
#[derive(Debug, Default)]
struct PartialFactory {
devices: MemoryTunFactory,
addresses: std::sync::Mutex<Vec<Cidr>>,
}
impl TunFactory for PartialFactory {
fn name(&self) -> &str {
"partial"
}
fn on_host(&self) -> bool {
false
}
fn create<'a>(
&'a self,
request: TunRequest,
) -> crate::BoxFuture<'a, Result<Arc<dyn TunDevice>, OverlayError>> {
self.devices.create(request)
}
fn reconfigure<'a>(
&'a self,
request: TunRequest,
) -> crate::BoxFuture<'a, Result<(), OverlayError>> {
Box::pin(async move {
let mut host = self.addresses.lock().unwrap();
*host = request.addresses;
if !host.is_empty() {
return Err(OverlayError::Unavailable("subnet route failed".into()));
}
Ok(())
})
}
}
let routes = Arc::new(RoutingTable::new());
let network = network("partial");
routes
.set_network(
network,
NetworkRoutes {
local: Some(addr(1)),
range: Some("10.13.37.0/24".parse().unwrap()),
..NetworkRoutes::default()
},
)
.unwrap();
let factory = Arc::new(PartialFactory::default());
let interface = Interface::start(
factory.clone(),
"tsunpartial",
1280,
routes.clone(),
Arc::new(Recorder::default()),
)
.await
.unwrap();
assert!(interface.address_error().is_none());
assert!(interface.sync_addresses().await.is_err());
assert!(
interface
.address_error()
.unwrap()
.contains("subnet route failed")
);
assert_eq!(factory.addresses.lock().unwrap().len(), 1);
routes.remove_network(network);
interface.sync_addresses().await.unwrap();
assert!(interface.address_error().is_none());
assert!(factory.addresses.lock().unwrap().is_empty());
interface.remove().await;
}
#[tokio::test]
async fn the_wanted_addresses_follow_the_table() {
let (interface, _device, routes, _carrier, id) = interface(false).await;
@@ -1477,6 +1585,47 @@ mod tests {
assert_eq!(interface.counters().received, 1);
}
#[tokio::test]
async fn an_exit_reply_must_terminate_locally_even_while_this_agent_offers_forwarding() {
use super::super::broadcast::BroadcastPolicy;
let (interface, device, routes, _, id) = interface(false).await;
routes.set_exit(
id,
ExitPolicy {
offer: true,
via: Some(peer(2)),
},
);
routes.set_broadcast(
id,
BroadcastPolicy {
enabled: true,
peers: [peer(2)].into_iter().collect(),
},
);
let udp = [0, 1, 0, 2, 0, 8, 0, 0];
for destination in [Ipv4Addr::new(1, 1, 1, 1), Ipv4Addr::BROADCAST] {
assert_eq!(
interface
.deliver(id, peer(2), ipv4(INTERNET, destination, &udp))
.await,
Err(Rejected::WrongDestination)
);
}
assert_eq!(interface.counters().received, 0);
// The same peer can still return internet traffic to us, and can
// originate its own ordinary packets under the network's offer.
for packet in [ipv4(INTERNET, addr(1), &udp), ipv4(addr(2), INTERNET, &udp)] {
interface
.deliver(id, peer(2), packet.clone())
.await
.unwrap();
assert_eq!(device.pop_to_os().await.unwrap(), packet);
}
}
#[tokio::test]
async fn an_exit_node_hands_a_members_internet_packet_to_the_host_only_while_offering() {
let (interface, device, routes, _carrier, id) = interface(false).await;
@@ -1577,6 +1726,19 @@ mod tests {
vec![Ipv4Addr::new(5, 6, 7, 8)]
);
let second = network("second underlay");
let second_path = Ipv4Addr::new(203, 0, 113, 10);
interface.set_underlay(second, [second_path], []).await;
assert_eq!(
rules.exit().installed().unwrap().bypass,
[Ipv4Addr::new(5, 6, 7, 8), second_path]
);
interface.set_underlay(second, [], []).await;
assert_eq!(
rules.exit().installed().unwrap().bypass,
[Ipv4Addr::new(5, 6, 7, 8)]
);
// Not using an exit node: nothing to keep direct.
routes.set_exit(id, Default::default());
interface.sync_exit_rules().await;
+1
View File
@@ -46,6 +46,7 @@ pub mod interface;
pub mod packet;
pub mod provision;
pub mod router;
pub mod source;
pub mod tun;
pub use config::{Cidr, DEFAULT_INTERFACE_PREFIX, MAX_INTERFACE_NAME_LEN, interface_name};
@@ -6,6 +6,8 @@
use std::net::{Ipv4Addr, Ipv6Addr};
pub use crate::vip::packet::{Reassembly as Ipv4Reassembly, fragments as fragment_ipv4};
/// The addresses of an IP packet, as far as routing cares.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IpHeader {
@@ -76,7 +76,9 @@ enum Command {
DelBroadcastRoute(String, Reply<()>),
/// Send the host's default traffic through this interface, except what
/// this user id sends.
SetExitClient(String, u32, Reply<()>),
SetExitClient(String, u32, Option<Ipv4Addr>, Reply<()>),
/// Replace only the default route on an already protected interface.
UpdateExitSource(String, Option<Ipv4Addr>, Reply<()>),
/// Take those routing rules away again.
ClearExitClient(Reply<()>),
/// Stop the thread.
@@ -213,10 +215,25 @@ impl RouteHandle {
/// Sends the host's default traffic through `interface`, except what the
/// user id `uid` sends. Replaces what an earlier call set up.
pub(crate) fn set_exit_client(&self, interface: &str, uid: u32) -> Result<(), OverlayError> {
pub(crate) fn set_exit_client(
&self,
interface: &str,
uid: u32,
source: Option<Ipv4Addr>,
) -> Result<(), OverlayError> {
let interface = interface.to_string();
call_thread(&self.commands, |reply| {
Command::SetExitClient(interface, uid, reply)
Command::SetExitClient(interface, uid, source, reply)
})
}
pub(crate) fn update_exit_source(
&self,
interface: &str,
source: Option<Ipv4Addr>,
) -> Result<(), OverlayError> {
call_thread(&self.commands, |reply| {
Command::UpdateExitSource(interface.to_string(), source, reply)
})
}
@@ -346,7 +363,8 @@ fn netlink_thread(requests: mpsc::Receiver<Command>) {
| Command::Configure(_, reply)
| Command::SetBroadcastRoute(_, _, reply)
| Command::DelBroadcastRoute(_, reply)
| Command::SetExitClient(_, _, reply) => {
| Command::SetExitClient(_, _, _, reply)
| Command::UpdateExitSource(_, _, reply) => {
let _ = reply.send(Err(OverlayError::Unavailable(message)));
}
Command::ClearExitClient(reply) => {
@@ -398,9 +416,19 @@ fn netlink_thread(requests: mpsc::Receiver<Command>) {
});
let _ = reply.send(result);
}
Command::SetExitClient(name, uid, reply) => {
Command::SetExitClient(name, uid, source, reply) => {
let result = NetAdmin::acquire().and_then(|guard| {
let result = runtime.block_on(set_exit_client(&name, uid));
let result = runtime.block_on(set_exit_client(&name, uid, source));
drop(guard);
result
});
let _ = reply.send(result);
}
Command::UpdateExitSource(name, source, reply) => {
let result = NetAdmin::acquire().and_then(|guard| {
let result = runtime.block_on(with_netlink(|handle| async move {
replace_exit_default(&handle, &name, source).await
}));
drop(guard);
result
});
@@ -704,13 +732,19 @@ fn is_exit_rule(rule: &RuleMessage) -> bool {
}
}
fn exit_default_route(index: Option<u32>) -> rtnetlink::packet_route::route::RouteMessage {
fn exit_default_route(
index: Option<u32>,
source: Option<Ipv4Addr>,
) -> rtnetlink::packet_route::route::RouteMessage {
let mut builder = RouteMessageBuilder::<Ipv4Addr>::new()
.destination_prefix(Ipv4Addr::UNSPECIFIED, 0)
.table_id(EXIT_TABLE);
if let Some(index) = index {
builder = builder.output_interface(index).scope(RouteScope::Link);
}
if let Some(source) = source {
builder = builder.pref_source(source);
}
builder.build()
}
@@ -772,7 +806,12 @@ async fn remove_exit_rules(
async fn remove_exit_client(handle: &rtnetlink::Handle) -> Result<(), OverlayError> {
remove_exit_rules(handle, IpVersion::V4).await?;
match handle.route().del(exit_default_route(None)).execute().await {
match handle
.route()
.del(exit_default_route(None, None))
.execute()
.await
{
Ok(()) => {}
// "No such process": no such route, which is the goal.
Err(err) if err.to_string().contains("No such") => {}
@@ -797,10 +836,32 @@ async fn remove_exit_client(handle: &rtnetlink::Handle) -> Result<(), OverlayErr
}
}
/// Replace the default route atomically when the selected overlay address changes.
async fn replace_exit_default(
handle: &rtnetlink::Handle,
name: &str,
source: Option<Ipv4Addr>,
) -> Result<(), OverlayError> {
let index = link_index(handle, name).await.ok_or_else(|| {
OverlayError::Unavailable(format!(
"interface `{name}` disappeared before the exit node route could be added"
))
})?;
handle
.route()
.add(exit_default_route(Some(index), source))
.replace()
.execute()
.await
.map_err(|err| {
OverlayError::Unavailable(format!("cannot set the exit node default route: {err}"))
})
}
/// Sets up the using side of an exit node.
///
/// ```text
/// ip route replace default dev <if> table 0x7473
/// ip route replace default dev <if> src <selected overlay address> table 0x7473
/// ip rule add priority 5205 fwmark 0x40000000/0x40000000 lookup main
/// ip rule add priority 5206 uidrange <uid>-<uid> lookup main
/// ip rule add priority 5290 lookup main suppress_prefixlength 0
@@ -813,24 +874,17 @@ async fn remove_exit_client(handle: &rtnetlink::Handle) -> Result<(), OverlayErr
/// What an earlier call left is removed first, so repeating it is safe, and
/// the rules go in last, so a failure part way never leaves a rule that
/// sends traffic to a table with no route in it.
async fn set_exit_client(name: &str, uid: u32) -> Result<(), OverlayError> {
async fn set_exit_client(
name: &str,
uid: u32,
source: Option<Ipv4Addr>,
) -> Result<(), OverlayError> {
with_netlink(|handle| async move {
let index = link_index(&handle, name).await.ok_or_else(|| {
OverlayError::Unavailable(format!(
"interface `{name}` disappeared before the exit node routes could be added"
))
})?;
remove_exit_client(&handle).await?;
let fail = |what: &str, err: rtnetlink::Error| {
OverlayError::Unavailable(format!("cannot add the exit node {what}: {err}"))
};
handle
.route()
.add(exit_default_route(Some(index)))
.replace()
.execute()
.await
.map_err(|err| fail("default route", err))?;
replace_exit_default(&handle, name, source).await?;
add_mark_bypass(&handle, false).await?;
@@ -1190,13 +1244,17 @@ mod tests {
#[test]
fn the_default_route_of_the_exit_table_names_the_table_and_the_interface() {
let route = exit_default_route(Some(7));
let source = Ipv4Addr::new(10, 99, 0, 1);
let route = exit_default_route(Some(7), Some(source));
assert_eq!(route.header.destination_prefix_length, 0);
let debug = format!("{route:?}");
assert!(debug.contains(&format!("Table({EXIT_TABLE})")), "{debug}");
assert!(debug.contains("Oif(7)"), "{debug}");
assert!(route.attributes.contains(
&rtnetlink::packet_route::route::RouteAttribute::PrefSource(source.into())
));
// Deleting names no interface, so it matches whatever it was added on.
assert!(!format!("{:?}", exit_default_route(None)).contains("Oif"));
assert!(!format!("{:?}", exit_default_route(None, None)).contains("Oif"));
}
#[test]
+221 -106
View File
@@ -39,7 +39,8 @@
//! `getifaddrs`. An interface is matched by its real `utunN` name, which only
//! matters on reconfiguration: the first create always makes a fresh device.
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use netdev::ipnet::IpNet;
use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use crate::BoxFuture;
@@ -115,7 +116,7 @@ impl InterfaceProvisioner for UtunProvisioner {
if self.is_ours(&plan.name) {
let current = observe(&plan.name).await;
let changes = plan_changes(&current, plan, true)?;
configure(&plan.name, &changes).await?;
configure(&plan.name, &changes, &plan.addresses).await?;
return Ok(Provisioned {
changes,
device: None,
@@ -136,7 +137,7 @@ impl InterfaceProvisioner for UtunProvisioner {
// A failure here leaves an interface that exists but cannot carry
// traffic. Drop the device so the utun closes, and report, rather
// than leave a trap behind.
if let Err(err) = configure(&real, &changes).await {
if let Err(err) = configure(&real, &changes, &plan.addresses).await {
drop(device);
return Err(err);
}
@@ -225,28 +226,25 @@ async fn observe(name: &str) -> InterfaceState {
}
/// Applies MTU, link state, addresses and the on-link routes they imply.
async fn configure(name: &str, changes: &super::Changes) -> Result<(), OverlayError> {
async fn configure(
name: &str,
changes: &super::Changes,
wanted: &[Cidr],
) -> Result<(), OverlayError> {
if let Some(mtu) = changes.set_mtu {
set_mtu(name, mtu).await?;
}
for cidr in &changes.remove {
// Best effort: an address that is already gone is the outcome wanted.
if let Err(err) = address_del(name, *cidr).await {
tracing::debug!(interface = %name, %cidr, %err, "could not remove address");
}
if let Err(err) = route_del(name, *cidr).await {
tracing::debug!(interface = %name, %cidr, %err, "could not remove route");
let network = subnet(*cidr)?;
if !is_host_route(*cidr)
&& matches!(subnet_route(network).await?, SubnetRoute::Present { interface, .. } if interface == name)
{
run("/sbin/route", route_args("delete", name, network)).await?;
}
address_del(name, *cidr).await?;
}
for cidr in &changes.add {
address_add(name, *cidr).await?;
// The subnet route makes the whole overlay range reach the interface;
// a point-to-point utun does not install one from the address alone. A
// host address (/32 or /128) needs none. Best effort: a route that is
// already there is the outcome wanted.
if let Err(err) = route_add(name, *cidr).await {
tracing::debug!(interface = %name, %cidr, %err, "could not add route");
}
}
if changes.bring_up {
// Best effort: a utun with a descriptor open is up already, and a
@@ -255,31 +253,22 @@ async fn configure(name: &str, changes: &super::Changes) -> Result<(), OverlayEr
tracing::debug!(interface = %name, %err, "could not enable the interface");
}
}
Ok(())
}
/// The network address of a CIDR, with the host bits cleared.
fn network_of(cidr: Cidr) -> IpAddr {
match cidr.addr {
IpAddr::V4(addr) => {
let bits = u32::from(addr);
let mask = if cidr.prefix_len == 0 {
0
} else {
u32::MAX << (32 - u32::from(cidr.prefix_len))
};
IpAddr::V4(Ipv4Addr::from(bits & mask))
}
IpAddr::V6(addr) => {
let bits = u128::from(addr);
let mask = if cidr.prefix_len == 0 {
0
} else {
u128::MAX << (128 - u32::from(cidr.prefix_len))
};
IpAddr::V6(Ipv6Addr::from(bits & mask))
// An alias may already be present after a partial reconcile, or its old
// subnet route may still select the first alias on this utun.
let mut result = Ok(());
for &cidr in wanted {
if !is_host_route(cidr) {
// Finish the other networks even when one subnet conflicts.
let update = ensure_subnet_route(name, subnet(cidr)?).await;
result = result.and(update);
}
}
result
}
fn subnet(cidr: Cidr) -> Result<IpNet, OverlayError> {
IpNet::new(cidr.addr, cidr.prefix_len)
.map_err(|err| OverlayError::Unavailable(format!("invalid overlay prefix {cidr}: {err}")))
}
/// Whether a CIDR is a single host address, which needs no subnet route.
@@ -326,40 +315,26 @@ fn address_del_args(name: &str, cidr: Cidr) -> Vec<String> {
]
}
/// The `route` arguments that point a CIDR's subnet at the interface.
fn route_add_args(name: &str, cidr: Cidr) -> Vec<String> {
let family = match cidr.addr {
fn route_args(command: &str, name: &str, subnet: IpNet) -> Vec<String> {
let family = match subnet.addr() {
IpAddr::V4(_) => "-inet",
IpAddr::V6(_) => "-inet6",
};
vec![
"-q".into(),
let mut args = vec![
if command == "get" { "-v" } else { "-q" }.into(),
"-n".into(),
"add".into(),
command.into(),
family.into(),
"-net".into(),
format!("{}/{}", network_of(cidr), cidr.prefix_len),
"-interface".into(),
name.into(),
]
}
/// The `route` arguments that remove that subnet route.
fn route_del_args(name: &str, cidr: Cidr) -> Vec<String> {
let family = match cidr.addr {
IpAddr::V4(_) => "-inet",
IpAddr::V6(_) => "-inet6",
};
vec![
"-q".into(),
"-n".into(),
"delete".into(),
family.into(),
"-net".into(),
format!("{}/{}", network_of(cidr), cidr.prefix_len),
"-interface".into(),
name.into(),
]
subnet.trunc().to_string(),
];
if command != "get" {
args.extend(["-interface".into(), name.into()]);
}
if matches!(command, "add" | "change") {
args.extend(["-ifa".into(), subnet.addr().to_string()]);
}
args
}
async fn address_add(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
@@ -370,18 +345,92 @@ async fn address_del(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
ifconfig(address_del_args(name, cidr)).await
}
async fn route_add(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
if is_host_route(cidr) {
return Ok(());
}
route(route_add_args(name, cidr)).await
#[derive(Debug, Eq, PartialEq)]
enum SubnetRoute {
Absent,
Present { interface: String, source: IpAddr },
}
async fn route_del(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
if is_host_route(cidr) {
return Ok(());
impl SubnetRoute {
fn action(&self, name: &str, subnet: IpNet) -> Result<Option<&'static str>, OverlayError> {
match self {
Self::Absent => Ok(Some("add")),
Self::Present { interface, .. } if interface != name => {
Err(OverlayError::Unavailable(format!(
"route for {}/{} belongs to {interface}; cannot install it on {name}",
subnet.network(),
subnet.prefix_len()
)))
}
Self::Present { source, .. } if *source == subnet.addr() => Ok(None),
Self::Present { .. } => Ok(Some("change")),
}
}
route(route_del_args(name, cidr)).await
}
// A verbose RTM_GET prints two sockaddr lists (request and reply). In the
// kernel's reply IFA follows the variable-width link address of the interface.
fn parse_subnet_route(output: &str, subnet: IpNet) -> Result<SubnetRoute, OverlayError> {
let invalid =
|| OverlayError::Unavailable(format!("could not read the kernel route for {subnet}"));
let field = |key: &str| {
output
.lines()
.find_map(|line| line.trim().strip_prefix(key).map(str::trim))
};
let destination = field("destination:").ok_or_else(invalid)?;
let matches = |text: &str, expected: IpAddr| {
text.parse::<IpAddr>() == Ok(expected) || (text == "default" && expected.is_unspecified())
};
if !matches(destination, subnet.network())
|| !field("mask:").is_some_and(|mask| matches(mask, subnet.netmask()))
{
return Ok(SubnetRoute::Absent);
}
let interface = field("interface:").ok_or_else(invalid)?;
let (_, reply) = output.rsplit_once("sockaddrs:").ok_or_else(invalid)?;
let (fields, addresses) = reply.trim().split_once('\n').ok_or_else(invalid)?;
let after = fields
.trim()
.trim_matches(['<', '>'])
.split(',')
.rev()
.position(|field| field == "IFA")
.ok_or_else(invalid)?;
let source = addresses
.split_whitespace()
.rev()
.nth(after)
.and_then(|ip| ip.parse().ok())
.ok_or_else(invalid)?;
Ok(SubnetRoute::Present {
interface: interface.into(),
source,
})
}
async fn subnet_route(subnet: IpNet) -> Result<SubnetRoute, OverlayError> {
match run("/sbin/route", route_args("get", "", subnet)).await {
Ok(output) => parse_subnet_route(&output, subnet),
Err(OverlayError::Unavailable(message)) if message.ends_with("not in table") => {
Ok(SubnetRoute::Absent)
}
Err(err) => Err(err),
}
}
async fn ensure_subnet_route(name: &str, subnet: IpNet) -> Result<(), OverlayError> {
if let Some(command) = subnet_route(subnet).await?.action(name, subnet)? {
run("/sbin/route", route_args(command, name, subnet)).await?;
let observed = subnet_route(subnet).await?;
if observed.action(name, subnet)?.is_some() {
return Err(OverlayError::Unavailable(format!(
"route for {subnet} on {name} did not select source {} (observed {observed:?})",
subnet.addr()
)));
}
}
Ok(())
}
async fn set_mtu(name: &str, mtu: u32) -> Result<(), OverlayError> {
@@ -394,27 +443,26 @@ async fn set_up(name: &str) -> Result<(), OverlayError> {
/// Runs `/sbin/ifconfig`, turning a non-zero exit into an error with its text.
async fn ifconfig(args: Vec<String>) -> Result<(), OverlayError> {
run("/sbin/ifconfig", args).await
}
/// Runs `/sbin/route`, turning a non-zero exit into an error with its text.
async fn route(args: Vec<String>) -> Result<(), OverlayError> {
run("/sbin/route", args).await
run("/sbin/ifconfig", args).await.map(|_| ())
}
/// Runs a system tool by absolute path, so nothing on `PATH` can stand in for
/// it, and turns a non-zero exit into an error carrying what it said.
async fn run(program: &'static str, args: Vec<String>) -> Result<(), OverlayError> {
async fn run(program: &'static str, args: Vec<String>) -> Result<String, OverlayError> {
let display = format!("{program} {}", args.join(" "));
let output = tokio::task::spawn_blocking(move || {
std::process::Command::new(program).args(&args).output()
std::process::Command::new(program)
.env("LC_ALL", "C")
.args(&args)
.output()
})
.await
.map_err(|err| OverlayError::Other(format!("could not run {display}: {err}")))?
.map_err(|err| OverlayError::Unavailable(format!("could not run {display}: {err}")))?;
if output.status.success() {
return Ok(());
// Darwin route can exit successfully after a routing-socket write failed.
if output.status.success() && (program != "/sbin/route" || output.stderr.is_empty()) {
return Ok(String::from_utf8_lossy(&output.stdout).into_owned());
}
let message = {
let stderr = String::from_utf8_lossy(&output.stderr);
@@ -439,6 +487,7 @@ mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use std::net::{Ipv4Addr, Ipv6Addr};
fn v4(last: u8, prefix: u8) -> Cidr {
Cidr::new(IpAddr::V4(Ipv4Addr::new(10, 13, 37, last)), prefix).unwrap()
@@ -476,8 +525,8 @@ mod tests {
}
#[test]
fn a_subnet_route_points_the_masked_network_at_the_interface() {
let args = route_add_args("utun5", v4(69, 24));
fn a_subnet_route_names_its_own_overlay_source() {
let args = route_args("add", "utun5", subnet(v4(69, 24)).unwrap());
assert_eq!(
args,
vec![
@@ -488,11 +537,93 @@ mod tests {
"-net",
"10.13.37.0/24",
"-interface",
"utun5"
"utun5",
"-ifa",
"10.13.37.69"
]
);
}
#[test]
fn a_wrong_source_is_repaired_only_on_the_owned_interface() {
let cidr = subnet(v4(69, 24)).unwrap();
let observed = "destination: 10.13.37.0\n mask: 255.255.255.0\n interface: utun5\n\
sockaddrs: <DST,GATEWAY,NETMASK,IFP,IFA>\n 10.13.37.0 index: 20 255.255.255.0 index: 20 utun5 10.99.0.2\n";
let route = parse_subnet_route(observed, cidr).unwrap();
assert_eq!(route.action("utun5", cidr).unwrap(), Some("change"));
assert!(route.action("utun9", cidr).is_err());
let corrected = observed.replace("10.99.0.2", "10.13.37.69");
assert_eq!(
parse_subnet_route(&corrected, cidr)
.unwrap()
.action("utun5", cidr)
.unwrap(),
None
);
assert!(parse_subnet_route(&observed.replace(",IFA>", ">"), cidr).is_err());
assert!(parse_subnet_route("", cidr).is_err());
let broader = observed.replace("255.255.255.0", "255.255.0.0");
assert_eq!(
parse_subnet_route(&broader, cidr).unwrap(),
SubnetRoute::Absent
);
}
#[tokio::test]
#[ignore = "requires root and creates a temporary macOS utun with two subnet routes"]
async fn unbound_sockets_choose_each_networks_source_on_one_real_utun() {
let provisioner = UtunProvisioner::new().unwrap();
let first = Cidr::new("198.18.251.1".parse().unwrap(), 30).unwrap();
let second = Cidr::new("198.19.251.1".parse().unwrap(), 30).unwrap();
let created = provisioner
.reconcile(&InterfacePlan::new("tsuntest", 1280, vec![first]))
.await
.unwrap();
let device = created.device.unwrap();
let plan = InterfacePlan::new(device.name(), 1280, vec![first, second]);
let before = netwatch::netmon::State::new().await;
provisioner.reconcile(&plan).await.unwrap();
let after = netwatch::netmon::State::new().await;
assert!(crate::net::only_owned_interface_changed(
&before,
&after,
device.name()
));
for (peer, expected) in [("198.18.251.2", first), ("198.19.251.2", second)] {
let socket = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).unwrap();
socket
.connect((peer.parse::<Ipv4Addr>().unwrap(), 9))
.unwrap();
assert_eq!(socket.local_addr().unwrap().ip(), expected.addr);
}
// Simulate a route left by an earlier release, with both aliases still present.
let second_subnet = subnet(second).unwrap();
let mut stale = route_args("change", device.name(), second_subnet);
*stale.last_mut().unwrap() = first.addr.to_string();
run("/sbin/route", stale).await.unwrap();
assert_eq!(
subnet_route(second_subnet)
.await
.unwrap()
.action(device.name(), second_subnet)
.unwrap(),
Some("change")
);
provisioner.reconcile(&plan).await.unwrap();
let socket = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).unwrap();
socket.connect(("198.19.251.2", 9)).unwrap();
assert_eq!(socket.local_addr().unwrap().ip(), second.addr);
provisioner
.reconcile(&InterfacePlan::new(device.name(), 1280, vec![first]))
.await
.unwrap();
assert_eq!(
subnet_route(second_subnet).await.unwrap(),
SubnetRoute::Absent
);
provisioner.remove(device.name()).await.unwrap();
}
#[test]
fn a_host_address_installs_no_subnet_route() {
assert!(is_host_route(v4(69, 32)));
@@ -501,22 +632,6 @@ mod tests {
assert!(!is_host_route(v6(1, 64)));
}
#[test]
fn the_network_address_clears_the_host_bits() {
assert_eq!(
network_of(v4(69, 24)),
IpAddr::V4(Ipv4Addr::new(10, 13, 37, 0))
);
assert_eq!(
network_of(Cidr::new(IpAddr::V4(Ipv4Addr::new(10, 13, 37, 69)), 16).unwrap()),
IpAddr::V4(Ipv4Addr::new(10, 13, 0, 0))
);
assert_eq!(
network_of(v6(0x1234, 64)),
IpAddr::V6(Ipv6Addr::new(0xfd00, 0, 0, 0, 0, 0, 0, 0))
);
}
#[test]
fn link_local_addresses_are_not_ours_to_manage() {
assert!(is_link_local(IpAddr::V6(Ipv6Addr::new(
@@ -131,10 +131,14 @@ impl InterfaceProvisioner for WintunProvisioner {
};
for cidr in flush.iter().chain(changes.remove.iter()) {
// Best effort: an address that is already gone is the outcome
// wanted, and refusing to start over one is not worth it.
if let Err(err) = address_del(&plan.name, *cidr).await {
tracing::debug!(interface = %plan.name, %cidr, %err, "could not remove address");
if let Err(err) = address_del(&plan.name, *cidr).await
&& observe(&plan.name)
.await
.addresses
.iter()
.any(|a| a.addr == cidr.addr)
{
return Err(err);
}
}
@@ -262,11 +266,12 @@ async fn configure(plan: &InterfacePlan, changes: &super::Changes) -> Result<(),
set_mtu(&plan.name, mtu).await?;
}
for cidr in &changes.add {
if let Err(err) = address_add(&plan.name, *cidr).await {
let err_str = err.to_string();
if !err_str.contains("already exists") && !err_str.contains("0x80071392") {
return Err(err);
}
// An already-installed alias is idempotent, including on localized
// Windows. A duplicate on a different adapter cannot satisfy the plan.
if let Err(err) = address_add(&plan.name, *cidr).await
&& !observe(&plan.name).await.addresses.contains(cidr)
{
return Err(err);
}
}
if changes.bring_up {
@@ -300,6 +305,7 @@ fn address_add_args(name: &str, cidr: Cidr) -> Vec<String> {
format!("address={addr}"),
format!("mask={}", ipv4_mask(cidr.prefix_len)),
"store=active".into(),
"skipassource=false".into(),
],
IpAddr::V6(addr) => vec![
"interface".into(),
@@ -466,6 +472,70 @@ mod tests {
assert!(args.contains(&"name=tsun0".to_string()));
assert!(args.contains(&"address=10.13.37.69".to_string()));
assert!(args.contains(&"mask=255.255.255.0".to_string()));
assert!(args.contains(&"skipassource=false".to_string()));
}
#[tokio::test]
#[ignore = "requires an elevated Windows host with Wintun"]
async fn two_windows_subnets_choose_their_own_source_and_survive_removal() {
let addresses = [
(
Ipv4Addr::new(198, 18, 251, 1),
Ipv4Addr::new(198, 18, 251, 2),
),
(
Ipv4Addr::new(198, 19, 251, 1),
Ipv4Addr::new(198, 19, 251, 2),
),
];
for iface in netdev::get_interfaces() {
for prefix in iface.ipv4 {
assert!(
addresses.iter().all(|(ip, destination)| {
!prefix.contains(ip) && !prefix.contains(destination)
}),
"test subnets already in use"
);
}
}
let adapter = format!("tsun-test-{:08x}", rand::random::<u32>());
let provisioner = WintunProvisioner::new().unwrap();
let cidrs: Vec<_> = addresses
.iter()
.map(|(ip, _)| Cidr::new((*ip).into(), 30).unwrap())
.collect();
let mut device = None;
for wanted in [&cidrs[..1], &cidrs[..], &cidrs[1..], &cidrs[..]] {
let plan = InterfacePlan::new(&adapter, 1280, wanted.to_vec());
let result = provisioner.reconcile(&plan).await.unwrap();
if let Some(created) = result.device {
assert!(device.replace(created).is_none());
}
// Allow the Windows address to finish duplicate address detection.
tokio::time::timeout(std::time::Duration::from_secs(10), async {
loop {
let ready = addresses
.iter()
.filter(|(ip, _)| wanted.iter().any(|c| c.addr == IpAddr::V4(*ip)))
.all(|(ip, destination)| {
std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))
.and_then(|socket| {
socket.connect((*destination, 9))?;
socket.local_addr()
})
.is_ok_and(|source| source.ip() == IpAddr::V4(*ip))
});
if ready {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
})
.await
.expect("Windows selected the wrong source");
assert_eq!(observe(&adapter).await.addresses, plan.addresses);
}
provisioner.remove(&adapter).await.unwrap();
}
#[test]
+114 -18
View File
@@ -40,6 +40,12 @@ pub struct Route {
pub peer: EndpointId,
}
/// An internet source is valid only for a reply to our address in the exit's network.
pub(super) enum PacketSource {
Member,
ExitReply { local: Option<Ipv4Addr> },
}
/// A network's exit-node settings, as far as packets are concerned.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ExitPolicy {
@@ -120,7 +126,29 @@ impl RoutingTable {
/// interface an address can belong to only one network, and guessing
/// which would send somebody's traffic to a stranger.
pub fn set_network(&self, network: NetworkId, routes: NetworkRoutes) -> Result<(), RouteError> {
self.replace_network(&mut self.write(), network, routes)
}
/// A fresh allocation snapshot cannot change the operator's exit settings.
pub(crate) fn update_allocations(
&self,
network: NetworkId,
mut routes: NetworkRoutes,
) -> Result<(), RouteError> {
let mut networks = self.write();
routes.exit = networks
.get(&network)
.map(|current| current.exit)
.unwrap_or_default();
self.replace_network(&mut networks, network, routes)
}
fn replace_network(
&self,
networks: &mut HashMap<NetworkId, NetworkRoutes>,
network: NetworkId,
routes: NetworkRoutes,
) -> Result<(), RouteError> {
if let Some(range) = routes.range {
for (other, existing) in networks.iter() {
if *other == network {
@@ -139,9 +167,12 @@ impl RoutingTable {
}
}
}
if routes.exit.via.is_some() {
clear_other_exits(networks, network);
}
networks.insert(network, routes);
self.broadcast
.store(Arc::new(BroadcastTable::build(&networks)));
.store(Arc::new(BroadcastTable::build(networks)));
Ok(())
}
@@ -172,8 +203,16 @@ impl RoutingTable {
/// A network that has no entry yet (its range is not agreed) takes them
/// from [`NetworkRoutes::exit`] when it is added.
pub fn set_exit(&self, network: NetworkId, policy: ExitPolicy) {
if let Some(routes) = self.write().get_mut(&network) {
routes.exit = policy;
self.update_exit(network, |current| *current = policy);
}
pub(crate) fn update_exit(&self, network: NetworkId, update: impl FnOnce(&mut ExitPolicy)) {
let mut networks = self.write();
if let Some(routes) = networks.get_mut(&network) {
update(&mut routes.exit);
if routes.exit.via.is_some() {
clear_other_exits(&mut networks, network);
}
}
}
@@ -241,20 +280,30 @@ impl RoutingTable {
/// internet carries the internet's addresses, so from *that* peer any
/// source outside the overlay ranges is accepted.
pub fn may_send_from(&self, network: NetworkId, peer: EndpointId, source: Ipv4Addr) -> bool {
self.packet_source(network, peer, source).is_some()
}
pub(super) fn packet_source(
&self,
network: NetworkId,
peer: EndpointId,
source: Ipv4Addr,
) -> Option<PacketSource> {
let networks = self.read();
let Some(routes) = networks.get(&network) else {
return false;
};
let routes = networks.get(&network)?;
if routes
.peers
.iter()
.any(|(address, holder)| *address == source && *holder == peer)
{
return true;
return Some(PacketSource::Member);
}
routes.exit.via == Some(peer)
(exit_via(&networks) == Some((network, peer))
&& is_internet_destination(source)
&& !in_any_range(&networks, source)
&& !in_any_range(&networks, source))
.then_some(PacketSource::ExitReply {
local: routes.local,
})
}
/// Whether this agent, as an exit node of `network`, takes a member's
@@ -275,8 +324,7 @@ impl RoutingTable {
/// The network and member this device sends its internet traffic through.
///
/// One default route, so one answer; if several networks claim one (they
/// should not) the lowest network id decides, so two runs agree.
/// Choosing another exit replaces the previous one under the table's write lock.
pub fn exit_via(&self) -> Option<(NetworkId, EndpointId)> {
exit_via(&self.read())
}
@@ -423,12 +471,19 @@ fn in_any_range(networks: &HashMap<NetworkId, NetworkRoutes>, address: Ipv4Addr)
.any(|routes| routes.range.is_some_and(|range| range.contains(address)))
}
/// The exit node in use, if any, from the lowest network that names one.
fn clear_other_exits(networks: &mut HashMap<NetworkId, NetworkRoutes>, selected: NetworkId) {
for (id, routes) in networks {
if *id != selected {
routes.exit.via = None;
}
}
}
/// Only the selected network can have an exit peer.
fn exit_via(networks: &HashMap<NetworkId, NetworkRoutes>) -> Option<(NetworkId, EndpointId)> {
networks
.iter()
.filter_map(|(network, routes)| Some((*network, routes.exit.via?)))
.min_by_key(|(network, _)| *network)
.find_map(|(network, routes)| Some((*network, routes.exit.via?)))
}
/// Whether two ranges share any address.
@@ -745,6 +800,46 @@ mod tests {
const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34);
#[test]
fn refreshing_either_networks_addresses_preserves_the_last_exit_choice() {
let table = RoutingTable::new();
let (a, b) = (network("first"), network("second"));
let first = with_exit(true, Some(peer(2)));
let second = NetworkRoutes {
range: Some("10.99.0.0/24".parse().unwrap()),
local: Some(Ipv4Addr::new(10, 99, 0, 1)),
..Default::default()
};
table.set_network(a, first.clone()).unwrap();
table.set_network(b, second.clone()).unwrap();
table.set_exit(
b,
ExitPolicy {
offer: false,
via: Some(peer(3)),
},
);
table.update_allocations(a, first).unwrap();
table.update_allocations(b, second).unwrap();
assert_eq!(
table.exit_client(),
(true, Some(Ipv4Addr::new(10, 99, 0, 1)))
);
assert_eq!(table.exit_via(), Some((b, peer(3))));
assert_eq!(
table.exit_settings(a).unwrap().0,
ExitPolicy {
offer: true,
via: None
}
);
table.remove_network(a);
assert_eq!(table.exit_via(), Some((b, peer(3))));
table.remove_network(b);
assert_eq!(table.exit_via(), None);
}
#[test]
fn without_an_exit_node_the_internet_has_nowhere_to_go() {
let table = RoutingTable::new();
@@ -819,7 +914,7 @@ mod tests {
}
#[test]
fn two_exit_choices_resolve_to_the_lowest_network_id() {
fn competing_exit_choices_use_the_same_peer_for_requests_and_replies() {
let table = RoutingTable::new();
let (a, b) = (network("one"), network("two"));
table
@@ -838,9 +933,10 @@ mod tests {
},
)
.unwrap();
let (chosen, _) = table.exit_via().unwrap();
assert_eq!(chosen, a.min(b));
assert_eq!(table.route(INTERNET).unwrap().network, a.min(b));
assert_eq!(table.exit_via(), Some((b, peer(9))));
assert_eq!(table.route(INTERNET).unwrap().network, b);
assert!(table.may_send_from(b, peer(9), INTERNET));
assert!(!table.may_send_from(a, peer(2), INTERNET));
}
#[test]
+787
View File
@@ -0,0 +1,787 @@
//! Translate host-selected IPv4 aliases at the local packet interface.
use super::Cidr;
use super::packet::{Ipv4Reassembly, fragment_ipv4};
use bytes::Bytes;
use smoltcp::wire::{Ipv4Cidr, Ipv4Packet};
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr};
use std::time::{Duration, Instant};
mod icmp;
#[cfg(any(all(windows, feature = "tun-device"), test))]
pub(crate) mod windows;
// No mappings are persisted, and a new flow cannot evict a live socket.
const MAX_FLOWS: usize = 4096;
const MAX_FRAGMENTED: usize = 16;
const UDP_IDLE: Duration = Duration::from_secs(120);
const TCP_IDLE: Duration = Duration::from_secs(2 * 60 * 60);
const ECHO_IDLE: Duration = Duration::from_secs(30);
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct WireFlow {
local: Ipv4Addr,
remote: Ipv4Addr,
protocol: u8,
local_port: u16,
remote_port: u16,
}
impl WireFlow {
// ICMP errors quote as few as eight transport bytes; the caller validates
// the outer packet separately. Echo requests in opposite directions can
// have the same identifier without sharing a flow.
fn parse(packet: &[u8], outbound: bool) -> Option<Self> {
let h = usize::from(*packet.first()? & 15) * 4;
if packet[0] >> 4 != 4
|| h < 20
|| packet.len() < h + 8
|| u16::from_be_bytes([packet[6], packet[7]]) & 0x1fff != 0
{
return None;
}
let src = Ipv4Addr::from(<[u8; 4]>::try_from(&packet[12..16]).ok()?);
let dst = Ipv4Addr::from(<[u8; 4]>::try_from(&packet[16..20]).ok()?);
let (local, remote) = if outbound { (src, dst) } else { (dst, src) };
let protocol = packet[9];
let data = &packet[h..];
let (local_port, remote_port) = match protocol {
6 | 17 => {
let src = u16::from_be_bytes([data[0], data[1]]);
let dst = u16::from_be_bytes([data[2], data[3]]);
if outbound { (src, dst) } else { (dst, src) }
}
1 if matches!(data[0], 0 | 8) && data[1] == 0 => {
let id = u16::from_be_bytes([data[4], data[5]]);
(id, u16::from(outbound != (data[0] == 8)))
}
_ => return None,
};
Some(Self {
local,
remote,
protocol,
local_port,
remote_port,
})
}
}
#[derive(Clone, Copy)]
struct Binding {
host: Ipv4Addr,
// A response from an unbound UDP listener can leave Android with the
// primary address even though its request targeted a different alias.
remote_initiated: bool,
expires: Instant,
}
/// How the host chooses a source at the TUN boundary.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SourceMode {
/// Android can choose the primary VPN address even for another mesh.
Primary,
/// Windows chooses the matching subnet for mesh traffic, but may select
/// any local alias for a default route.
ExitOnly,
}
#[derive(Debug, PartialEq, Eq)]
struct Domains {
aliases: Vec<Ipv4Cidr>,
exit: Option<Ipv4Addr>,
mode: SourceMode,
}
impl Domains {
fn new(addresses: &[Cidr], exit: Option<Ipv4Addr>, mode: SourceMode) -> Self {
let aliases = addresses
.iter()
.filter_map(|cidr| match cidr.addr {
IpAddr::V4(addr) if cidr.prefix_len <= 32 => {
Some(Ipv4Cidr::new(addr, cidr.prefix_len))
}
_ => None,
})
.collect();
Self {
aliases,
exit,
mode,
}
}
fn primary(&self) -> Option<Ipv4Addr> {
match self.mode {
SourceMode::Primary => self.aliases.first().map(Ipv4Cidr::address),
SourceMode::ExitOnly => None,
}
}
fn has(&self, addr: Ipv4Addr) -> bool {
self.aliases.iter().any(|alias| alias.address() == addr)
}
fn owner(&self, remote: Ipv4Addr) -> Option<Ipv4Addr> {
if remote.is_broadcast()
|| remote.is_multicast()
|| remote.is_unspecified()
|| remote.is_loopback()
|| self.has(remote)
{
return None;
}
if let Some(prefix) = self.aliases.iter().find(|p| p.contains_addr(&remote)) {
return (self.mode == SourceMode::Primary && prefix.broadcast() != Some(remote))
.then(|| prefix.address());
}
self.exit
}
}
/// Bounded flow bindings restore replies to the socket that opened each flow.
pub struct SourceFlows {
domains: Domains,
mtu: u32,
flows: HashMap<Ipv4Addr, HashMap<WireFlow, Binding>>,
primary_has_translations: bool,
last_sweep: Instant,
outgoing_parts: HashMap<Ipv4Addr, Ipv4Reassembly>,
incoming_parts: HashMap<Ipv4Addr, Ipv4Reassembly>,
}
impl SourceFlows {
/// Addresses are in the same order as on the device, primary first where applicable.
pub fn new(addresses: &[Cidr], exit: Option<Ipv4Addr>, mtu: u32, mode: SourceMode) -> Self {
Self {
domains: Domains::new(addresses, exit, mode),
mtu,
flows: HashMap::new(),
primary_has_translations: false,
last_sweep: Instant::now(),
outgoing_parts: HashMap::new(),
incoming_parts: HashMap::new(),
}
}
/// Keep live bindings whose host and wire addresses still belong to the same domains.
pub fn reconfigure(&mut self, addresses: &[Cidr], exit: Option<Ipv4Addr>, mtu: u32) {
self.domains = Domains::new(addresses, exit, self.domains.mode);
self.mtu = mtu;
self.flows.retain(|_, table| {
table.retain(|wire, entry| {
self.domains.has(entry.host) && self.domains.owner(wire.remote) == Some(wire.local)
});
!table.is_empty()
});
self.refresh_primary();
// Outstanding fragments belong to the previous VPN attachment.
self.outgoing_parts.clear();
self.incoming_parts.clear();
}
fn refresh_primary(&mut self) {
if let Some(primary) = self.domains.primary() {
self.primary_has_translations = self
.flows
.get(&primary)
.is_some_and(|table| table.values().any(|entry| entry.host != primary));
if !self.primary_has_translations {
self.flows.remove(&primary);
}
}
}
/// Packets read from the host.
pub fn outbound(&mut self, packet: Bytes) -> Vec<Bytes> {
self.process(packet, true)
}
/// Packets admitted by the mesh and destined for the host.
pub fn inbound(&mut self, packet: Bytes) -> Vec<Bytes> {
self.process(packet, false)
}
fn process(&mut self, packet: Bytes, outbound: bool) -> Vec<Bytes> {
if self.domains.aliases.len() < 2 || packet.first().is_none_or(|byte| byte >> 4 != 4) {
return vec![packet];
}
let Ok(ip) = Ipv4Packet::new_checked(&packet[..]) else {
return vec![];
};
let h = usize::from(ip.header_len());
if h < 20 || usize::from(ip.total_len()) != packet.len() {
return vec![];
}
let (local, remote) = if outbound {
(ip.src_addr(), ip.dst_addr())
} else {
(ip.dst_addr(), ip.src_addr())
};
// ICMP errors can come from a router other than the original peer.
let is_icmp = packet[9] == 1;
let owner = self.domains.owner(remote);
let fragmented = ip.more_frags() || ip.frag_offset() != 0;
if self.domains.mode == SourceMode::ExitOnly {
// A mesh router can report PMTU for an internet flow whose source
// we translated. All other native mesh and forwarded packets pass
// directly, including fragments and packets headed to the gateway.
let exit_error = !outbound
&& Some(local) == self.domains.exit
&& is_icmp
&& (fragmented || matches!(packet.get(h), Some(3 | 11 | 12)));
if !self.domains.has(local) || (owner.is_none() && !exit_error) {
return vec![packet];
}
}
if !ip.verify_checksum() {
return vec![];
}
let primary = self.domains.primary();
// The kernel already uses the primary address for its own subnet. A
// primary change can leave earlier translated sockets draining there.
if Some(local) == primary
&& (!outbound || owner == primary)
&& !self.primary_has_translations
{
return vec![packet];
}
if owner.is_none() && !(is_icmp && self.domains.has(local)) {
return vec![packet];
}
if !self.domains.has(local) {
// Never translate addresses outside the local host's assignments.
return if outbound { vec![] } else { vec![packet] };
}
let now = Instant::now();
if now.duration_since(self.last_sweep) >= Duration::from_secs(5) {
self.flows.retain(|_, table| {
table.retain(|_, entry| now < entry.expires);
!table.is_empty()
});
self.refresh_primary();
self.last_sweep = now;
}
let packet = if fragmented {
let parts = if outbound {
&mut self.outgoing_parts
} else {
&mut self.incoming_parts
};
let key = if outbound {
owner.unwrap_or(local)
} else {
local
};
let Some(packet) = parts
.entry(key)
.or_default()
.accept(packet, MAX_FRAGMENTED, None)
else {
return vec![];
};
packet
} else {
packet
};
let h = usize::from(packet[0] & 15) * 4;
let output = if is_icmp
&& packet
.get(h)
.is_some_and(|kind| matches!(kind, 3 | 11 | 12))
{
icmp::rewrite_error(packet, h, !outbound, |quote, quote_outbound| {
let binding = WireFlow::parse(quote, quote_outbound)
.and_then(|flow| self.domains.owner(flow.remote).map(|alias| (flow, alias)));
let Some((flow, alias)) = binding else {
// The quote passed validation but never required exit translation,
// for example a native socket talking to a peer inside the mesh.
return (self.domains.mode == SourceMode::ExitOnly).then_some((local, local));
};
let wire = WireFlow {
local: alias,
..flow
};
let entry = self
.flows
.get(&wire.local)
.and_then(|table| table.get(&wire))
.filter(|entry| now < entry.expires);
let Some(entry) = entry else {
return (wire.local == flow.local
&& (Some(wire.local) == primary
|| self.domains.mode == SourceMode::ExitOnly))
.then_some((wire.local, wire.local));
};
if quote_outbound {
(flow.local == wire.local).then_some((wire.local, entry.host))
} else {
(flow.local == entry.host).then_some((entry.host, wire.local))
}
})
} else {
self.translate(packet, h, local, remote, outbound, now)
};
match output {
Some(packet) if fragmented => fragment_ipv4(packet, self.mtu),
Some(packet) => vec![packet],
None => vec![],
}
}
fn translate(
&mut self,
packet: Bytes,
h: usize,
local: Ipv4Addr,
remote: Ipv4Addr,
outbound: bool,
now: Instant,
) -> Option<Bytes> {
let Some(alias) = self.domains.owner(remote) else {
return Some(packet);
};
// VIP/exit replies and any other special delivery already admitted by
// core may have a source outside the addressed subnet.
if !outbound && local != alias {
return Some(packet);
}
let Some(flow) = WireFlow::parse(&packet, outbound) else {
return (local == alias).then_some(packet);
};
let data = &packet[h..];
let idle = match flow.protocol {
6 => {
let n = usize::from(*data.get(12)? >> 4) * 4;
if n < 20 || n > data.len() {
return None;
}
if data[13] & 5 != 0 {
UDP_IDLE
} else {
TCP_IDLE
}
}
17 => {
if usize::from(u16::from_be_bytes([data[4], data[5]])) != data.len() {
return None;
}
UDP_IDLE
}
_ => ECHO_IDLE,
};
let wire = WireFlow {
local: alias,
..flow
};
let table = self.flows.entry(alias).or_default();
if table.get(&wire).is_some_and(|entry| entry.expires <= now) {
table.remove(&wire);
}
if !table.contains_key(&wire) {
if Some(alias) == self.domains.primary() && local == alias {
return Some(packet);
}
if table.len() >= MAX_FLOWS {
return None;
}
if outbound
&& local != alias
&& (self
.domains
.primary()
.is_some_and(|primary| primary != local)
|| flow.protocol == 6 && data[13] & 0x12 != 2)
{
return None;
}
}
let entry = table.entry(wire).or_insert(Binding {
host: local,
remote_initiated: !outbound,
expires: now + idle,
});
let target = if outbound {
if local != entry.host {
let wildcard_reply = entry.remote_initiated
&& entry.host == alias
&& flow.protocol == 17
&& self.domains.primary() == Some(local);
if !wildcard_reply {
return None;
}
}
alias
} else {
if entry.host != alias && flow.protocol == 6 && data[13] & 0x12 == 2 {
return None;
}
entry.host
};
entry.expires = now + idle;
if target == local {
return Some(packet);
}
let mut out = packet.to_vec();
let address = if outbound { 12 } else { 16 };
out[address..address + 4].copy_from_slice(&target.octets());
let check = u16::from_be_bytes([out[10], out[11]]);
out[10..12].copy_from_slice(&update_checksum(check, local, target).to_be_bytes());
if matches!(flow.protocol, 6 | 17) {
let off = h + if flow.protocol == 6 { 16 } else { 6 };
let check = u16::from_be_bytes([out[off], out[off + 1]]);
if flow.protocol == 6 || check != 0 {
let new = update_checksum(check, local, target);
let new = if new == 0 && flow.protocol == 17 {
u16::MAX
} else {
new
};
out[off..off + 2].copy_from_slice(&new.to_be_bytes());
}
}
Some(out.into())
}
}
/// RFC 1624 one's-complement adjustment for replacing an IPv4 address.
fn update_checksum(checksum: u16, old: Ipv4Addr, new: Ipv4Addr) -> u16 {
let mut sum = u32::from(!checksum);
for (old, new) in old
.octets()
.as_chunks::<2>()
.0
.iter()
.zip(new.octets().as_chunks::<2>().0)
{
sum += u32::from(!u16::from_be_bytes(*old)) + u32::from(u16::from_be_bytes(*new));
}
while sum >> 16 != 0 {
sum = (sum & 0xffff) + (sum >> 16);
}
!(sum as u16)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
const FIRST: Ipv4Addr = Ipv4Addr::new(10, 1, 0, 1);
const SECOND: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 1);
const PEER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 8);
fn aliases() -> Vec<Cidr> {
vec![
Cidr::new(FIRST.into(), 24).unwrap(),
Cidr::new(SECOND.into(), 24).unwrap(),
]
}
fn udp(src: Ipv4Addr, dst: Ipv4Addr, sport: u16, dport: u16, payload: &[u8]) -> Bytes {
use smoltcp::wire::{IpAddress, Ipv4Packet, UdpPacket};
let mut bytes = vec![0; 28 + payload.len()];
bytes[0] = 0x45;
let size = bytes.len() as u16;
bytes[2..4].copy_from_slice(&size.to_be_bytes());
bytes[8] = 64;
bytes[9] = 17;
bytes[12..16].copy_from_slice(&src.octets());
bytes[16..20].copy_from_slice(&dst.octets());
Ipv4Packet::new_unchecked(&mut bytes[..]).fill_checksum();
let mut udp = UdpPacket::new_unchecked(&mut bytes[20..]);
udp.set_src_port(sport);
udp.set_dst_port(dport);
udp.set_len(size - 20);
udp.payload_mut().copy_from_slice(payload);
udp.fill_checksum(&IpAddress::Ipv4(src), &IpAddress::Ipv4(dst));
bytes.into()
}
#[test]
fn connected_udp_keeps_its_kernel_address_while_the_peer_sees_the_right_alias() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
let request = udp(FIRST, PEER, 4123, 1234, b"request");
assert_eq!(
flows.outbound(request),
vec![udp(SECOND, PEER, 4123, 1234, b"request")]
);
assert_eq!(
flows.inbound(udp(PEER, SECOND, 1234, 4123, b"reply")),
vec![udp(PEER, FIRST, 1234, 4123, b"reply")]
);
assert!(
flows
.outbound(udp(SECOND, PEER, 4123, 1234, b"bound collision"))
.is_empty()
);
assert_eq!(
flows.inbound(udp(PEER, SECOND, 1234, 4124, b"to a listener")),
vec![udp(PEER, SECOND, 1234, 4124, b"to a listener")]
);
assert_eq!(
flows.outbound(udp(FIRST, PEER, 4124, 1234, b"wildcard listener reply")),
vec![udp(SECOND, PEER, 4124, 1234, b"wildcard listener reply")]
);
assert_eq!(
flows.inbound(udp(PEER, SECOND, 1234, 4124, b"again")),
vec![udp(PEER, SECOND, 1234, 4124, b"again")]
);
}
#[test]
fn windows_exit_accepts_any_local_alias_and_restores_external_replies() {
let mut flows = SourceFlows::new(&aliases(), Some(FIRST), 1280, SourceMode::ExitOnly);
let internet = Ipv4Addr::new(203, 0, 113, 2);
let request = udp(SECOND, internet, 4123, 443, b"external");
assert_eq!(
flows.outbound(request),
[udp(FIRST, internet, 4123, 443, b"external")]
);
assert_eq!(
flows.inbound(udp(internet, FIRST, 443, 4123, b"reply")),
[udp(internet, SECOND, 443, 4123, b"reply")]
);
// An explicitly bound socket cannot take replies from this flow.
assert!(
flows
.outbound(udp(FIRST, internet, 4123, 443, b"collision"))
.is_empty()
);
// An address in either overlay, including the gateway itself, stays native.
let mesh = udp(SECOND, PEER, 4123, 443, b"mesh");
assert_eq!(flows.outbound(mesh.clone()), [mesh]);
}
#[tokio::test]
async fn wintun_normalizes_only_external_flows_while_an_exit_is_selected() {
use super::windows::ExitSourceTun;
use crate::overlay::{MemoryTun, TunDevice};
let device = MemoryTun::new("test", 1280);
let tun = ExitSourceTun::new(device.clone());
let internet = Ipv4Addr::new(203, 0, 113, 2);
let request = udp(FIRST, internet, 4000, 80, &[1; 1600]);
let on_wire = udp(SECOND, internet, 4000, 80, &[1; 1600]);
tun.set_exit_source(&aliases(), Some(SECOND));
for part in fragment_ipv4(request.clone(), 1280) {
device.push_from_os(part);
}
for expected in fragment_ipv4(on_wire, 1280) {
assert_eq!(tun.recv().await, Some(expected));
}
// Periodic exit rule refreshes must preserve the original socket.
tun.set_exit_source(&aliases(), Some(SECOND));
tun.send(udp(internet, SECOND, 80, 4000, b"reply"))
.await
.unwrap();
assert_eq!(
device.pop_to_os().await,
Some(udp(internet, FIRST, 80, 4000, b"reply"))
);
let forwarded = udp(PEER, internet, 4000, 80, b"forwarded");
device.push_from_os(forwarded.clone());
assert_eq!(tun.recv().await, Some(forwarded));
tun.set_exit_source(&aliases(), None);
device.push_from_os(request.clone());
assert_eq!(tun.recv().await, Some(request));
}
#[test]
fn proper_bound_flows_and_limited_broadcast_keep_their_identity() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
let native = udp(SECOND, PEER, 3000, 3001, b"bound");
assert_eq!(flows.outbound(native.clone()), vec![native]);
assert!(
flows
.outbound(udp(FIRST, PEER, 3000, 3001, b"collision"))
.is_empty()
);
let reply = udp(PEER, SECOND, 3001, 3000, b"native");
assert_eq!(flows.inbound(reply.clone()), vec![reply]);
let broadcast = udp(FIRST, Ipv4Addr::BROADCAST, 3000, 3001, b"lan");
assert_eq!(flows.outbound(broadcast.clone()), vec![broadcast]);
assert!(
flows
.outbound(udp(PEER, PEER, 3100, 3100, b"forged source"))
.is_empty()
);
}
fn packet(src: Ipv4Addr, dst: Ipv4Addr, protocol: u8, data: &[u8]) -> Bytes {
let mut out = vec![0; 20 + data.len()];
let size = out.len() as u16;
out[0] = 0x45;
out[2..4].copy_from_slice(&size.to_be_bytes());
out[8] = 64;
out[9] = protocol;
out[12..16].copy_from_slice(&src.octets());
out[16..20].copy_from_slice(&dst.octets());
out[20..].copy_from_slice(data);
Ipv4Packet::new_unchecked(&mut out).fill_checksum();
out.into()
}
fn tcp(src: Ipv4Addr, dst: Ipv4Addr, sport: u16, dport: u16, flags: u8) -> Bytes {
use smoltcp::wire::{IpAddress, TcpPacket};
let mut data = [0; 20];
data[..2].copy_from_slice(&sport.to_be_bytes());
data[2..4].copy_from_slice(&dport.to_be_bytes());
data[12] = 0x50;
data[13] = flags;
TcpPacket::new_unchecked(&mut data[..])
.fill_checksum(&IpAddress::Ipv4(src), &IpAddress::Ipv4(dst));
packet(src, dst, 6, &data)
}
#[test]
fn tcp_keeps_direction_and_bindings_survive_unrelated_plans() {
let mut aliases = aliases();
let mut flows = SourceFlows::new(&aliases, None, 1280, SourceMode::Primary);
assert!(flows.outbound(tcp(FIRST, PEER, 333, 443, 16)).is_empty());
assert_eq!(
flows.outbound(tcp(FIRST, PEER, 333, 443, 2)),
[tcp(SECOND, PEER, 333, 443, 2)]
);
flows.reconfigure(&aliases, None, 1280);
assert_eq!(
flows.inbound(tcp(PEER, SECOND, 443, 333, 18)),
[tcp(PEER, FIRST, 443, 333, 18)]
);
// An inbound connection cannot replace a client's active translation.
assert!(flows.inbound(tcp(PEER, SECOND, 443, 333, 2)).is_empty());
let inbound = tcp(PEER, SECOND, 12345, 80, 2);
assert_eq!(flows.inbound(inbound.clone()), [inbound]);
let syn_ack = tcp(SECOND, PEER, 80, 12345, 18);
assert_eq!(flows.outbound(syn_ack.clone()), [syn_ack]);
aliases.remove(0);
flows.reconfigure(&aliases, None, 1280);
assert!(
!flows
.flows
.values()
.any(|table| table.values().any(|e| e.host == FIRST))
);
}
#[test]
fn a_new_primary_drains_earlier_translations_and_passes_its_own_packets() {
let mut aliases = aliases();
let mut flows = SourceFlows::new(&aliases, None, 1280, SourceMode::Primary);
assert_eq!(flows.outbound(udp(FIRST, PEER, 2222, 53, b"q")).len(), 1);
aliases.swap(0, 1);
flows.reconfigure(&aliases, Some(SECOND), 1280);
assert_eq!(
flows.inbound(udp(PEER, SECOND, 53, 2222, b"a")),
[udp(PEER, FIRST, 53, 2222, b"a")]
);
let bound = udp(SECOND, PEER, 4444, 443, b"native");
assert_eq!(flows.outbound(bound.clone()), [bound]);
let native_reply = udp(PEER, SECOND, 443, 4444, b"r");
assert_eq!(flows.inbound(native_reply.clone()), [native_reply]);
assert_eq!(flows.flows[&SECOND].len(), 1);
}
#[test]
fn untracked_primary_errors_and_point_to_point_destinations_are_preserved() {
let mut aliases = aliases();
let mut flows = SourceFlows::new(&aliases, None, 1280, SourceMode::Primary);
let router = Ipv4Addr::new(10, 1, 0, 7);
let mut unreachable = vec![3, 1, 0, 0, 0, 0, 0, 0];
unreachable.extend_from_slice(&udp(FIRST, router, 50_000, 7, b"probe")[..28]);
smoltcp::wire::Icmpv4Packet::new_unchecked(&mut unreachable).fill_checksum();
let error = packet(router, FIRST, 1, &unreachable);
assert_eq!(flows.inbound(error.clone()), [error]);
let directed = udp(FIRST, Ipv4Addr::new(10, 2, 0, 255), 5, 6, b"broadcast");
assert_eq!(flows.outbound(directed.clone()), [directed]);
let point = Ipv4Addr::new(10, 2, 0, 0);
aliases[1] = Cidr::new(point.into(), 31).unwrap();
flows.reconfigure(&aliases, None, 1280);
assert_eq!(
flows.outbound(udp(FIRST, SECOND, 5, 6, b"p2p")),
[udp(point, SECOND, 5, 6, b"p2p")]
);
}
#[test]
fn echo_ids_can_match_in_both_directions() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
let message = |src, dst, kind| {
use smoltcp::wire::Icmpv4Packet;
let mut data = [kind, 0, 0, 0, 0x12, 0x34, 0, 2];
Icmpv4Packet::new_unchecked(&mut data[..]).fill_checksum();
packet(src, dst, 1, &data)
};
assert_eq!(
flows.outbound(message(FIRST, PEER, 8)),
[message(SECOND, PEER, 8)]
);
assert_eq!(
flows.inbound(message(PEER, SECOND, 8)),
[message(PEER, SECOND, 8)]
);
assert_eq!(
flows.outbound(message(SECOND, PEER, 0)),
[message(SECOND, PEER, 0)]
);
assert_eq!(
flows.inbound(message(PEER, SECOND, 0)),
[message(PEER, FIRST, 0)]
);
}
#[test]
fn saturated_network_does_not_take_another_networks_capacity() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
for port in 0..MAX_FLOWS {
assert_eq!(
flows
.outbound(udp(FIRST, PEER, port as u16, 53, b"q"))
.len(),
1
);
}
assert!(
flows
.outbound(udp(FIRST, PEER, 60000, 53, b"full"))
.is_empty()
);
let primary_peer = Ipv4Addr::new(10, 1, 0, 20);
let own = udp(FIRST, primary_peer, 60000, 53, b"first");
assert_eq!(flows.outbound(own.clone()), [own]);
for entry in flows.flows.get_mut(&SECOND).unwrap().values_mut() {
entry.expires = Instant::now();
}
flows.last_sweep -= Duration::from_secs(6);
assert_eq!(
flows.outbound(udp(FIRST, PEER, 60000, 53, b"free")).len(),
1
);
assert_eq!(flows.flows[&SECOND].len(), 1);
}
#[test]
fn fragmented_udp_translates_after_assembly_in_both_directions() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
let mut original = udp(FIRST, PEER, 3333, 4444, &[7; 1900]);
let parts = fragment_ipv4(original.clone(), 1280);
let mut output = Vec::new();
for part in parts.into_iter().rev() {
output.extend(flows.outbound(part));
}
assert_eq!(
output,
fragment_ipv4(udp(SECOND, PEER, 3333, 4444, &[7; 1900]), 1280)
);
original = udp(PEER, SECOND, 4444, 3333, &[8; 1900]);
let mut output = Vec::new();
for part in fragment_ipv4(original, 1280) {
output.extend(flows.inbound(part));
}
assert_eq!(
output,
fragment_ipv4(udp(PEER, FIRST, 4444, 3333, &[8; 1900]), 1280)
);
}
}
@@ -0,0 +1,255 @@
//! Translate errors on existing flows, including truncated RFC 792 quotations.
use super::update_checksum;
use bytes::Bytes;
use smoltcp::wire::{Icmpv4Packet, IpProtocol, Ipv4Packet};
use std::net::Ipv4Addr;
pub(super) fn rewrite_error(
packet: Bytes,
header_len: usize,
inbound: bool,
mut lookup: impl FnMut(&[u8], bool) -> Option<(Ipv4Addr, Ipv4Addr)>,
) -> Option<Bytes> {
let outer = Ipv4Packet::new_checked(&packet[..]).ok()?;
if outer.version() != 4
|| header_len < 20
|| header_len != usize::from(outer.header_len())
|| usize::from(outer.total_len()) != packet.len()
|| outer.next_header() != IpProtocol::Icmp
|| outer.more_frags()
|| outer.frag_offset() != 0
|| !outer.verify_checksum()
{
return None;
}
let icmp = outer.payload();
if !Icmpv4Packet::new_checked(icmp).ok()?.verify_checksum() || !matches!(icmp[0], 3 | 11 | 12) {
return None;
}
let payload = &icmp[8..];
// RFC 4884 records the padded quotation length in words when extensions follow.
let quote = match icmp[5] {
0 => payload,
words => payload.get(..usize::from(words) * 4)?,
};
quote.get(..20)?;
// The original total length may exceed the bytes the router chose to quote.
let inner = Ipv4Packet::new_unchecked(quote);
let inner_header = usize::from(inner.header_len());
let quote_len = quote.len().min(usize::from(inner.total_len()));
if inner.version() != 4
|| inner_header < 20
|| quote_len < inner_header + 8
|| inner.frag_offset() != 0
|| !inner.verify_checksum()
{
return None;
}
let (outer_local, inner_local) = if inbound {
(outer.dst_addr(), inner.src_addr())
} else {
(outer.src_addr(), inner.dst_addr())
};
if outer_local != inner_local {
return None;
}
let (old, new) = lookup(&quote[..quote_len], inbound)?;
if old != inner_local {
return None;
}
if old == new {
return Some(packet);
}
let transport = inner.next_header();
let mut result = packet.to_vec();
let quote_start = header_len + 8;
let mut inner = Ipv4Packet::new_unchecked(&mut result[quote_start..quote_start + quote_len]);
if inbound {
inner.set_src_addr(new);
} else {
inner.set_dst_addr(new);
}
inner.fill_checksum();
let transport_bytes = &mut inner.into_inner()[inner_header..];
// A minimum TCP quote includes ports and sequence number, but not its checksum.
let field = match transport {
IpProtocol::Tcp => transport_bytes.get_mut(16..18),
IpProtocol::Udp => transport_bytes.get_mut(6..8),
_ => None,
};
if let Some(field) = field {
let previous = u16::from_be_bytes([field[0], field[1]]);
if previous != 0 || transport == IpProtocol::Tcp {
let adjusted = update_checksum(previous, old, new);
let value = if adjusted == 0 && transport == IpProtocol::Udp {
u16::MAX
} else {
adjusted
};
field.copy_from_slice(&value.to_be_bytes());
}
}
Icmpv4Packet::new_unchecked(&mut result[header_len..]).fill_checksum();
let mut outer = Ipv4Packet::new_unchecked(&mut result);
if inbound {
outer.set_dst_addr(new);
} else {
outer.set_src_addr(new);
}
outer.fill_checksum();
Some(result.into())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use smoltcp::wire::{TcpPacket, UdpPacket};
const APP: Ipv4Addr = Ipv4Addr::new(10, 1, 0, 1);
const WIRE: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 1);
const PEER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 2);
const ROUTER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 3);
fn ipv4(protocol: u8, src: Ipv4Addr, dst: Ipv4Addr, payload: &[u8]) -> Vec<u8> {
let mut p = vec![0; 20 + payload.len()];
let total = p.len() as u16;
p[0] = 0x45;
p[2..4].copy_from_slice(&total.to_be_bytes());
p[8] = 64;
p[9] = protocol;
p[12..16].copy_from_slice(&src.octets());
p[16..20].copy_from_slice(&dst.octets());
p[20..].copy_from_slice(payload);
Ipv4Packet::new_unchecked(&mut p).fill_checksum();
p
}
fn error(src: Ipv4Addr, dst: Ipv4Addr, quote: &[u8]) -> Bytes {
let mut icmp = vec![3, 4, 0, 0, 0, 0, 5, 0];
icmp.extend_from_slice(quote);
Icmpv4Packet::new_unchecked(&mut icmp).fill_checksum();
ipv4(1, src, dst, &icmp).into()
}
#[test]
fn wintun_keeps_mesh_errors_and_restores_exit_errors_from_a_mesh_router() {
use super::super::{SourceFlows, SourceMode};
use crate::overlay::Cidr;
let external = Ipv4Addr::new(203, 0, 113, 200);
let mut flows = SourceFlows::new(
&[
Cidr::new(APP.into(), 24).unwrap(),
Cidr::new(WIRE.into(), 24).unwrap(),
],
Some(WIRE),
1280,
SourceMode::ExitOnly,
);
let mut udp = [0; 8];
udp[4..6].copy_from_slice(&8u16.to_be_bytes());
let mesh_packet = ipv4(17, WIRE, PEER, &udp);
let mesh_error = error(ROUTER, WIRE, &mesh_packet);
assert_eq!(flows.inbound(mesh_error.clone()), [mesh_error]);
let original = ipv4(17, APP, external, &udp);
let translated = flows.outbound(original.clone().into()).pop().unwrap();
assert_eq!(
flows.inbound(error(ROUTER, WIRE, &translated)),
[error(ROUTER, APP, &original)]
);
}
#[test]
fn inbound_pmtu_restores_a_truncated_udp_quote_and_preserves_the_reporting_router() {
use super::super::{SourceFlows, SourceMode};
use crate::overlay::Cidr;
let mut flows = SourceFlows::new(
&[
Cidr::new(APP.into(), 24).unwrap(),
Cidr::new(WIRE.into(), 24).unwrap(),
],
None,
1280,
SourceMode::Primary,
);
let mut udp = [0x71; 16];
udp[4..6].copy_from_slice(&16u16.to_be_bytes());
UdpPacket::new_unchecked(&mut udp[..]).fill_checksum(&APP.into(), &PEER.into());
let original = ipv4(17, APP, PEER, &udp);
let wire = flows.outbound(original.clone().into()).pop().unwrap();
let p = error(ROUTER, WIRE, &wire[..28]);
let restored = flows.inbound(p).pop().unwrap();
let outer = Ipv4Packet::new_checked(&restored[..]).unwrap();
assert!(outer.verify_checksum());
assert_eq!(outer.src_addr(), ROUTER);
assert_eq!(outer.dst_addr(), APP);
assert!(
Icmpv4Packet::new_checked(outer.payload())
.unwrap()
.verify_checksum()
);
assert_eq!(outer.payload()[6..8], 1280u16.to_be_bytes());
assert_eq!(outer.payload()[8..], original[..28]);
}
#[test]
fn outbound_error_restores_tcp_quotes_with_or_without_a_transport_checksum() {
let mut tcp = [0x41; 48];
tcp[12] = 0x50;
TcpPacket::new_unchecked(&mut tcp[..]).fill_checksum(&PEER.into(), &APP.into());
let original = ipv4(6, PEER, APP, &tcp);
TcpPacket::new_unchecked(&mut tcp[..]).fill_checksum(&PEER.into(), &WIRE.into());
let wire = ipv4(6, PEER, WIRE, &tcp);
for length in [28, original.len()] {
let p = error(APP, PEER, &original[..length]);
let rewritten = rewrite_error(p, 20, false, |_, outbound| {
assert!(!outbound);
Some((APP, WIRE))
})
.unwrap();
assert_eq!(rewritten, error(WIRE, PEER, &wire[..length]));
}
}
#[test]
fn malformed_quotes_unknown_flows_and_unrelated_outer_addresses_are_rejected() {
let original = ipv4(17, WIRE, PEER, &[0; 8]);
let p = error(ROUTER, WIRE, &original);
assert_eq!(
rewrite_error(p.clone(), 20, true, |_, _| Some((WIRE, WIRE))),
Some(p.clone())
);
assert!(rewrite_error(p, 20, true, |_, _| None).is_none());
for invalid in [
error(ROUTER, APP, &original),
error(ROUTER, WIRE, &original[..26]),
{
let mut fragment = original.clone();
fragment[7] = 1;
Ipv4Packet::new_unchecked(&mut fragment).fill_checksum();
error(ROUTER, WIRE, &fragment)
},
{
let mut damaged = error(ROUTER, WIRE, &original).to_vec();
damaged[22] ^= 1;
damaged.into()
},
] {
assert!(
rewrite_error(invalid, 20, true, |_, _| panic!(
"invalid quote reached lookup"
))
.is_none()
);
}
// IPv4 UDP allows a zero checksum; translation may not enable it.
let restored = rewrite_error(error(ROUTER, WIRE, &original), 20, true, |_, _| {
Some((WIRE, APP))
})
.unwrap();
assert_eq!(restored[54..56], [0, 0]);
}
}
@@ -0,0 +1,102 @@
//! Wintun default routes cannot specify a preferred IPv4 source address.
use super::{Domains, SourceFlows, SourceMode};
use crate::BoxFuture;
use crate::overlay::{Cidr, OverlayError, TunDevice};
use bytes::Bytes;
use std::net::Ipv4Addr;
use std::sync::{Arc, Mutex, MutexGuard};
pub(crate) struct ExitSourceTun {
device: Arc<dyn TunDevice>,
state: Mutex<Option<State>>,
}
struct State {
flows: SourceFlows,
pending: std::vec::IntoIter<Bytes>,
}
impl std::fmt::Debug for ExitSourceTun {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ExitSourceTun").field(&self.device).finish()
}
}
impl ExitSourceTun {
pub(crate) fn new(device: Arc<dyn TunDevice>) -> Self {
Self {
device,
state: Mutex::default(),
}
}
fn state(&self) -> MutexGuard<'_, Option<State>> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
}
impl TunDevice for ExitSourceTun {
fn name(&self) -> &str {
self.device.name()
}
fn mtu(&self) -> u32 {
self.device.mtu()
}
fn set_exit_source(&self, addresses: &[Cidr], source: Option<Ipv4Addr>) {
let mut active = self.state();
let domains = Domains::new(addresses, source, SourceMode::ExitOnly);
if domains.aliases.len() < 2 || !source.is_some_and(|addr| domains.has(addr)) {
*active = None;
return;
}
if let Some(state) = active.as_mut() {
if state.flows.domains != domains {
state.flows.reconfigure(addresses, source, self.mtu());
state.pending = Vec::new().into_iter();
}
} else {
*active = Some(State {
flows: SourceFlows::new(addresses, source, self.mtu(), SourceMode::ExitOnly),
pending: Vec::new().into_iter(),
});
}
}
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
Box::pin(async {
if let Some(part) = self.state().as_mut().and_then(|s| s.pending.next()) {
return Some(part);
}
loop {
let packet = self.device.recv().await?;
let mut active = self.state();
let Some(state) = active.as_mut() else {
return Some(packet);
};
state.pending = state.flows.outbound(packet).into_iter();
if let Some(part) = state.pending.next() {
return Some(part);
}
}
})
}
fn send(&self, packet: Bytes) -> BoxFuture<'_, Result<(), OverlayError>> {
Box::pin(async move {
let parts = self
.state()
.as_mut()
.map(|s| s.flows.inbound(packet.clone()));
if let Some(parts) = parts {
for part in parts {
self.device.send(part).await?;
}
Ok(())
} else {
self.device.send(packet).await
}
})
}
}
+10 -2
View File
@@ -66,6 +66,10 @@ pub trait TunDevice: Send + Sync + std::fmt::Debug + 'static {
/// The interface MTU.
fn mtu(&self) -> u32;
/// Supply the local Wintun address and exit selection used for off-mesh flows.
#[cfg(any(windows, test))]
fn set_exit_source(&self, _addresses: &[super::Cidr], _source: Option<std::net::Ipv4Addr>) {}
/// The next packet the operating system wants to send, or `None` once the
/// device is gone.
fn recv(&self) -> BoxFuture<'_, Option<Bytes>>;
@@ -476,12 +480,16 @@ mod system {
let name = request.name.clone();
let (reader, writer) = tokio::io::split(device);
Ok(Arc::new(SystemTun {
let device: Arc<dyn TunDevice> = Arc::new(SystemTun {
name,
mtu: request.mtu,
reader: Mutex::new(reader),
writer: Mutex::new(writer),
}) as Arc<dyn TunDevice>)
});
#[cfg(windows)]
let device: Arc<dyn TunDevice> =
Arc::new(crate::overlay::source::windows::ExitSourceTun::new(device));
Ok(device)
}
fn open_error(name: &str, error: tun::Error) -> OverlayError {
+6 -2
View File
@@ -273,15 +273,19 @@ struct Datagram {
bytes: usize,
}
type FragmentKey = (Option<[u8; 32]>, Ipv4Addr, Ipv4Addr, u16, u8);
/// Bounded IPv4 fragment assembly for a local packet consumer.
#[derive(Debug, Default)]
pub(crate) struct Reassembly {
pub struct Reassembly {
pending: HashMap<FragmentKey, Datagram>,
}
impl Reassembly {
/// Forget incomplete datagrams after their five-second lifetime.
pub fn expire(&mut self, now: Instant) {
self.pending
.retain(|_, d| now.duration_since(d.at) < Duration::from_secs(5));
}
/// Accept one fragment or complete packet. `max` bounds pending datagrams;
/// `scope` separates authenticated senders sharing an address domain.
pub fn accept(&mut self, p: Bytes, max: usize, scope: Option<[u8; 32]>) -> Option<Bytes> {
let n = header(&p)?;
let flags = u16::from_be_bytes([p[6], p[7]]);
@@ -363,7 +367,7 @@ impl Reassembly {
}
/// Re-fragments an assembled NAT datagram for the unchanged overlay MTU.
pub(crate) fn fragments(packet: Bytes, mtu: u32) -> Vec<Bytes> {
pub fn fragments(packet: Bytes, mtu: u32) -> Vec<Bytes> {
if packet.len() <= mtu as usize {
return vec![packet];
}
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-runtime"
version = "1.0.0"
version = "1.0.3-rc1"
description = "Built-in mesh transports and status reporting for native tsunagi agents."
edition.workspace = true
rust-version.workspace = true
@@ -8,11 +8,11 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.0" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.0" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.0" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.0" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.0" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.3-rc1" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.3-rc1" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.3-rc1" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.3-rc1" }
tokio.workspace = true
tracing.workspace = true
+2
View File
@@ -107,6 +107,8 @@ pub fn networks(
hostname: peer.hostname.clone(),
transport: peer.transport.to_string(),
rtt_ms: peer.rtt.map(|rtt| rtt.as_millis() as u64),
data_rtt_ms: peer.data_rtt.map(|rtt| rtt.as_millis() as u64),
data_transport_detail: peer.data_transport_detail.clone(),
exit_node: peer.exit_node,
path: data_path_report(&peer.data_path),
})
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-tcp-tls"
version = "1.0.0"
version = "1.0.3-rc1"
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
edition.workspace = true
rust-version.workspace = true
@@ -8,7 +8,7 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.0" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" }
iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
rustls = "0.23"
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-tray"
version = "1.0.0"
version = "1.0.3-rc1"
description = "Tray application to manage a running tsunagi agent."
edition.workspace = true
rust-version.workspace = true
@@ -16,7 +16,7 @@ tsunagi-ui = { path = "../tsunagi-ui" }
# The agent control client and the report types: the GUI is a thin client over
# the same local control interface the CLI uses, so it reuses these directly
# and never re-implements the protocol.
tsunagi-core = { path = "../tsunagi-core", version = "1.0.0" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" }
# Native, lightweight GUI — no web engine. eframe re-exports egui.
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] }
# Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI).
+1 -1
View File
@@ -78,7 +78,7 @@ fn colour_of(health: Health) -> [u8; 3] {
match health {
Health::Disconnected => DARK_RED,
Health::Connected => BLUE,
Health::RangeConflict => [0xd9, 0x91, 0x20],
Health::RangeConflict | Health::InterfaceError => [0xd9, 0x91, 0x20],
Health::ExitNode => GREEN,
}
}
+15
View File
@@ -22,6 +22,8 @@ pub(crate) enum Health {
Disconnected,
/// Connected, nothing out of the ordinary.
Connected,
/// The shared host interface could not apply its addresses or routes.
InterfaceError,
/// At least one configured network is blocked by an overlapping active range.
RangeConflict,
/// This device's traffic leaves through an exit node, and that works.
@@ -35,6 +37,9 @@ impl Health {
let Some(report) = report else {
return Self::Disconnected;
};
if report.overlay_config_error.is_some() {
return Self::InterfaceError;
}
if report
.networks
.iter()
@@ -65,6 +70,7 @@ impl Health {
match self {
Self::Disconnected => "tsunagi: not connected",
Self::Connected => "tsunagi: connected",
Self::InterfaceError => "tsunagi: overlay interface configuration failed",
Self::RangeConflict => "tsunagi: network range conflict; open to switch networks",
Self::ExitNode => "tsunagi: using an exit node",
}
@@ -118,6 +124,15 @@ mod tests {
}
}
#[test]
fn a_host_interface_error_is_visible_even_with_connected_peers() {
let mut status = report(vec![network(2, ExitReport::default())]);
status.overlay_config_error = Some("utun5: could not install subnet route".into());
assert_eq!(Health::of(Some(&status)), Health::InterfaceError);
status.overlay_config_error = None;
assert_eq!(Health::of(Some(&status)), Health::Connected);
}
#[test]
fn overlapping_networks_are_visible_even_while_other_peers_are_connected() {
let mut blocked = NetworkReport {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-ui"
version = "1.0.0"
version = "1.0.3-rc1"
description = "Shared egui widgets for the tray and Android clients."
edition.workspace = true
rust-version.workspace = true
+35 -31
View File
@@ -52,6 +52,8 @@ struct Device<'a> {
data_error: Option<&'a str>,
address: Option<String>,
control_rtt_ms: Option<u64>,
data_rtt_ms: Option<u64>,
data_transport_detail: Option<&'a str>,
overlay: Option<&'a OverlayPeerReport>,
/// It is connected and offers to be an exit node.
exit_node: bool,
@@ -438,14 +440,9 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
.map(|id| {
let overlay = overlay_peers.iter().find(|p| p.endpoint_id == id);
let member = network.members.iter().find(|m| m.endpoint_id == id);
let online = member.is_some_and(|m| m.online)
|| network.peers.iter().any(|p| p.endpoint_id == id);
let path = network
.peers
.iter()
.find(|p| p.endpoint_id == id)
.map(|p| &p.path)
.or_else(|| member.map(|m| &m.path));
let peer = network.peers.iter().find(|p| p.endpoint_id == id);
let online = member.is_some_and(|m| m.online) || peer.is_some();
let path = peer.map(|p| &p.path).or_else(|| member.map(|m| &m.path));
let via_name = match path {
Some(DataPathReport::Relayed { via, .. }) => Some(exit::name_of(network, via)),
_ => None,
@@ -465,25 +462,15 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
hostname,
copy: hostname.map(|h| format!("{h}.{}", network.name)),
id,
data_error: network
.peers
.iter()
.find(|p| p.endpoint_id == id)
.and_then(|p| p.data_error.as_deref()),
data_error: peer.and_then(|p| p.data_error.as_deref()),
address: overlay
.and_then(|p| p.address.clone())
.or_else(|| member.and_then(|m| m.overlay_address_v4.clone())),
control_rtt_ms: network
.peers
.iter()
.find(|p| p.endpoint_id == id)
.and_then(|p| p.rtt_ms),
control_rtt_ms: peer.and_then(|p| p.rtt_ms),
data_rtt_ms: peer.and_then(|p| p.data_rtt_ms),
data_transport_detail: peer.and_then(|p| p.data_transport_detail.as_deref()),
overlay,
exit_node: online
&& network
.peers
.iter()
.any(|p| p.endpoint_id == id && p.exit_node),
exit_node: peer.is_some_and(|p| p.exit_node),
in_use: network.exit.via.as_deref() == Some(id),
}
})
@@ -501,7 +488,7 @@ const COLUMN_HEADERS: [&str; 10] = [
"device",
"exit",
"data",
"RTT",
"RTT data / control",
"address",
"data path",
"pkts",
@@ -647,7 +634,7 @@ fn device_table(
let (path, _) = data_path_text(device.path, device.via_name.as_deref(), device.online);
for (column, text) in [
(2, "waiting".to_owned()),
(3, rtt_text(device.control_rtt_ms)),
(3, rtt_pair(device)),
(4, device.address.clone().unwrap_or_default()),
(5, path),
] {
@@ -728,8 +715,9 @@ fn device_table(
1 => exit_cell(ui, device, network_id, confirm),
2 => tunnel_cell(ui, device),
3 => {
ui.label(rtt_text(device.control_rtt_ms))
.on_hover_text("Control-connection round-trip time.");
ui.label(rtt_pair(device)).on_hover_text(
"Median authenticated direct data-link RTT / selected control-connection RTT. A dash means there is no current measurement.",
);
}
4 => match &device.address {
Some(address) => format::copy_field(ui, address, address),
@@ -791,11 +779,18 @@ fn device_table(
);
}
/// Control RTT is independent of the hidden internal cipher's handshake age.
fn rtt_text(rtt: Option<u64>) -> String {
rtt.map_or_else(|| "—".into(), |value| format!("{value} ms"))
}
fn rtt_pair(device: &Device<'_>) -> String {
format!(
"{} / {}",
rtt_text(device.data_rtt_ms),
rtt_text(device.control_rtt_ms)
)
}
fn tunnel_cell(ui: &mut egui::Ui, device: &Device<'_>) {
let ready = device.overlay.is_some_and(|peer| peer.is_up())
&& !matches!(device.path, None | Some(DataPathReport::None));
@@ -855,7 +850,9 @@ fn data_path_cell(ui: &mut egui::Ui, device: &Device<'_>) {
)
};
response.on_hover_text(match device.path {
Some(DataPathReport::Direct { .. }) => "Direct transport; no mesh relay.",
Some(DataPathReport::Direct { .. }) => device
.data_transport_detail
.unwrap_or("Direct link to this member."),
Some(DataPathReport::Relayed { .. }) => "Traffic forwarded through another device.",
_ if device.online => "Control connected; data transport unavailable.",
_ => "Unreachable.",
@@ -1110,6 +1107,8 @@ mod tests {
data_error: None,
endpoint_id: "peer".into(),
rtt_ms: Some(27),
data_rtt_ms: Some(203),
data_transport_detail: Some("relay via relay.example".into()),
..Default::default()
}],
overlay: Some(OverlayReport {
@@ -1125,6 +1124,11 @@ mod tests {
};
let rows = devices(&network, "own");
assert_eq!(rtt_text(rows[0].control_rtt_ms), "27 ms");
assert_eq!(rtt_text(rows[0].data_rtt_ms), "203 ms");
assert_eq!(
rows[0].data_transport_detail,
Some("relay via relay.example")
);
assert_eq!(rtt_text(None), "—");
}
@@ -1231,8 +1235,8 @@ mod tests {
let mut texts = Vec::new();
collect_text(&shapes, &mut texts);
for (label, next_column) in [
("RTT".to_string(), "address"),
(rtt_text(Some(12_345)), "address"),
("RTT data / control".to_string(), "address"),
(rtt_pair(&rows[0]), "address"),
(format!("{packets}/{}", packets + 1), "bytes"),
(format!("{}/{}", packets * 2, (packets + 1) * 2), "bytes"),
] {
+12 -2
View File
@@ -35,7 +35,7 @@ pub(super) fn roster(
let size = egui::vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 8.0);
ui.spacing_mut().item_spacing.y = 1.0;
let (header, _) = ui.allocate_exact_size(size, egui::Sense::hover());
for (x, title) in offsets.into_iter().zip(["device", "IPv4", "RTT"]) {
for (x, title) in offsets.into_iter().zip(["device", "IPv4", "Data RTT"]) {
ui.painter().text(
header.left_center() + egui::vec2(x, 0.),
egui::Align2::LEFT_CENTER,
@@ -73,7 +73,7 @@ pub(super) fn roster(
);
}
let name = member.name();
let rtt = rtt_text(member.control_rtt_ms);
let rtt = rtt_text(member.data_rtt_ms);
let labels = [
name.as_str(),
member.address.as_deref().unwrap_or("—"),
@@ -148,6 +148,16 @@ fn details(
ui.label(path);
tunnel_cell(ui, member);
});
if member.online {
if let Some(path) = member.data_transport_detail {
ui.label(path);
}
ui.label(format!(
"Data RTT {} · Control RTT {}",
rtt_text(member.data_rtt_ms),
rtt_text(member.control_rtt_ms)
));
}
if let Some(error) = member.data_error {
ui.colored_label(AMBER, error);
}
+4 -3
View File
@@ -18,7 +18,7 @@ pub fn choose_exit(ui: &mut Ui, network: &NetworkReport, own: &str) -> Option<Ex
let muted = ui.visuals().weak_text_color();
for (x, label) in [
(columns.name, "Exit node"),
(columns.rtt, "RTT"),
(columns.rtt, "Data RTT"),
(columns.path, "Path"),
] {
ui.painter().text(
@@ -83,7 +83,7 @@ pub fn choose_exit(ui: &mut Ui, network: &NetworkReport, own: &str) -> Option<Ex
peer: Some(candidate.id),
name: &name,
address: candidate.address.as_deref(),
rtt: candidate.control_rtt_ms,
rtt: candidate.data_rtt_ms,
path,
transport,
selected: candidate.in_use,
@@ -224,7 +224,8 @@ mod tests {
network.peers.push(PeerReport {
endpoint_id: id.into(),
hostname: Some(name.into()),
rtt_ms: Some(37),
data_rtt_ms: Some(37),
rtt_ms: Some(142),
path: DataPathReport::Direct {
transport: "wg".into(),
},
+4 -1
View File
@@ -105,6 +105,9 @@ pub fn draw_header(
"cache unavailable",
);
}
if let Some(error) = &report.overlay_config_error {
ui.colored_label(BAD, format!("Shared overlay interface {error}"));
}
}
/// One compact network tile.
@@ -278,7 +281,7 @@ fn draw_protocols(
egui::CollapsingHeader::new(format!("data transports {summary}"))
.id_salt(("protocols", &network.network_id))
.show(ui, |ui| {
ui.weak("Preference order; changes apply immediately and are saved.");
ui.weak("Order sets the first choice. Peers that support link comparison can switch to a faster enabled transport.");
let mut selected = network.protocols.clone();
let mut changed = false;
ui.add_enabled_ui(!agent.busy(), |ui| {
+2 -2
View File
@@ -3,7 +3,7 @@ name = "tsunagi-wg-quic"
# Its own version, and deliberately separate from the wire version it
# negotiates: a release here does not stop it talking to a peer on an older
# build, because what peers compare is `ANNOUNCEMENT_VERSION`.
version = "1.0.0"
version = "1.0.3-rc1"
description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers."
edition.workspace = true
rust-version.workspace = true
@@ -11,7 +11,7 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.0" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" }
iroh.workspace = true
tokio.workspace = true
serde.workspace = true
+265 -47
View File
@@ -8,7 +8,9 @@ use std::{
time::Duration,
};
use tempfile::TempDir;
use tsunagi::dataplane::transport::{DataCarrier, PacketTransport, SharedLink, TransportError};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tsunagi::dataplane::transport::{PacketTransport, SharedLink, TransportError};
use tsunagi::discovery::SharedMemoryDiscovery;
use tsunagi::overlay::{MemoryTun, MemoryTunFactory};
use tsunagi::testing::{config_with, network, wait_for_peers, wait_until};
@@ -56,7 +58,8 @@ struct Node {
agent: Agent,
tunnel: Arc<WireguardPlugin>,
tuns: MemoryTunFactory,
accept: tokio::task::JoinHandle<()>,
wireguard: Option<Arc<UdpTransport>>,
_listeners: tokio::task::JoinSet<()>,
}
impl Node {
async fn new(
@@ -64,14 +67,15 @@ impl Node {
protocol: &str,
ports: Arc<std::sync::Mutex<Vec<(EndpointId, u16)>>>,
) -> Self {
Self::configured(discovery, protocol, ports, true).await
Self::configured(discovery, &[protocol], ports, true).await
}
async fn configured(
discovery: &SharedMemoryDiscovery,
protocol: &str,
protocols: &[&str],
ports: Arc<std::sync::Mutex<Vec<(EndpointId, u16)>>>,
register_transport: bool,
) -> Self {
tsunagi::testing::init_tracing();
let root = TempDir::new().unwrap();
let identity = tsunagi::storage::StateStore::open(
tsunagi::StoragePaths::under(root.path()).state_db(),
@@ -86,49 +90,64 @@ impl Node {
.await
.unwrap();
let tuns = MemoryTunFactory::new();
let config = config_with(root.path(), discovery)
let mut config = config_with(root.path(), discovery)
.with_interface(Arc::new(tuns.clone()), "carrier-test", 1280)
.with_tunnel(tunnel.clone());
let (agent, accept) = if protocol == "wg" {
let transport =
UdpTransport::wireguard(identity.endpoint_id(), Ipv4Addr::LOCALHOST, None);
let carrier: Arc<dyn DataCarrier> = UdpCarrier::new(transport.clone());
let mut config = config.with_carrier(carrier);
if register_transport {
config = config.with_custom_transport(protocol, transport.clone());
let mut wireguard = None;
let mut tls = None;
for &protocol in protocols {
match protocol {
"wg" => {
let transport =
UdpTransport::wireguard(identity.endpoint_id(), Ipv4Addr::LOCALHOST, None);
config = config.with_carrier(UdpCarrier::new(transport.clone()));
if register_transport {
config = config.with_custom_transport(protocol, transport.clone());
}
wireguard = Some(transport);
}
"tcp-tls" => {
let transport = Arc::new(
TcpTlsTransport::bind(&identity, Some(0), None)
.await
.unwrap(),
);
ports
.lock()
.unwrap()
.push((identity.endpoint_id(), transport.bound_port()));
config = config
.with_carrier(TcpTlsCarrier::new(transport.clone()))
.with_custom_transport(
protocol,
Arc::new(LoopbackTls {
inner: transport.clone(),
ports: ports.clone(),
}),
);
tls = Some(transport);
}
"wg-quic" => {
config = config.with_carrier(Arc::new(
tsunagi::dataplane::transport::iroh_link::IrohCarrier,
))
}
_ => panic!("unknown carrier {protocol}"),
}
let agent = Agent::spawn(config).await.unwrap();
}
let agent = Agent::spawn(config).await.unwrap();
let mut listeners = tokio::task::JoinSet::new();
if let Some(transport) = wireguard.clone() {
let incoming = agent.clone();
let accept = tokio::spawn(async move {
listeners.spawn(async move {
while let Some(link) = transport.next_inbound().await {
let _ = incoming.install_inbound_link(link).await;
}
});
(agent, accept)
} else {
let transport = Arc::new(
TcpTlsTransport::bind(&identity, Some(0), None)
.await
.unwrap(),
);
ports
.lock()
.unwrap()
.push((identity.endpoint_id(), transport.bound_port()));
let carrier: Arc<dyn DataCarrier> = TcpTlsCarrier::new(transport.clone());
let custom = Arc::new(LoopbackTls {
inner: transport.clone(),
ports,
});
let agent = Agent::spawn(
config
.with_carrier(carrier)
.with_custom_transport(protocol, custom),
)
.await
.unwrap();
}
if let Some(transport) = tls {
let incoming = agent.clone();
let accept = tokio::spawn(async move {
listeners.spawn(async move {
transport
.accept_loop(move |link| {
let incoming = incoming.clone();
@@ -138,14 +157,14 @@ impl Node {
})
.await;
});
(agent, accept)
};
}
Self {
_root: root,
agent,
tunnel,
tuns,
accept,
wireguard,
_listeners: listeners,
}
}
fn tun(&self) -> Arc<MemoryTun> {
@@ -162,12 +181,215 @@ impl Node {
}
}
// Real TLS bytes flow through this loopback proxy. Delay one direction so
// authenticated probes can distinguish two otherwise healthy carriers.
async fn delayed_tcp_listener(port: u16) -> (u16, tokio::task::JoinHandle<()>) {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let local_port = listener.local_addr().unwrap().port();
let task = tokio::spawn(async move {
let mut streams = tokio::task::JoinSet::new();
while let Ok((client, _)) = listener.accept().await {
streams.spawn(async move {
let server = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).await?;
let (mut from_client, mut to_client) = client.into_split();
let (mut from_server, mut to_server) = server.into_split();
let delayed = async {
let mut buffer = [0; 8192];
loop {
let n = from_client.read(&mut buffer).await?;
if n == 0 {
return Ok::<(), std::io::Error>(());
}
tokio::time::sleep(Duration::from_millis(85)).await;
to_server.write_all(&buffer[..n]).await?;
}
};
tokio::select! {
res = delayed => res,
res = tokio::io::copy(&mut from_server, &mut to_client) => res.map(|_| ()),
}
});
}
});
(local_port, task)
}
async fn deliver(source: &Node, destination: &Node, id: NetworkId, tag: u8) {
let mut packet = vec![0; 32];
packet[0] = 0x45;
packet[2..4].copy_from_slice(&32_u16.to_be_bytes());
packet[8] = 64;
packet[9] = 253;
packet[12..16].copy_from_slice(&source.addr(id).octets());
packet[16..20].copy_from_slice(&destination.addr(id).octets());
packet[20] = tag;
let packet = Bytes::from(packet);
source.tun().push_from_os(packet.clone());
assert_eq!(
tokio::time::timeout(Duration::from_secs(5), destination.tun().pop_to_os())
.await
.unwrap()
.unwrap(),
packet
);
}
#[tokio::test]
async fn data_flows_over_the_incumbent_while_a_faster_carrier_is_measured_and_promoted() {
use tsunagi::agent::{DataPath, Event};
let discovery = SharedMemoryDiscovery::new();
let ports = Arc::default();
let protocols = ["tcp-tls", "wg-quic"];
let a = Node::configured(&discovery, &protocols, Arc::clone(&ports), true).await;
let b = Node::configured(&discovery, &protocols, Arc::clone(&ports), true).await;
let mut proxies = Vec::new();
let registered = ports.lock().unwrap().clone();
for (peer, port) in registered {
let (proxy_port, task) = delayed_tcp_listener(port).await;
proxies.push(task);
ports
.lock()
.unwrap()
.iter_mut()
.find(|(id, _)| *id == peer)
.unwrap()
.1 = proxy_port;
}
let mut events = a.agent.subscribe();
let (name, secret) = network("measured-carrier");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
let observations = |node: &Node| {
let overview = node.tunnel.overview(id)?;
let tunnel = overview.peers.first()?.tunnel.as_ref()?;
tunnel.health.is_up().then_some(tunnel.stats.counter_epoch)
};
let epochs = wait_until(
"both endpoints have a single established cipher",
|| async { Some((observations(&a)?, observations(&b)?)) },
)
.await;
let selected = |protocol: &str, status: &tsunagi::NetworkStatus| {
matches!(status.peers.first().map(|p| &p.data_path),
Some(DataPath::Direct { transport }) if transport == protocol)
};
tokio::time::timeout(Duration::from_secs(60), async {
wait_until("slow TLS data-link probes are visible", || async {
let status = a.agent.network_status(id).await.ok()?;
(selected("tcp-tls", &status) && status.peers.first()?.data_rtt? >= Duration::from_millis(75)).then_some(())
}).await;
deliver(&a, &b, id, 1).await;
tsunagi::testing::wait_event(&mut events, |event| {
matches!(event, Event::DataLinkUp { network, protocol, .. } if *network == id && protocol == "wg-quic").then_some(())
}).await;
for (source, dest) in [(&a, &b), (&b, &a)] {
assert!(selected("tcp-tls", &source.agent.network_status(id).await.unwrap()));
deliver(source, dest, id, 2).await;
}
wait_until("both endpoints use the faster measured data link", || async {
let left = a.agent.network_status(id).await.ok()?;
let right = b.agent.network_status(id).await.ok()?;
(selected("wg-quic", &left) && selected("wg-quic", &right)).then_some(())
}).await;
for (source, dest) in [(&a, &b), (&b, &a)] {
deliver(source, dest, id, 3).await;
}
assert_eq!((observations(&a), observations(&b)), (Some(epochs.0), Some(epochs.1)));
}).await.expect("comparison must finish with traffic on the existing tunnel");
a.agent.shutdown().await;
b.agent.shutdown().await;
for proxy in proxies {
proxy.abort();
}
}
#[tokio::test]
async fn a_stalled_comparison_does_not_delay_recovery_on_a_third_carrier() {
use tsunagi::agent::DataPath;
let discovery = SharedMemoryDiscovery::new();
let ports = Arc::default();
let protocols = ["wg", "tcp-tls", "wg-quic"];
let a = Node::configured(&discovery, &protocols, Arc::clone(&ports), true).await;
let b = Node::configured(&discovery, &protocols, Arc::clone(&ports), true).await;
let stalled = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
for (_, port) in &mut *ports.lock().unwrap() {
*port = stalled.local_addr().unwrap().port();
}
let (name, secret) = network("recover-during-comparison");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
let nodes = [&a, &b];
let both_use = |carrier: &'static str| async move {
for node in nodes {
let status = node.agent.network_status(id).await.ok()?;
if !matches!(&status.peers.first()?.data_path, DataPath::Direct { transport } if transport == carrier)
|| !node
.tunnel
.overview(id)?
.peers
.first()?
.tunnel
.as_ref()?
.health
.is_up()
{
return None;
}
}
Some(())
};
wait_until("both endpoints start on native WireGuard", || {
both_use("wg")
})
.await;
deliver(&a, &b, id, 1).await;
// Accept the real TLS ClientHello but never answer it. The TCP handshake
// establishes that the background attempt has started before WG is lost.
let mut handshake = tokio::time::timeout(Duration::from_secs(30), async {
let (mut handshake, _) = stalled.accept().await.unwrap();
assert_eq!(handshake.read_u8().await.unwrap(), 22);
handshake
})
.await
.expect("background TLS ClientHello");
for (source, destination) in [(&a, &b), (&b, &a)] {
source
.wireguard
.as_ref()
.unwrap()
.forget_peer(id, destination.agent.endpoint_id());
}
tokio::time::timeout(Duration::from_secs(8), async {
wait_until(
"QUIC recovers traffic before the background deadline",
|| both_use("wg-quic"),
)
.await;
deliver(&a, &b, id, 2).await;
deliver(&b, &a, id, 3).await;
let mut tail = Vec::new();
if let Err(error) = handshake.read_to_end(&mut tail).await {
assert!(
matches!(
error.kind(),
std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted
),
"{error}"
);
}
})
.await
.expect("the stalled TLS attempt must be cancelled when QUIC can recover");
a.agent.shutdown().await;
b.agent.shutdown().await;
}
#[tokio::test]
async fn missing_native_transport_cannot_silently_turn_wireguard_into_quic() {
let discovery = SharedMemoryDiscovery::new();
let ports = Arc::default();
let a = Node::configured(&discovery, "wg", Arc::clone(&ports), false).await;
let b = Node::configured(&discovery, "wg", ports, false).await;
let a = Node::configured(&discovery, &["wg"], Arc::clone(&ports), false).await;
let b = Node::configured(&discovery, &["wg"], ports, false).await;
let (name, secret) = network("no-disguised-quic-fallback");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
@@ -193,8 +415,6 @@ async fn missing_native_transport_cannot_silently_turn_wireguard_into_quic() {
.await;
a.agent.shutdown().await;
b.agent.shutdown().await;
a.accept.abort();
b.accept.abort();
}
#[tokio::test]
@@ -279,7 +499,5 @@ async fn wireguard_and_tls_carriers_both_carry_the_same_internal_cipher_and_exac
}
a.agent.shutdown().await;
b.agent.shutdown().await;
a.accept.abort();
b.accept.abort();
}
}
+247 -7
View File
@@ -18,16 +18,17 @@ use iroh::EndpointId;
use tempfile::TempDir;
use tsunagi::dataplane::IpPlugin;
use tsunagi::discovery::SharedMemoryDiscovery;
use tsunagi::identity::NetworkId;
use tsunagi::identity::{NetworkId, NetworkName, NetworkSecret};
use tsunagi::overlay::{MemoryTun, MemoryTunFactory, MockHostRules};
use tsunagi::state::{DEFAULT_IPV4_RANGE, Ipv4Range};
use tsunagi::testing::{network, wait_until};
use tsunagi::{Agent, NetworkStatus};
use tsunagi::{Agent, AgentConfig, NetworkStatus};
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34);
struct Node {
_dir: TempDir,
dir: TempDir,
agent: Agent,
plugin: Arc<WireguardPlugin>,
tuns: MemoryTunFactory,
@@ -36,7 +37,27 @@ struct Node {
impl Node {
async fn spawn(discovery: &SharedMemoryDiscovery, tag: &str) -> Self {
let dir = TempDir::new().unwrap();
Self::open(
TempDir::new().unwrap(),
discovery,
tag,
Some(DEFAULT_IPV4_RANGE),
)
.await
}
async fn open(
dir: TempDir,
discovery: &SharedMemoryDiscovery,
tag: &str,
range: Option<Ipv4Range>,
) -> Self {
let config =
tsunagi::testing::config_with(dir.path(), discovery).with_overlay_ipv4_range(range);
Self::start(dir, tag, config).await
}
async fn start(dir: TempDir, tag: &str, config: AgentConfig) -> Self {
let tuns = MemoryTunFactory::new();
let rules = MockHostRules::new();
let plugin = WireguardPlugin::open(
@@ -46,8 +67,7 @@ impl Node {
.await
.unwrap();
let agent = Agent::spawn(
tsunagi::testing::config_with(dir.path(), discovery)
.with_overlay_ipv4_range(Some(tsunagi::state::DEFAULT_IPV4_RANGE))
config
.with_interface(
Arc::new(tuns.clone().with_host_rules(Arc::new(rules.clone()))),
tag,
@@ -61,7 +81,7 @@ impl Node {
.await
.unwrap();
Self {
_dir: dir,
dir,
agent,
plugin,
tuns,
@@ -99,6 +119,22 @@ impl Node {
async fn status(&self, network: NetworkId) -> NetworkStatus {
self.agent.network_status(network).await.unwrap()
}
async fn selected_exits(&self) -> Vec<(NetworkId, EndpointId)> {
self.agent
.status()
.await
.unwrap()
.networks
.into_iter()
.filter_map(|network| Some((network.network_id, network.exit_via?)))
.collect()
}
async fn shutdown(self) -> TempDir {
self.agent.shutdown().await;
self.dir
}
}
fn ipv4_packet(source: Ipv4Addr, destination: Ipv4Addr, payload: &[u8]) -> Bytes {
@@ -124,6 +160,210 @@ async fn next(tun: &MemoryTun) -> Bytes {
.unwrap()
}
struct ExitNetwork<'a> {
id: NetworkId,
peer: &'a Node,
client_addr: Ipv4Addr,
peer_addr: Ipv4Addr,
peer_tun: Arc<MemoryTun>,
}
impl<'a> ExitNetwork<'a> {
async fn join(
client: &Node,
peer: &'a Node,
credentials: (NetworkName, NetworkSecret),
) -> Self {
let (name, secret) = credentials;
let id = peer.agent.join_network(&name, &secret).await.unwrap();
peer.overlay(id).await;
let range = peer.status(id).await.range.unwrap();
peer.agent.set_exit_offer(id, true).await.unwrap();
client.agent.join_network(&name, &secret).await.unwrap();
client.wait_for_tunnels(id, 1).await;
peer.wait_for_tunnels(id, 1).await;
let client_addr = wait_until(
"client adopts the peer's range and sees its exit offer",
|| async {
let address = client.plugin.overview(id)?.overlay_address_v4?;
(range.contains(address)
&& client
.status(id)
.await
.peers
.iter()
.any(|p| p.endpoint_id == peer.id() && p.exit_node))
.then_some(address)
},
)
.await;
Self {
id,
peer,
client_addr,
peer_addr: peer.overlay(id).await,
peer_tun: peer.tun().await,
}
}
async fn check_mesh(&self, client_tun: &MemoryTun) {
let request = ipv4_packet(self.client_addr, self.peer_addr, self.id.as_bytes());
client_tun.push_from_os(request.clone());
assert_eq!(next(&self.peer_tun).await, request);
let reply = ipv4_packet(self.peer_addr, self.client_addr, self.id.as_bytes());
self.peer_tun.push_from_os(reply.clone());
assert_eq!(next(client_tun).await, reply);
}
}
#[tokio::test]
async fn switching_the_exit_between_networks_keeps_both_overlays_reachable() {
let discovery = SharedMemoryDiscovery::new();
let client = Node::open(TempDir::new().unwrap(), &discovery, "client", None).await;
let left = Node::spawn(&discovery, "left").await;
let right_range = "10.99.0.0/16".parse().unwrap();
let right = Node::open(
TempDir::new().unwrap(),
&discovery,
"right",
Some(right_range),
)
.await;
let alpha = ExitNetwork::join(&client, &left, network("exit-left")).await;
let beta = ExitNetwork::join(&client, &right, network("exit-right")).await;
let tun = client.tun().await;
for exit in [&alpha, &beta] {
client
.agent
.set_exit_via(exit.id, Some(exit.peer.id()))
.await
.unwrap();
let plan = client.rules.exit().installed().unwrap();
assert_eq!(plan.client_source, Some(exit.client_addr));
assert_eq!(plan.overlay.len(), 2);
let internet = ipv4_packet(exit.client_addr, INTERNET, b"request");
tun.push_from_os(internet.clone());
assert_eq!(next(&exit.peer_tun).await, internet);
let reply = ipv4_packet(INTERNET, exit.client_addr, b"reply");
exit.peer_tun.push_from_os(reply.clone());
assert_eq!(next(&tun).await, reply);
for net in [&alpha, &beta] {
let selected = (net.id == exit.id).then(|| net.peer.id());
assert_eq!(client.status(net.id).await.exit_via, selected);
net.check_mesh(&tun).await;
}
}
// Right offers on beta only. An invalid replacement must preserve the live route.
assert!(
client
.agent
.set_exit_via(alpha.id, Some(right.id()))
.await
.is_err()
);
assert_eq!(client.selected_exits().await, [(beta.id, right.id())]);
let request = ipv4_packet(beta.client_addr, INTERNET, b"still using beta");
tun.push_from_os(request.clone());
assert_eq!(next(&beta.peer_tun).await, request);
// Two independent commands may race. Both must leave one effective exit,
// and restarting from the same SQLite state must restore that exact choice.
let (one, two) = tokio::join!(
client.agent.set_exit_via(alpha.id, Some(left.id())),
client.agent.set_exit_via(beta.id, Some(right.id())),
);
one.unwrap();
two.unwrap();
let exits = client.selected_exits().await;
assert!(
exits == [(alpha.id, left.id())] || exits == [(beta.id, right.id())],
"{exits:?}"
);
let (lost, live) = if exits[0].0 == alpha.id {
(&alpha, &beta)
} else {
(&beta, &alpha)
};
lost.peer.agent.shutdown().await;
client.wait_for_tunnels(lost.id, 0).await;
wait_until("the selected exit is offline", || async {
let status = client.status(lost.id).await;
(status.exit_via == Some(lost.peer.id()) && !status.exit_via_online).then_some(())
})
.await;
assert!(client.rules.exit().installed().unwrap().client);
let dropped = client.agent.overlay().unwrap().counters.undeliverable;
tun.push_from_os(ipv4_packet(lost.client_addr, INTERNET, b"offline exit"));
wait_until(
"internet traffic cannot use the other offering peer",
|| async { (client.agent.overlay()?.counters.undeliverable > dropped).then_some(()) },
)
.await;
live.check_mesh(&tun).await;
let dir = client.shutdown().await;
let restarted = Node::open(dir, &discovery, "client", None).await;
assert_eq!(restarted.selected_exits().await, exits);
restarted.agent.shutdown().await;
live.peer.agent.shutdown().await;
}
#[tokio::test]
async fn selecting_a_shared_peer_uses_only_the_chosen_membership_for_exit() {
let discovery = SharedMemoryDiscovery::new();
let client = Node::open(TempDir::new().unwrap(), &discovery, "client", None).await;
let dir = TempDir::new().unwrap();
let config = tsunagi::testing::config_with(dir.path(), &discovery);
let peer = Node::start(dir, "shared", config).await;
// Fixed credentials keep the two automatically derived /24s distinct.
let mut meshes = Vec::new();
for (name, secret) in [("shared-left", [1; 32]), ("shared-right", [2; 32])] {
let credentials = (
NetworkName::new(name).unwrap(),
NetworkSecret::from_bytes(secret).unwrap(),
);
meshes.push(ExitNetwork::join(&client, &peer, credentials).await);
}
let tun = client.tun().await;
for (chosen, other) in [(&meshes[0], &meshes[1]), (&meshes[1], &meshes[0])] {
client
.agent
.set_exit_via(chosen.id, Some(peer.id()))
.await
.unwrap();
assert_eq!(client.selected_exits().await, [(chosen.id, peer.id())]);
assert_eq!(
client.rules.exit().installed().unwrap().client_source,
Some(chosen.client_addr)
);
chosen.check_mesh(&tun).await;
other.check_mesh(&tun).await;
let request = ipv4_packet(chosen.client_addr, INTERNET, b"external");
tun.push_from_os(request.clone());
assert_eq!(next(&chosen.peer_tun).await, request);
// Both memberships authenticate the same device key. A reply through
// its other tunnel still lacks the external-source exception.
let wrong_source = client.agent.overlay().unwrap().counters.wrong_source;
chosen
.peer_tun
.push_from_os(ipv4_packet(INTERNET, other.client_addr, b"wrong mesh"));
wait_until(
"external reply on unselected membership is rejected",
|| async {
(client.agent.overlay()?.counters.wrong_source > wrong_source).then_some(())
},
)
.await;
let reply = ipv4_packet(INTERNET, chosen.client_addr, b"reply");
chosen.peer_tun.push_from_os(reply.clone());
assert_eq!(next(&tun).await, reply);
}
peer.agent.shutdown().await;
client.agent.shutdown().await;
}
#[tokio::test]
async fn a_member_sends_its_internet_traffic_through_an_exit_node_and_gets_the_answers() {
let discovery = SharedMemoryDiscovery::new();
@@ -42,6 +42,8 @@ fn source(agent: Agent, plugin: Arc<WireguardPlugin>) -> Arc<dyn tsunagi::ipc::R
hostname: peer.hostname.clone(),
transport: format!("{:?}", peer.transport),
rtt_ms: peer.rtt.map(|rtt| rtt.as_millis() as u64),
data_rtt_ms: peer.data_rtt.map(|rtt| rtt.as_millis() as u64),
data_transport_detail: peer.data_transport_detail.clone(),
exit_node: peer.exit_node,
path: Default::default(),
})
+19
View File
@@ -1133,6 +1133,25 @@ async fn two_networks_share_one_interface_with_keys_and_ranges_of_their_own() {
"the other overlay must see nothing"
);
for (network, local, remote) in [(alpha, hub_alpha, &left), (beta, hub_beta, &right)] {
let address = remote.overlay(network).await;
for (sender, source, receiver, destination) in [
(&hub, local, remote, address),
(remote, address, &hub, local),
] {
let packet = ipv4_packet(source, destination, network.as_bytes());
sender.tun(network).await.push_from_os(packet.clone());
let received = tokio::time::timeout(
tsunagi::testing::DEADLINE,
receiver.tun(network).await.pop_to_os(),
)
.await
.expect("bidirectional traffic on both networks")
.unwrap();
assert_eq!(received, packet);
}
}
hub.shutdown().await;
left.shutdown().await;
right.shutdown().await;
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-wireguard"
version = "1.0.0"
version = "1.0.3-rc1"
description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi."
edition.workspace = true
rust-version.workspace = true
@@ -8,7 +8,7 @@ license = "WTFPL AND Apache-2.0"
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.0" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" }
iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
serde.workspace = true
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi"
version = "1.0.0"
version = "1.0.3-rc1"
description = "The tsunagi command line agent."
edition.workspace = true
rust-version.workspace = true
@@ -12,11 +12,11 @@ name = "tsng"
path = "src/main.rs"
[dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.0" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.0", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.0" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.0" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.0" }
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.3-rc1" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.3-rc1" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.3-rc1" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.3-rc1" }
iroh.workspace = true
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
tracing.workspace = true
+63 -15
View File
@@ -80,7 +80,8 @@ enum Command {
/// device's internet traffic through one.
///
/// The other half of `tsng network exit-node`, which is what makes a
/// device offer itself. A device uses one exit node at a time.
/// device offer itself. One exit serves all active networks. Traffic to
/// peers and services in each mesh keeps its own route.
ExitNode(ExitNodeArgs),
/// Removes everything this device has stored and starts over.
Wipe(WipeArgs),
@@ -106,7 +107,7 @@ struct DnsArgs {
#[derive(Debug, Args)]
#[command(
after_help = "Examples:\n tsng protocols\n tsng protocols home\n tsng protocols home awg,wg-quic\n tsng protocols home none\n\nThe selection is local to this device, saved per network and applied immediately.\nThe choice governs local incoming and outgoing data links only.
Adjacent peers need a common external transport; control and discovery are independent."
The order sets the first choice. Peers that support link comparison can switch to a faster mutually enabled transport."
)]
struct ProtocolsArgs {
#[command(flatten)]
@@ -116,7 +117,7 @@ struct ProtocolsArgs {
control_socket: Option<PathBuf>,
/// Network's exact name, id or unique id prefix.
network: Option<String>,
/// Replace the selection, best first: awg,wg-quic; none disables data traffic.
/// Replace the enabled transports in initial preference order. Use none for control only.
#[arg(value_name = "LIST", requires = "network")]
protocols: Option<String>,
}
@@ -486,7 +487,7 @@ struct UpArgs {
#[arg(long, help_heading = "System")]
no_tun: bool,
/// Initial protocol selection for networks without a saved choice, best first.
/// Enabled transports in initial preference order for networks without a saved choice.
///
/// A pair of peers uses one they both have at the same wire version. A
/// peer with none in common keeps its control plane and gets no data
@@ -1995,7 +1996,7 @@ async fn protocols_command(args: ProtocolsArgs) -> Result<(), Box<dyn std::error
None => network.protocols.clone(),
};
println!(
"protocols {} for `{}` ({}) · preference order",
"protocols {} for `{}` ({}) · initial preference order",
if protocols.is_empty() {
"none".into()
} else {
@@ -2624,8 +2625,11 @@ async fn exit_node_command(args: ExitNodeArgs) -> Result<(), Box<dyn std::error:
any = true;
let in_use = network.exit.via.as_deref() == Some(peer.endpoint_id.as_str());
let mut detail = format!("network {}", network.name);
if let Some(rtt) = peer.data_rtt_ms {
detail.push_str(&format!(" · data RTT {rtt}ms"));
}
if let Some(rtt) = peer.rtt_ms {
detail.push_str(&format!(" · rtt {rtt}ms"));
detail.push_str(&format!(" · control RTT {rtt}ms"));
}
if in_use {
detail.push_str(" · IN USE");
@@ -3239,6 +3243,13 @@ async fn status(args: StatusArgs) -> Result<(), Box<dyn std::error::Error>> {
Row::new(Health::Degraded, "cache", "unavailable")
.with_note("disposable: the agent runs, rediscovering what it cached")
});
if let Some(error) = &report.overlay_config_error {
agent.push(Row::new(
Health::Degraded,
"shared overlay interface",
error,
));
}
}
Observed::Stored {
why,
@@ -3398,6 +3409,8 @@ struct MemberRow<'a> {
/// that control connection reaches the peer.
transport: Option<&'a str>,
rtt_ms: Option<u64>,
data_rtt_ms: Option<u64>,
data_transport_detail: Option<&'a str>,
overlay_address_v4: Option<&'a str>,
tunnel: Option<&'a tsunagi::ipc::OverlayPeerReport>,
failed_dials: u32,
@@ -3440,6 +3453,8 @@ fn member_rows<'a>(network: &'a tsunagi::ipc::NetworkReport, own_id: &str) -> Ve
name_taken: None,
transport: None,
rtt_ms: None,
data_rtt_ms: None,
data_transport_detail: None,
overlay_address_v4: None,
tunnel: None,
failed_dials: 0,
@@ -3469,6 +3484,8 @@ fn member_rows<'a>(network: &'a tsunagi::ipc::NetworkReport, own_id: &str) -> Ve
row.path = Some(&peer.path);
row.transport = Some(&peer.transport);
row.rtt_ms = peer.rtt_ms;
row.data_rtt_ms = peer.data_rtt_ms;
row.data_transport_detail = peer.data_transport_detail.as_deref();
row.data_error = peer.data_error.as_deref();
}
if let Some(overlay) = &network.overlay {
@@ -3873,11 +3890,14 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
detail.push_str(&format!("{v4:<15} "));
}
detail.push_str(&path);
if let Some(rtt) = row.data_rtt_ms {
detail.push_str(&format!(" data RTT {rtt}ms"));
}
if let Some(transport) = row.transport {
detail.push_str(&format!(" · control path {}", transport.to_lowercase()));
}
if let Some(rtt) = row.rtt_ms {
detail.push_str(&format!(" rtt {rtt}ms"));
detail.push_str(&format!(" control RTT {rtt}ms"));
}
if row.exit_in_use {
detail.push_str(" · your exit node");
@@ -3896,6 +3916,9 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
if let Some(reason) = row.data_error {
out = out.with_note(reason.to_owned());
}
if !tunnel_up && let Some(path) = row.data_transport_detail {
out = out.with_note(path.to_owned());
}
if let Some(tunnel) = row.tunnel {
out = out.with_note(match tunnel.handshake_secs_ago {
Some(_) => format!(
@@ -3909,7 +3932,7 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
} else {
String::new()
},
tunnel.path
row.data_transport_detail.unwrap_or(&tunnel.path)
),
None => "encrypted data channel is not ready yet".into(),
});
@@ -4635,7 +4658,7 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
let tun_factory: Arc<dyn TunFactory> = if args.no_tun {
Arc::new(MemoryTunFactory::new())
} else {
system_tun_factory()?
system_tun_factory(&paths.state_dir)?
};
let mtu = args.mtu.unwrap_or(tsunagi_wg_quic::DEFAULT_MTU);
config = config.with_interface(tun_factory, args.interface.clone(), mtu);
@@ -4707,7 +4730,7 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
println!(" endpoint id {}", agent.endpoint_id());
println!(" hostname {}", agent.hostname());
println!(
" protocols {} (priority order)",
" protocols {} (initial preference order)",
protocol_names.join(", ")
);
// What this device belongs to is a separate question from whether its
@@ -4839,6 +4862,7 @@ async fn build_report(
let networks = tsunagi_runtime::report::networks(&status, overlay.as_ref(), wireguard);
StatusReport {
overlay_config_error: overlay.and_then(|state| state.address_error),
available_protocols: PROTOCOLS
.iter()
.map(|p| tsunagi::ipc::ProtocolReport {
@@ -4931,7 +4955,9 @@ async fn stop_signal() -> &'static str {
/// an open file descriptor and goes away with the agent, however the agent
/// goes away.
#[cfg(target_os = "linux")]
fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
fn system_tun_factory(
_state_dir: &std::path::Path,
) -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
use tsunagi::overlay::{ManagedTunFactory, NetlinkProvisioner};
let provisioner = NetlinkProvisioner::new()?;
let rules = Arc::new(provisioner.host_rules());
@@ -4943,7 +4969,9 @@ fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error
/// The Wintun adapter, created and configured by the agent and removed when it
/// exits, the same as the Linux one.
#[cfg(target_os = "windows")]
fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
fn system_tun_factory(
_state_dir: &std::path::Path,
) -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
use tsunagi::overlay::{ManagedTunFactory, WindowsHostRules, WintunProvisioner};
let provisioner = WintunProvisioner::new()?;
Ok(Arc::new(
@@ -4956,12 +4984,14 @@ fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error
/// exits, the same as the Linux and Windows ones. The kernel assigns the utun
/// unit, so the interface reports a `utunN` name the agent adopts.
#[cfg(target_os = "macos")]
fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
fn system_tun_factory(
state_dir: &std::path::Path,
) -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
use tsunagi::overlay::{MacosHostRules, ManagedTunFactory, UtunProvisioner};
let provisioner = UtunProvisioner::new()?;
Ok(Arc::new(
ManagedTunFactory::new(Arc::new(provisioner))
.with_host_rules(Arc::new(MacosHostRules::new())),
.with_host_rules(Arc::new(MacosHostRules::with_state_dir(state_dir))),
))
}
@@ -4970,7 +5000,9 @@ fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error
/// Refused here rather than at the first packet, and with the one thing that
/// does work on every platform named.
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
fn system_tun_factory(
_state_dir: &std::path::Path,
) -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
Err(format!(
"managing the overlay interface is not implemented on {} yet. \
Run with `--no-tun` to keep the tunnels off the operating system.",
@@ -5179,6 +5211,8 @@ mod status_tests {
hostname: Some("music".into()),
transport: "direct".into(),
rtt_ms: Some(24),
data_rtt_ms: None,
data_transport_detail: None,
exit_node: false,
path: tsunagi::ipc::DataPathReport::Direct {
transport: "wg".into(),
@@ -5709,6 +5743,20 @@ mod status_tests {
assert!(out.render(false).contains("control path relay"));
}
#[test]
fn data_and_control_latency_are_reported_separately_before_tunnel_traffic() {
let mut network = network_after_a_peer_returned();
network.overlay = None;
network.peers[0].data_rtt_ms = Some(203);
network.peers[0].data_transport_detail = Some("relay via relay.example".into());
let mut out = report::Report::new();
out.push(network_section(&network, OWN, false));
let text = out.render(false);
assert!(text.contains("data RTT 203ms"), "{text}");
assert!(text.contains("control RTT 24ms"), "{text}");
assert!(text.contains("relay via relay.example"), "{text}");
}
#[test]
fn a_tunnel_that_never_handshook_is_flagged_while_the_peer_is_connected() {
let mut network = network_after_a_peer_returned();
+3 -1
View File
@@ -55,7 +55,8 @@ if [ -n "$tray" ]; then
relations=$'conflict = tsunagi\nprovides = tsunagi\nreplaces = tsunagi\n'
# What the tray and its window load at run time; none of it is linked in
# statically, so pacman has to be told.
for dep in gtk3 libayatana-appindicator libxkbcommon wayland libx11 libglvnd; do
glibc_min=$(bash "$here/../linux/required-glibc.sh" "$tray")
for dep in "glibc>=$glibc_min" gtk3 libayatana-appindicator libxkbcommon wayland libx11 libglvnd; do
relations+="depend = ${dep}"$'\n'
done
install -D -m 0755 "$tray" "$root/usr/bin/tsunagi-tray"
@@ -77,6 +78,7 @@ builddate = $(date +%s)
packager = AB <ab@hexor.cy>
size = ${size}
arch = ${arch}
depend = shadow
${relations}license = WTFPL
PKGINFO
+8 -3
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# Assemble a dependency-free Debian package from prebuilt tsunagi binaries,
# Assemble a Debian package from prebuilt tsunagi binaries,
# using only dpkg-deb (no cargo-deb, no nfpm).
#
# Usage: build-deb.sh <binary> <deb_arch> <version> <output.deb> [tray_binary]
@@ -14,7 +14,9 @@ set -euo pipefail
binary="$1"
arch="$2"
version="$3"
# Debian treats a hyphen as a packaging revision. A tilde orders an upstream
# prerelease before the corresponding final version (1.0.3~rc1 < 1.0.3).
version=$(printf '%s' "$3" | sed 's/-/~/')
output="$4"
tray="${5:-}"
@@ -38,6 +40,7 @@ install -D -m 0644 "$here/../../README.md" "$root/usr/share/doc/tsunagi/README.m
install -D -m 0644 "$here/../linux/README.md" "$root/usr/share/doc/tsunagi/INSTALL.md"
pkgname=tsunagi
depends="adduser"
extra_control=""
desc_gui=""
if [ -n "$tray" ]; then
@@ -46,7 +49,8 @@ if [ -n "$tray" ]; then
# with it (both ship /usr/bin/tsng).
extra_control=$'Conflicts: tsunagi\nReplaces: tsunagi\nProvides: tsunagi\n'
# What the tray and its window load at run time.
extra_control+=$'Depends: libgtk-3-0 | libgtk-3-0t64, libayatana-appindicator3-1 | libappindicator3-1, libxkbcommon0, libwayland-client0, libx11-6, libgl1\n'
glibc_min=$(bash "$here/../linux/required-glibc.sh" "$tray")
depends+=", libc6 (>= $glibc_min), libgtk-3-0 | libgtk-3-0t64, libayatana-appindicator3-1 | libappindicator3-1, libxkbcommon0, libwayland-client0, libx11-6, libgl1"
desc_gui=" It also installs the tray GUI (tsunagi-tray) and a desktop launcher so it can be started from the applications menu."
install -D -m 0755 "$tray" "$root/usr/bin/tsunagi-tray"
install -D -m 0644 "$here/../linux/tsunagi-tray.desktop" \
@@ -64,6 +68,7 @@ Architecture: ${arch}
Maintainer: AB <ab@hexor.cy>
Section: net
Priority: optional
Depends: ${depends}
Homepage: https://github.com/house-of-vanity/tsunagi
${extra_control}Description: Serverless private mesh networking agent
tsunagi forms small private mesh IP networks between peers, with NAT
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# Build RC and stable packages and verify apt's upgrade order.
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
for version in 1.0.3-rc1 1.0.3-rc2 1.0.3; do
bash "$here/build-deb.sh" /usr/bin/true amd64 "$version" "$work/$version.deb"
done
version_of() { dpkg-deb -f "$work/$1.deb" Version; }
test "$(version_of 1.0.3)" = '1.0.3'
dpkg --compare-versions "$(version_of 1.0.3-rc1)" gt 1.0.2
dpkg --compare-versions "$(version_of 1.0.3-rc1)" lt "$(version_of 1.0.3-rc2)"
dpkg --compare-versions "$(version_of 1.0.3-rc2)" lt "$(version_of 1.0.3)"
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Print the highest glibc symbol version imported by the Linux tray binary.
set -euo pipefail
export LC_ALL=C
minimum=$(objdump -T "$1" |
sed -nE '/\*UND\*/s/.*GLIBC_([0-9]+(\.[0-9]+)+).*/\1/p' |
sort -V | tail -n 1)
if [[ -z "$minimum" ]]; then
echo "No versioned glibc imports found in $1" >&2
exit 1
fi
printf '%s\n' "$minimum"
+19
View File
@@ -41,6 +41,25 @@ The cask starts the service for you. The agent runs as root, and its control
socket is open to the `admin` group, so the CLI and the tray work without
`sudo` for an administrator.
After upgrading the CLI, run `sudo brew services restart tsunagi` to load the
new binary into the system daemon. Running `brew services start tsunagi` in
a user shell creates a separate launch agent. If that happened, remove the
user service with `brew services stop tsunagi`, then check the system daemon
with `sudo brew services info tsunagi`.
### Publishing Homebrew packages
After a stable `vMAJOR.MINOR.PATCH` GitHub release uploads its assets, the
`Update the Homebrew tap` job verifies the Apple Silicon archive against its
GitHub release digest and updates the `tsunagi` formula and `tsunagi-gui` cask
together on `house-of-vanity/homebrew-tap`'s `main` branch.
Set the `HOMEBREW_TAP_TOKEN` Actions secret in `house-of-vanity/tsunagi` to a
fine-grained token with **Contents: Read and write** on
`house-of-vanity/homebrew-tap`. The token must be able to push to `main`.
If publication fails, fix the reported error and rerun the Homebrew job on
the existing release workflow run.
## Native deployment — root LaunchDaemon
For an always-on agent that starts at boot, install the bundled
+3 -2
View File
@@ -120,9 +120,10 @@ carrier change. Status and the tray show the actual external transport or relay
route and data readiness. There is no user-selectable internal cipher.
The internal capability is `wireguard-e2e` v4; external `wg` and `awg` use v2,
`wg-quic` v1 and `tcp-tls` v2. All members must upgrade together. Control ALPN
`wg-quic` v1 and `tcp-tls` v2, as in 1.0.1. Control ALPN
`tsunagi/ctrl/8`, discovery, membership and signed state are unchanged. The data
ALPN is `tsunagi/data/6`; the relay envelope format is unchanged. Local IPC is v23,
ALPN is `tsunagi/data/6`; the relay envelope format is unchanged. Automatic
carrier comparisons are optional on the mesh wire. Local IPC is v24,
so agent, CLI and tray must match. Historical `wg-quic/wireguard.sqlite` is the
canonical internal key store. Missing keys are imported transactionally from
`wg` then `awg`, without replacing an existing canonical key or modifying a
+41 -21
View File
@@ -1,8 +1,8 @@
# Exit nodes
A member can offer itself as an **exit node** in a network. Other members can
then send *all* their internet traffic through it, the way a commercial VPN
or Tailscale's exit nodes work. Linux only for now.
then send their default IPv4 internet traffic through it. Linux, macOS and
Windows can offer or use an exit node. Android can use one.
## Using it
@@ -23,16 +23,20 @@ The using side:
```sh
tsng exit-node # who offers one
tsng exit-node <name|id> # send everything through it
tsng exit-node <name|id> # choose the device's internet exit
tsng exit-node -n work gateway # choose gateway in work if the name is ambiguous
tsng exit-node off
```
The tray does the same: a checkbox on the network tile to offer, and an icon on
each device in the devices window that offers one, with a confirmation.
One device has one default route, so it uses **one** exit node at a time;
choosing another replaces the first. Offering is per network, so a device can
be an exit node in one network and not in another.
An agent uses **one exit node across all active networks**. Choosing another
replaces the previous selection and survives restart. Internet packets use
the local address in the selected exit's network. Each active mesh keeps
its own subnet route, including routes to the exit peer's overlay address,
other peers and virtual services. An unused address inside an active mesh
subnet is dropped locally. Offering an exit remains a per-network choice.
## How it works
@@ -44,7 +48,8 @@ be an exit node in one network and not in another.
network stops, and when the agent exits. Only networks that offer have
rules, so the others' traffic is not forwarded.
- **Client:** policy routing, with no change to the main table. Table `29811`
holds `default dev <interface>`. Rules `5205 fwmark 0x40000000/0x40000000
holds `default dev <interface> src <local address in the exit network>` once
that address is assigned. Rules `5205 fwmark 0x40000000/0x40000000
lookup main` and `5206 uidrange <agent uid> 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
@@ -73,9 +78,9 @@ be an exit node in one network and not in another.
error if marks would be ignored. It never disables `rp_filter` or changes
host sysctls. Netfilter strict reverse checks also need their mark-aware
form, such as `rpfilter --validmark`, which NixOS already uses.
- Packets for addresses outside every overlay range are sent to the exit node
by the router; the exit node's replies are accepted from any source. A member
that is not your exit node cannot do that.
- The router sends ordinary IPv4 unicast outside all active mesh ranges to
the selected exit. It accepts replies with external source addresses from
that peer only when they target this device's address in the exit network.
- **IPv6 is blocked while you use one.** There is no IPv6 through an exit node,
and letting it go the ordinary way would leak it. The same three rules exist
for IPv6 with an `unreachable default` in the table, so applications get an
@@ -96,13 +101,20 @@ is built from `pf` and `route`. The agent runs as root there.
macOS forgets at reboot. The egress is the default route's interface **at the
time the rules are applied**; after it changes (Wi-Fi to Ethernet) switch the
offer off and on.
- **Using:** `0.0.0.0/1` and `128.0.0.0/1` routes through the overlay interface,
and a `pf` `route-to` rule that sends the agent's own traffic (matched by its
user id, root) back out the physical interface, with translation to that
interface's address. Anything else you run as root also bypasses the tunnel.
IPv6 is blocked with rejecting `::/1` and `8000::/1` routes.
- Not verified on a live host when this was written: run `tsng exit-node` and
check `sudo pfctl -a com.apple/tsunagi-exit-utunN -s rules -s nat`.
- When **using** an exit, ordinary IPv4 internet connections take the two
split-default routes through the utun, with the local address of the selected
network. More specific routes continue to reach their own networks.
- Sockets already using the physical address need matching routes scoped to
the uplink. Without them, macOS can reject a send before the packet reaches
PF. For new TCP and UDP sockets, PF sends the agent's traffic out the uplink
and preserves its source port. Replies to these tagged connections return
through loopback after reverse NAT so macOS can deliver them to a socket
whose local address belongs to the utun. This exemption matches the
daemon's user ID, so it also applies to other processes running as root.
IPv6 internet traffic is blocked with rejecting `::/1` and `8000::/1` routes.
- To inspect an active exit, run `tsng exit-node` and
`sudo pfctl -a com.apple/tsunagi-exit-utunN -vvsr`, using the daemon's utun
number. The physical interface and the utun should both see transport packets.
## Windows
@@ -117,10 +129,18 @@ is built from `pf` and `route`. The agent runs as root there.
off the tunnel *by destination*. `0.0.0.0/1` and `128.0.0.0/1` go through the
overlay interface; a `/32` route with metric 7373 (the marker for "ours")
through the physical default gateway is added for every address the agent
talks to directly: verified direct paths of its connections, plus the relays
it uses, resolved when the rules are applied. The set follows path changes. A
path that appears after the last apply goes through the tunnel until the next
one. IPv6 is blackholed with `::/1` and `8000::/1` on the overlay interface,
talks to directly, including verified connection paths and current relay
servers. Existing LAN and other more specific routes keep their next hop.
A newly authenticated connection supplies its direct paths immediately.
After a disconnect, the agent keeps its last verified paths for up to two
minutes to allow reconnection. It checks the physical gateway and relay
DNS every 30 seconds while the exit is active. Recent DNS answers remain
usable for up to two minutes after rotation or a failed lookup.
Physical bypass routes exclude every active mesh subnet. Wintun can choose
any local alias for the default route. For
TCP, UDP and ICMP echo, the agent uses the exit network's address on the
tunnel and restores replies to the address the Windows socket used.
IPv6 is blackholed with `::/1` and `8000::/1` on the overlay interface,
so applications fall back to IPv4 after a delay rather than at once.
Everything is in the active store: a reboot clears it.
- Not verified on a live host when this was written. To inspect:
+9
View File
@@ -162,6 +162,15 @@ channel is declined, which is an ordinary outcome rather than an error.
Only one side dials — the one with the smaller endpoint id — so two agents
never open two channels for the same thing.
The optional `link-choice` v1 capability lets this dialler compare a second
mutually enabled carrier. An authenticated `Transport` message named
`link-choice` contains two 16-byte identifiers from the private link-health
profiles, in keep/retire order. The responder selects the surviving carrier
and echoes the decision. The dialler keeps accepting traffic on the former
carrier until confirmation or closure. Choices apply to one peer and network
and expire with the link generations. Peers without the capability use the
original carrier negotiation.
Packets ride as QUIC **datagrams**: unreliable and unordered, which is what a
tunnelled protocol wants, and free of the head-of-line blocking a stream would
add. `max_datagram` negotiates the reassembled payload limit (at most 65536
+25 -5
View File
@@ -18,9 +18,11 @@ Each authenticated control session advertises that peer's own direct data
links. There is one table for each network, whatever protocols run over it: a
link is a way to reach a neighbour, while the single internal protocol is an
end-to-end tunnel to a peer. The envelope names the protocol, so the two are independent. A neighbour
reached over several kinds of transport (UDP, TCP, QUIC datagrams) is sent to
over the best open one, in the order the protocols were configured, and over
the next if that one fails or cannot carry the frame. Every authenticated
reached over several kinds of transport (UDP, TCP, QUIC datagrams) receives
traffic over the selected link. Another open link can carry the frame if
the selected link fails or its MTU is too small. The configured order
selects the initial link. Peers with automatic carrier selection can then
prefer a faster measured link for that neighbour. Every authenticated
member enters the graph; a member in the middle needs no protocol in common
with either end, only a link to each. A snapshot refreshes on the maintenance
interval, expires after 90 seconds, and is withdrawn when the session ends.
@@ -33,7 +35,7 @@ capability and independent of the selected external protocols. The tunnel is
created when a member and its key are known; its logical link survives temporary
loss of all physical paths. Carrier selection changes, automatic fallback and
shorter routes keep the same keys, interface and counters. The lower endpoint
id still chooses the mutually enabled external carrier in its preference order.
id chooses among the mutually enabled external carriers.
A relayed AWG first hop can lead to a QUIC next hop: the user's choice governs
this device's adjacent links, while the inner ciphertext stays unchanged.
An existing TCP connection continues after transient loss if its own timeout
@@ -100,6 +102,23 @@ Logical peer links and end-to-end encryption state survive these changes.
## Carrier health and switching
Two peers advertising `link-choice` v1 automatically compare carriers. The
lower endpoint id opens one alternative while the established carrier keeps
serving traffic. At most two comparisons start concurrently per network. Each
peer pair rotates through its alternatives, with a two-minute interval after
a trial. A failed active link still triggers immediate fallback.
The measurements use authenticated round trips over the data carrier. After
at least six seconds and five successful probes on each link, the alternative
must have zero observed loss in its window and a median RTT improvement of
at least 20% and 5 ms. If early probes are lost while the responder installs
its probe profile, the dialler keeps sampling for up to 30 seconds so those
losses can leave the 20-probe window. The incumbent stays selected if the
alternative fails to qualify. The agents coordinate retirement over their
authenticated control session. An older peer
continues using the configured order and failure recovery. One enabled carrier
restricts the pair to that carrier.
Carrier setup failures and persistent encrypted delivery loss advance the
initiator's ordered fallback cycle. Logical end-to-end links survive while
physical links are retired explicitly. The AWG carrier negotiates a fresh
@@ -127,4 +146,5 @@ end-to-end network latency or VPN throughput; encryption, fragmentation,
sockets, congestion and scheduling contribute separately.
Wire compatibility: control ALPN `tsunagi/ctrl/8`, data ALPN `tsunagi/data/6`.
Upgrade every participant together; saved identities and network state persist.
Version 1.0.2 interoperates with 1.0.1 peers using these wire versions.
Saved identities and network state persist.
+12 -2
View File
@@ -50,7 +50,8 @@ boringtun, with an in-memory TUN device so none of it needs privileges. It
covers real IPv6 packets travelling both ways through a tunnel, a three-agent
mesh, a peer that sends from an address it does not own being dropped, packets
for unowned addresses being counted rather than broadcast, a departing peer
losing its tunnel, two networks keeping separate interfaces and keys, restart
losing its tunnel, two networks exchanging traffic in both directions over one
shared interface with separate addresses and keys, restart
keeping the WireGuard identity, shutdown removing every interface, a forged
overlay claim being rejected, and the core carrying the payload without
interpreting it.
@@ -224,6 +225,12 @@ retained. It requires root, iproute2,
iptables/ip6tables and Python; it does not run in the default suite or claim
to test the entire mesh inside these namespaces.
`tsunagi-wg-quic/tests/exit_node.rs` runs a client in two disjoint meshes
with a different exit peer in each. It switches the internet route, exchanges
packets in both meshes over encrypted tunnels, races two exit selections and
restarts the client from its SQLite directory to check the winning choice.
The interfaces in this test are memory TUNs.
Devices-window tests render the egui grid at multiple widths with its real
scroll area. They check stretching and shrinking without an expanding first
column, control RTT without internal handshake/protocol clutter, unknown measurements
@@ -257,7 +264,10 @@ histories. These are headless egui checks, not native desktop screenshots.
`tsunagi-wg-quic/tests/carriers.rs` uses the same internal WireGuard plugin over
real ordinary WG UDP and TCP/TLS, with loopback address selection and memory
TUNs. Exact original IP byte/packet counts exclude health probes and encryption
overhead. The AWG suite connects AWG-only and QUIC-only endpoints through a
overhead. An artificial delay on a real TCP/TLS link exercises automatic
selection of a faster QUIC carrier. Both endpoints exchange packets across the
transition and retain their original encrypted tunnels. The AWG suite connects
AWG-only and QUIC-only endpoints through a
mixed relay. One real smoltcp TCP connection stays established through relay →
direct QUIC → a dropped packet with all local carriers off → AWG relay; both
middle TUNs and endpoint keys are checked. This exercises a real userspace TCP
+1 -1
View File
@@ -34,7 +34,7 @@ let
in
rustPlatform.buildRustPackage {
pname = if withTray then "tsunagi" else "tsunagi-cli";
version = "1.0.0";
version = "1.0.3-rc1";
src = lib.cleanSource ../.;
cargoLock.lockFile = ../Cargo.lock;
+10
View File
@@ -58,3 +58,13 @@ wire formats are unchanged. The rootless real-endpoint regression is
`crates/tsunagi-core/tests/iroh_candidates.rs`; overlay subnet filtering for
introductions is also covered in the core. This prevents the recursive path;
it does not prove the historical cause of any particular high byte counter.
## Changes to the owned overlay interface
The optional `Builder::network_change_filter` receives consecutive netwatch
snapshots before iroh rechecks paths and rebinds sockets. Tsunagi suppresses
events caused solely by its own TUN. Adding a second network can then add an
address to the shared interface while the first network keeps its UDP sockets.
Physical interface changes, default-route changes and resume events still
reach iroh. The watcher advances its baseline even for a skipped event.
Keep this behaviour when updating the vendored dependency.
+21 -1
View File
@@ -127,7 +127,7 @@ pub use crate::{net_report::NetReportConfig, portmapper::PortmapperConfig};
/// new [`EndpointId`].
///
/// To create the [`Endpoint`] call [`Builder::bind`].
#[derive(Debug)]
#[derive(derive_more::Debug)]
pub struct Builder {
secret_key: Option<SecretKey>,
alpn_protocols: Vec<Vec<u8>>,
@@ -139,6 +139,8 @@ pub struct Builder {
/// [`Builder::address_lookup`].
addr_filter: Option<AddrFilter>,
direct_addr_filter: Option<AddrFilter>,
#[debug(skip)]
network_change_filter: Option<socket::NetworkChangeFilter>,
proxy_url: Option<Url>,
ca_tls_config: Option<CaTlsConfig>,
#[cfg(not(wasm_browser))]
@@ -208,6 +210,7 @@ impl Builder {
address_lookup_user_data: Default::default(),
addr_filter: None,
direct_addr_filter: None,
network_change_filter: None,
proxy_url: None,
ca_tls_config: None,
#[cfg(not(wasm_browser))]
@@ -274,6 +277,7 @@ impl Builder {
let sock_opts = socket::Options {
direct_addr_filter: self.direct_addr_filter,
network_change_filter: self.network_change_filter,
transports: self.transports,
secret_key,
address_lookup_user_data: self.address_lookup_user_data,
@@ -636,6 +640,22 @@ impl Builder {
self
}
/// Filters OS network changes before rechecking paths and rebinding transports.
///
/// Return false only when the change cannot affect this endpoint's underlay,
/// for example when an application adds an address to its own overlay interface.
/// The next change is compared with the latest snapshot even if this one is ignored.
pub fn network_change_filter(
mut self,
filter: impl Fn(&netwatch::netmon::State, &netwatch::netmon::State) -> bool
+ Send
+ Sync
+ 'static,
) -> Self {
self.network_change_filter = Some(Box::new(filter));
self
}
/// Clears the address filter, allowing all addresses to be published.
///
/// This removes any filter previously set via [`Self::addr_filter`], including
+18 -3
View File
@@ -157,10 +157,15 @@ impl From<mpsc::error::SendError<RemoteStateMessage>> for RemoteStateActorStoppe
}
}
pub(crate) type NetworkChangeFilter =
Box<dyn Fn(&netmon::State, &netmon::State) -> bool + Send + Sync>;
/// Contains options for `Socket::listen`.
#[derive(derive_more::Debug)]
pub(crate) struct Options {
pub(crate) direct_addr_filter: Option<address_lookup::AddrFilter>,
#[debug(skip)]
pub(crate) network_change_filter: Option<NetworkChangeFilter>,
/// The configuration for the different transports.
pub(crate) transports: Vec<TransportConfig>,
@@ -883,6 +888,7 @@ impl EndpointInner {
let Options {
direct_addr_filter,
network_change_filter,
secret_key,
transports: transport_configs,
address_lookup_user_data,
@@ -1093,6 +1099,7 @@ impl EndpointInner {
periodic_re_stun_timer: new_re_stun_timer(false),
network_monitor,
local_interfaces_watcher,
network_change_filter,
direct_addr_update_state,
transports_network_change,
direct_addr_done_rx,
@@ -1475,6 +1482,7 @@ struct Actor {
network_monitor: netmon::Monitor,
/// Watcher for changes to the local network interfaces, IP addresses and routes.
local_interfaces_watcher: n0_watcher::Direct<netmon::State>,
network_change_filter: Option<NetworkChangeFilter>,
transports_network_change: transports::NetworkChangeSender,
/// Indicates the direct addr update state.
direct_addr_update_state: DirectAddrUpdateState,
@@ -1608,14 +1616,19 @@ impl Actor {
self.sock.metrics.socket.actor_tick_other.inc();
continue;
};
let is_major = state.is_major_change(&current_netmon_state);
let previous = std::mem::replace(&mut current_netmon_state, state);
if let Some(filter) = &self.network_change_filter
&& !filter(&previous, &current_netmon_state)
{
continue;
}
let is_major = current_netmon_state.is_major_change(&previous);
event!(
target: "iroh::_events::link_change",
Level::DEBUG,
?state,
state = ?current_netmon_state,
is_major
);
current_netmon_state = state;
self.sock.metrics.socket.actor_link_change.inc();
self.handle_network_change(is_major);
}
@@ -2192,6 +2205,7 @@ mod tests {
static_config,
configured_addrs: Default::default(),
direct_addr_filter: None,
network_change_filter: None,
}
}
@@ -2609,6 +2623,7 @@ mod tests {
static_config,
configured_addrs: Default::default(),
direct_addr_filter: None,
network_change_filter: None,
};
let sock = EndpointInner::bind(opts).await?;
Ok(sock)