Compare commits

..
40 Commits
Author SHA1 Message Date
Aleksandr Bogomiakov 6a0a87e76c Keep the selected exit ready and report idle tunnels in 1.0.5
Read the exit network and endpoint from the published routing choice.
Start a normal WireGuard exchange at 120 seconds for that tunnel even
when idle. BoringTun keeps the current key usable during the exchange
and owns retry and expiry. Switching or clearing the route also moves
or removes the renewal policy.

Show Idle in the tray, on Android and in CLI status after 30 seconds
without IP traffic on a previously established tunnel. Keep key changes
and keepalives out of activity, and keep waiting packets, missing paths
and transport errors visible. Preserve queued flow tags when a native
keepalive occupies a slot and drain pending IP on key confirmation.

Bump the local status IPC to 26 and update the workspace, Android and
Nix versions. Upgrade the daemon and desktop clients together. Mesh
protocols, key lifetimes and persistent storage remain compatible.

On macOS arm64 the initial workspace run passed 602 tests. A separate
181-second two-agent test observed renewal only in the selected mesh
and delivered its first internet packet after idle. Formatting and
strict workspace Clippy passed on the release sources. The maintainer
requested publication without waiting for another full test run.
2026-11-25 16:57:10 +02:00
Aleksandr Bogomiakov e3e6089d0b Adapt mesh views to phone rotation and toggle the exit from Quick Settings
Use the available width for the Android device table, keeping individual
peers expandable and their full details reachable in both orientations.
Show network selection and settings side by side in landscape and reuse
the VIP editor with a compact toolbar and width-aware backend columns.
Retain the selected network, expanded peer, traffic unit and VIP draft
across rotation.

Show data-channel readiness consistently in the tray and on Android.
Distinguish an establishing channel, a disabled data plane, an offline
peer and a transport failure. Use an animated arc for visible waiting
peers. Explain Phosphor controls on hover, focus and long press, and
provide a masked-by-default reveal button in the shared secret field.

Store the last confirmed exit network and endpoint in Android's private
preferences. A Quick Settings tap disconnects that selection or restores
the exact peer through the existing agent. First use opens the chooser.
On a cold start, wait for an authenticated exit offer outside the command
loop. Check the current selection again before changing the route. Only
changed exit offers wake roster subscribers. Wire formats, software
version and mesh identity storage remain compatible.

On macOS arm64, cargo fmt and strict workspace Clippy passed. The locked
workspace suite passed 598 tests with four opt-in tests ignored. Built the
tray, the ARM64 debug APK and its test APK. All three instrumentation tests
passed on an Android API 37 emulator. Opened the chooser from the actual
Quick Settings tile, rotated the activity and inspected rendered device
lists with ready, waiting, failed and offline peers. Physical phones and
native Linux and Windows builds were not exercised.
2026-11-25 15:38:10 +02:00
Aleksandr Bogomiakov 50c0ecea45 Reduce idle mesh traffic and Android background work for 1.0.4
A phone keeping its mesh online was paying for two data-path probe exchanges
per WG or AWG link, repeated control snapshots, and a full Android status
and DNS rebuild every two seconds while the activity was closed.

Let a timely, authenticated reply of the requested size on the physical
carrier satisfy its native delivery check. Keep the full-sized probe, RTT
window, loss thresholds, roaming, and independent silence detection. Resume
native probes when shared confirmations go stale and answer both probe
formats throughout the lifetime of the pair.

Index the latest signed objects once per network. Each reliable session
sends a full snapshot on connect and advances its cursor only when a frame
enters its send queue. Reopen the affected stream if a replica cannot
persist a received update. Send canonical peer hints in bounded batches,
publish changed edges immediately, and refresh reachability ahead of its
90-second expiry. The scheduling revisions live in memory and peers use
the existing wire formats and database schema.

Drive Android DNS and selected-exit notifications from coalesced roster
changes. The visible activity requests fresh counters, reusing the current
DNS zones. Set the workspace, Android, and Nix package versions to 1.0.4.

Formatting and strict workspace Clippy passed on macOS arm64. The locked
workspace suite passed 594 tests with four opt-in checks ignored. Both
Android instrumentation tests passed on an API 37 arm64 emulator. Tested
mixed 1.0.3/1.0.4 pairs on WG and AWG. In a 30-second idle WG comparison,
one endpoint's combined UDP bytes fell from 220950 to 138596 and its
control messages from 24 to 2. Physical phone discharge and native Linux
and Windows runs remain unverified.
2026-11-25 15:04:07 +02:00
Aleksandr Bogomiakov 8c4c2fa34e Fold network cards and show which peer carries exit traffic
Start the tray and Android overviews with each network folded under its
bold name. Keep the selected exit, its host name and its sent and received
byte totals visible. Put VIP beside Copy secret and Show devices.

Default to bytes and make the unit switch update the desktop traffic
column, totals, rates and plots together. Open the devices window at
1000 points wide and bound the network and per-peer plots. Use both sides
of the phone detail view for transport, latency, version and traffic.

Attach counters to the current network and exit peer. Count off-mesh IP
bytes after carrier acceptance and replies after local interface delivery.
Changing the selection starts new totals. Ordinary mesh traffic to the
same peer and rejected packets stay out of the exit counters.

Advertise the agent release as an optional bounded trailer on an
authenticated control v8 announcement. Older readers can ignore it and
older peers display an unknown version. Release labels live for the
session and do not participate in authentication or wire negotiation.
The new status fields require local IPC v25, so update the daemon, CLI
and tray together. Existing mesh identities and databases need no migration.

On Android, request system interface consent on the first app launch.
Respect an explicit stop or declined consent across launches. Start
Tsunagi Agent re-enables automatic startup.

Checked formatting and strict workspace Clippy on macOS arm64. The full
locked workspace suite passed 588 tests with four opt-in tests ignored.
Built the tray and Android debug APKs. Both instrumentation tests passed
on an Android 37 arm64 emulator, including app startup, stop and restart.
Checked the first-run permission prompt and the rendered phone and desktop
layouts. Native Linux and Windows tests were not run on this host.
2026-11-25 14:33:50 +02:00
Aleksandr Bogomiakov f9f67f88b1 Prepare the 1.0.3 release
Promote the confirmed release candidate to 1.0.3 across the workspace packages, internal dependency requirements, lockfile, Android app and Nix package. The change is limited to release metadata. Tests were skipped at the maintainer's request.
2026-11-25 04:22:24 +02:00
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
Aleksandr Bogomiakov 04b5ebc1a0 Added CI package publication 2026-11-24 20:47:25 +02:00
Aleksandr Bogomiakov 429fa36e3e Publish a signed Android APK with GitHub releases
Build the ARM64 app on version tags alongside the desktop builds. Stamp
the APK with the tag version and the Release workflow run number so that
updates advance and reruns keep the same code. Sign with the repository's
persistent PKCS12 key in a separate step. Only the verified APK goes into
the run artifact and the release. Require it for both creation and reruns.

Use the same NDK for Cargo and Gradle's native strip step. Check the actual
APK's package, version, release mode, ARM64 library, alignment and signature.
Keep local debug version defaults. Document the two signing secrets, key
backup and the effect of switching from the debug build on a mesh identity.

On macOS, built the debug and release APKs, signed the release with a
throwaway key, and verified its certificate. Checked rejection of missing
credentials, a wrong password, an unsigned APK, a debug APK, incorrect
versions and an unstripped native library. Exercised the release-create
and rerun paths with a local gh stand-in, including a missing artifact.
Actionlint, ShellCheck, cargo fmt, locked all-target workspace Clippy with
warnings denied, and workspace tests passed (547 passed, 2 ignored).
No live release or signing credentials were created in GitHub.
2026-11-24 17:41:44 +02:00
Aleksandr Bogomiakov ef67e1c0ae Add a Rust Android mesh client with shared tray views
Run one agent for all joined networks behind Android's VPN service. Share
transport registration and reporting with the CLI, and move the tray's
egui forms into a Rust UI crate. Phones use compact device rows and a
full-width exit picker with RTT and data path. All four transports retain
their per-network selection and priority. The phone consumes remote IPv4
exits and keeps the existing desktop identity and wire protocols.

Send discovery and transport traffic over the physical network and bind
VIP TCP health checks to the mesh. Build local DNS zones from the same
signed membership and VIP records on desktop and Android. Answer UDP and
TCP queries on the VPN, keep unknown mesh names local, and resolve public
names through Android's underlying resolver, including with an exit.

Show an ongoing notification for the selected exit. Guard its disconnect
action against a stale selection and keep mesh routing and DNS alive when
it removes the default route. Remove the app notification in mesh-only
mode. Document Android 14's unlocked-device swipe behavior.

Checked formatting and ran locked all-target workspace Clippy with
warnings denied and tests on macOS (547 passed, 2 ignored). Built the
arm64 debug APK. A physical Pixel resolved a mesh member and a Kubernetes
VIP, answered UDP and TCP DNS, and reached the API over TLS (HTTP 401
without credentials). On a separate Android emulator the notification
action removed the default route and notice while mesh DNS still worked.
2026-11-24 17:28:23 +02:00
Aleksandr Bogomiakov 9dec056349 Prepare the 1.0.0 release
Set all seven workspace package versions to 1.0.0 and align their explicit
internal dependency requirements, Cargo.lock entries and Nix package version.
The CLI, agent status and tray now report 1.0.0 rather than 0.1.0. Release
packaging derives its version from the v1.0.0 tag through the existing
workflows, which classify the tag as a stable release.

This is a software version change only. Keep protocol wire versions, identity
derivation, handshake encoding and storage schemas unchanged; no data migration
or protocol upgrade is introduced relative to the current RC. External locked
dependencies are unchanged. Each protocol crate retains its own version field.

Validation on macOS:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets: 532 passed, 2 ignored
- target/debug/tsng --version reports tsng 1.0.0
- Cargo metadata confirms all seven workspace packages are 1.0.0
- Compared Cargo.lock external package entries with HEAD: unchanged
- git diff --check

Tests ran outside the sandbox so real local test agents could open sockets.
Linux/Windows release builds, native desktop GUI and Nix builds were not run.
Commit and release tag are local; publishing is left to the user.
2026-11-16 15:03:52 +00:00
Aleksandr Bogomiakov 91227afbac Publish GitHub releases to the Arch package repository
After release assets have all uploaded, dispatch the exact repository and tag to
house-of-vanity/arch_repo using the ARCH_REPO_TOKEN Actions secret. Keep this in a
separate job so notification failures can be retried without rebuilding a release;
a missing token fails with an actionable message. Document repository setup,
installation, publication status and recovery.

Fix Arch version ordering discovered during integration: 0.1.0_rc.10 sorts above
0.1.0 in pacman. Attach prerelease suffixes directly and add epoch 1 so existing
installations can migrate and later upgrade to stable. Keep the epoch out of
filenames and align both GitHub and Gitea packaging filenames. Git tags and
application versions are unchanged. Add real packaging/vercmp checks.

Validation: Arch packaging and version-order checks passed in an Arch Linux
Docker container, including CLI and GUI packages. cargo fmt --all -- --check,
cargo clippy --locked --workspace --all-targets -- -D warnings and cargo test
--locked --workspace --all-targets passed on macOS (default ignored tests stayed
ignored). GitHub release workflow passed actionlint. Running GitHub actionlint
on the Gitea workflow only reported its deliberately retained v3 artifact actions,
which are supported by Gitea but retired on GitHub. git diff --check passed.
2026-11-16 14:40:12 +00:00
Aleksandr Bogomiakov 66206544b0 Remove the tray dependency on libxdo
The Linux tray is built on Ubuntu and reused in Debian and Arch packages.
Its default tray-icon feature pulls in libxdo through muda, tying the binary
to the builder's libxdo SONAME. Arch now supplies libxdo.so.4 while existing
release binaries can require libxdo.so.3.

Disable tray-icon default features: libxdo only supports predefined clipboard
menu actions, while our tray uses Open, Quit and a separator. Keep GTK support.
Regenerate Cargo.lock without upgrading other packages, and remove libxdo
build/runtime dependencies from both release workflows, Debian/Arch packaging
and Nix. Update the Arch installation notes.

Clarify that static Linux CLI binaries are release artifacts built for musl;
ordinary host-target Cargo builds on glibc Linux are dynamic. Document the
existing musl build command and its output path. Both release workflows still
package the musl tsng independently of the GNU tray. No protocol, persistent
state, crate version or release tag changes.

Validation on macOS:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets: 532 passed, 2 ignored
- bash -n dist/arch/build-pkg.sh dist/deb/build-deb.sh
- Linux-target Cargo dependency graph retains GTK and contains no libxdo;
  resolved metadata contains neither libxdo nor libxdo-sys
- git diff --check

Initial offline resolution lacked smoltcp and sandboxed registry access failed;
resolution succeeded with approved network access. The first sandboxed test
run failed when child agents exited before readiness; the full run outside
the sandbox passed. Linux release binaries, native GUI startup, packages and
Nix builds were not run locally; CI/release execution is left to the user.
2026-11-16 12:55:34 +00:00
Aleksandr Bogomiakov 2166ba4800 Separate internal WireGuard encryption from data carriers
AWG-only policy also selected a competing end-to-end plugin, so compatible
external links could still have no compatible encrypted data channel. Carrier
changes replaced tunnel state and status selected counters from different
engines. Use one internal WireGuard plugin and a separate DataCarrier contract
for external capabilities/lifecycle. Keep the logical link, keys, handshake,
interface and counter epoch across policy, fallback and direct/relay changes.
Control/discovery transport selection and membership remain independent.

Share the bounded per-neighbour UDP WireGuard engine between ordinary WG and
Amnezia masking. Encrypt the relay envelope inside the outer hop channel with
fresh pair keys/PSK. Remove duplicate WG key/device code and the TCP/TLS inner
cipher. TLS carries opaque internal WireGuard frames. Refuse missing native
transports instead of letting default iroh impersonate their protocol names.
Probe the actual authenticated carrier, independently of the shared IP tunnel;
failed local probe submissions count as loss too.

Apply the vendored iroh interface exclusion to actual direct candidates, not
just public discovery records. Exclude overlay subnets from introductions and
propagate the actual owned interface name, including kernel-assigned utun names,
to every carrier. Production logs showed paths through the overlay itself.
This removes a recursive transport path; it does not establish the historical
cause of the reported 100 GB absolute counter. Exit-node traffic is also real
peer IP traffic even when local applications are idle.

Hide inner cipher choices/handshake clutter in CLI and tray. Report external
routes, readiness and actionable policy/version failures. Count original IP
packets only when their ciphertext is accepted by the logical transport,
including queued packets' exact unpadded lengths. Exclude physical probes and
keepalives. Export counter epochs; sum per-peer rate deltas and discard stale
histories so joins/restarts cannot turn old totals into fresh traffic. Status
also prints exact IP byte totals for comparison with the tray.

Coordinated upgrade: data ALPN 6, internal wireguard-e2e capability v4,
wg/awg v2, QUIC carrier v1, TLS v2, local IPC v23. Control ALPN 8, device/network
identity derivation, signed records and saved network choices stay unchanged.
Keep the historical wg-quic key store; transactionally import missing keys from
wg then awg without replacing canonical keys. Forget removes legacy copies too,
on the blocking pool, to prevent resurrection after restart. Preserve historic
cipher options as shared settings, rejecting contradictory values.

Validation on Linux in the Nix development shell:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets (562 passed, 3 ignored)
The inherited service socket/secret/group environment overrides were removed
for isolated CLI process tests. A new carrier test initially raced the first
peer announcement; its deadline polling now waits for a peer row explicitly.
Real loopback endpoints, membership, SQLite, WG/AWG/TLS encryption and memory
TUNs cover mixed-carrier relaying and one smoltcp TCP connection surviving
relay/direct/policy changes and a dropped transmission. Counter tests check
exact plaintext lengths, refused sends, epochs, joins and stale histories.
Public DHT, privileged kernel and manual benchmark tests remain ignored;
macOS/Windows native TUNs, desktop GUI and WAN/DPI behavior were not run.
2026-10-22 01:07:52 +01:00
Aleksandr Bogomiakov 8a6216bccb Expose tray runtime libraries in the Nix development shell
The development shell inherited build dependencies but Cargo-built tray
binaries lack the installed package's wrapper. AppIndicator was present in
the store yet its dlopen lookup failed because the runtime library path was
missing. The same problem affected dynamically loaded graphics libraries.

Expose the package's existing trayRuntimeLibs through passthru and reuse that
list in mkShell packages and its LD_LIBRARY_PATH hook. Include the existing
NixOS OpenGL driver path and preserve any caller-supplied library paths.
The development shell and installed tray now share one dependency list.
Document direct execution of Cargo-built tray binaries inside nix develop.
No agent, protocol, package version or system configuration changes.

Validation on Linux:
- Reproduced the missing AppIndicator dlopen failure before the change.
- Loaded libayatana-appindicator3.so.1, libxkbcommon-x11.so.0, libEGL.so.1,
  libGL.so.1 and libwayland-client.so.0 inside the updated shell.
- Verified AppIndicator still loads with an inherited LD_LIBRARY_PATH and
  that the existing value is preserved. The first probe used an older host
  Python with an incompatible glibc; probes using Python from the pinned
  nixpkgs input passed.
- Evaluated the x86_64-linux CLI package and shared runtime dependency list,
  and the aarch64-linux development shell; no aarch64 execution claimed.
- nixfmt --check flake.nix nix/package.nix
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets: 566 passed, 3 ignored
Cargo checks ran through nix develop, with TSUNAGI_CONTROL_SOCKET unset for
Clippy and tests. Existing agent and tray processes were not restarted.
2026-10-21 17:05:25 +01:00
Aleksandr Bogomiakov 2e7e238459 Improve tray VIP monitoring and table layout
The VIP editor put routing and traffic observations in a dense text block,
while nested layouts in the devices grid could let text escape its row.
Separate the VIP overview from configuration and draw both live tables with
explicit cell bounds, font-aware row heights, clipping and horizontal overflow.
Measure columns before painting and keep widths stable as live values change.

The overview reuses the existing traffic sparklines for service totals and
individual listener backends, with TX/RX rates, health, RTT, open flows and
counters. Retain bounded histories by service/listener/backend identity and
release them when their resources disappear. Recreated listeners start fresh.

Use egui 0.31 Scene and Painter for a pannable, zoomable routing diagram with
Fit, clickable backend details and linked table selection. Highlight recent
counter growth separately from the backend selected for new connections;
idle bindings alone do not imply traffic, and stale activity expires. Draw
legend markers directly rather than depending on optional font glyphs.
The overview only reads saved observations; edits and deletion still require
Save. No dependencies, wire formats, IPC or persistent schemas change.

Validation on Linux through nix develop:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets: 566 passed, 3 ignored
- cargo build --locked -p tsunagi-tray
The inherited TSUNAGI_CONTROL_SOCKET was unset for Clippy and tests.
Seven new GUI tests cover enlarged fonts, mixed online/offline rows, long
names, large counters, narrow/wide layouts, scene clicks, traffic selection,
stale samples, counter resets, listener recreation and history cleanup.
The first enlarged-font regression exposed an override-font height mismatch;
row sizing now resolves the actual selected font and the regression passes.
A disposable fixture preview rendered successfully with software OpenGL on
an isolated Xvfb display. Initial Xvfb attempts needed explicit xkbcommon and
OpenGL runtime paths in the Nix environment. The preview never contacted an
agent; its temporary source was removed. macOS, Windows, Wayland and live host
TUN traffic were not exercised by this UI change.
2026-10-21 16:57:27 +01:00
Aleksandr Bogomiakov 23af1a2d9d Add shared TCP and UDP virtual services
Provide named VIPs with independent protocol/port listeners and node/port
backends so applications can use one DNS endpoint without a separate load
balancer. Every authenticated member may create, edit or delete any service.
Client agents select the eligible backend with the lowest measured encrypted
data-plane RTT, including relayed paths, and pin existing flows. UDP recovers
on another backend after failure; established TCP is never replayed or moved.
An unanswered empty TCP SYN may retry another backend before establishment.

Keep signed multi-writer field registers in state/vip.rs. Independent backend
edits merge, same-field conflicts use Lamport/author/canonical ordering, and
listener generations prevent old backend entries returning on port recreation.
Permanent service tombstones protect replay while allowing obsolete fields to
be compacted. Active-service and deletion-history limits are separate. Commit
complete snapshots and the author's durable counter atomically before local
routing changes or publication. Restore counters from newer genuine author
updates learned from replicas after an old backup is restored.

Implement bounded client-side address/port NAT at overlay ingress and reverse
translation only after authenticated source/destination admission. Reserve OS
source ports to avoid direct-flow collisions and quarantine retired ports for
late replies. Handle a backend on the client itself, scoped fragment assembly,
checksums, re-fragmentation and quoted ICMP/PMTU headers. Plugins and encrypted
transit retain their existing contracts. Data-path probes measure RTT; bounded
fair TCP connect checks are enabled by default and configurable per listener.
Arbitrary UDP application readiness remains unknown; path checks and explicit
port errors drive eligibility without protocol-specific probe payloads.

Expose the shared draft API through local IPC, simple vip/listener/backend CLI
commands, JSON, editor-based atomic updates and watch output. Add a VIP button
on each network tile and a separate tray editor. Edits and removals stay local
until Save; stale revisions retain the draft, and closing a dirty window offers
explicit discard. Report local routing choices, health reasons, RTT age, active
and draining bindings, IP counters, rates, drops and UDP failovers. Extend DNS
with service names; keep numeric addresses secondary and preserve existing
bindings while VIP addresses or listeners change.

This changes control wire ALPN/version to tsunagi/ctrl/8 and local IPC to 22;
all members and local clients must upgrade together. Data ALPN remains 5.
SQLite schema 10 migrates existing mandatory state without changing identity,
secrets, network ids, derivation labels, handshake encoding or node records.
Crate versions and release tags are unchanged. No installed agent or tray was
replaced. Commands, limits and operational semantics are in docs/vip.md.

Checks on Linux in nix develop:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets: 559 passed, 3 ignored
- git diff --cached --check

The full suite includes real encrypted TCP/UDP VIP traffic, backend-stop UDP
failover, real loopback TCP check recovery, source admission, signed merges,
stale/deleted state, SQLite migration and rollback, restart/author recovery,
network isolation, actual CLI/DNS processes, and headless text-entry/Save-button
interaction. Discovery and memory TUNs are the existing test substitutions;
authentication, transport, encryption and SQLite remain real.

Initial checks outside Nix failed for missing GTK pkg-config metadata, and an
initial CLI test inherited TSUNAGI_CONTROL_SOCKET. Final checks use the Nix
environment with that variable unset so tests address their temporary sockets.
Root/internet-dependent tests remain ignored. No live host TUN, native desktop
session, macOS or Windows validation was performed.
2026-10-21 15:40:45 +01:00
Aleksandr Bogomiakov 94318e7c16 Keep tray device metrics on one line
The device table sized handshake/RTT and packet columns from fixed samples.
Its own header exceeded the handshake sample, and six-digit counters wrapped
at the slash, making device and total rows taller and misaligning the plots.
Measure actual headers, displayed values and totals before drawing, retain
the widest values across frames, and disable wrapping inside table cells.
When a column grows, request a second egui layout pass so the grid's cached
positions settle before larger text is painted over the next column.
Keep the plot as the stretch column and horizontal scrolling for narrow
windows. This changes only tray presentation.

A headless rendering regression checks the actual text shapes for the
header, handshake age/control RTT, per-device packet counts and totals as
counts grow past five digits, reach billions, shrink again, and the table
gets a narrower container. It checks one-line text and non-overlap with the
next column; it failed on the original wrapped header. Existing resize and
long-relay tests remain in place.

Checks on Linux in nix develop:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets, with inherited
  TSUNAGI_CONTROL_SOCKET unset so tests use their temporary sockets
- git diff --cached --check

The suite's root/internet-dependent tests remain ignored. No native GUI
session or checks on macOS/Windows were run; rendering was checked through
egui's headless output. No installed tray binary was replaced.
2026-10-14 23:37:38 +01:00
Aleksandr Bogomiakov 2b0c938487 Bound iroh path retries to prevent multi-connection OOM
A long-running rc.33 daemon reached OOM with roughly 22 GiB resident and
24 GiB swapped. Live inspection found 40 GiB and 10/20 GiB anonymous
container mappings; the active worker stack and tracing metadata identified
iroh's scheduled path-open retry loop. In iroh 1.2.0 every failed connection
requeues the same path, while each retry visits every connection again.
Separate control and data connections multiply the queue geometrically.

Vendor the published iroh 1.2.0 source and select it with a workspace Cargo
patch. Deduplicate retry admission and cap distinct pending paths at 64,
evicting the oldest before inserting a new candidate. Keep the current and
next retry batches bounded without combining control/data connections or
changing wire protocols, identity derivation, authentication or state.
Document source provenance, the live evidence and removal conditions.
Upstream PR 4551 merged on October 6, but inspection of the official 1.3.0
crate still shows the unconditional enqueue, so that upgrade alone is not
a fix. No version bump, release tag or installed-service change.

The default workspace suite includes the exact vendored admission module.
Three regressions failed with the original enqueue and pass with the fix:
repeated failures across connections, duplicate admission at capacity, and
10,000 distinct candidates with bounded length/capacity and FIFO eviction.
Transport integration tests continue using real endpoints and encryption.

Checks on Linux in nix develop:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets, with only the inherited
  TSUNAGI_CONTROL_SOCKET removed from the test environment
- git diff --cached --check

Initial full-suite runs failed six DNS readiness checks because the inherited
system socket path overrode their temporary state directories. Clearing that
environment variable resolves those failures without changing application code.
Root/network-dependent ignored tests and other operating systems were not run.
2026-10-14 23:28:53 +01:00
Ultradesu 4e235cbac6 Keep device data paths on one line
The tray used a fixed sample for the data-path column, so longer relay names wrapped and made device rows uneven. Measure each rendered path and retain the widest value, then render path labels without wrapping. Replace direct/via words with embedded Phosphor route icons while preserving transport, relay name, hop count and explanatory tooltips. The app already ships the font; keep its setup in one function and verify registration alongside a long-relay-width regression test. No wire or stored-state changes. Checks: cargo fmt --all -- --check; cargo clippy --locked --workspace --all-targets -- -D warnings; cargo test --locked --workspace --all-targets.
2026-10-14 13:50:05 +01:00
Aleksandr Bogomiakov 2631eb6975 Protect Linux exit-node connections and tidy the device table
Using an exit node could destroy direct peer connections: the agent's UID
bypass protected outbound routing, but reverse-path checks look up replies
without that UID and selected the overlay default. A real-host A/B check
confirmed that relaxing only strict reverse-path filtering restored direct
connections and exit HTTP traffic; the diagnostic host changes were removed.

Keep strict filtering and protect the Linux underlay with a dedicated masked
mark bit, 0x40000000. Mark the dedicated service UID in OUTPUT, save only that
bit in conntrack and restore it before PREROUTING reverse-path checks. Install
IPv4/IPv6 mark and UID main-table bypass rules before Tailscale's priorities;
leave application-specific and exit-default routing after them. Preserve
foreign mark bits, main-table routes and foreign firewall/policy rules.

Protect the first inbound TCP/UDP packet using bounded, locally owned socket
addresses/ports from /proc and an actual socket match. Refresh socket protection
before sending private transport negotiations and on discovery ticks, without
firewall writes for an unchanged socket set. Remote announcements never become
OS arguments. A failed refresh leaves active exit routing in place. Install
protection before routes, remove routes before protection, roll back partial
activation, and remove only exact interface tags, including legacy UID rules.

Reject strict kernel rp_filter without src_valid_mark with an actionable error;
never weaken filtering or change host sysctls. Document mark-aware Netfilter
requirements and provide the trusted ip6tables path in the NixOS module.
Other platforms retain their existing exit implementation. Peer wire formats,
identity derivation, local IPC and persistent storage are unchanged.

Make the tray devices grid fill and shrink with the window, constrain the first
cell and give remaining width to traffic plots. Keep displayed end-to-end
protocol and its short encryption tooltip consistent, independent of carrier
protocol. Move handshake/session age into its own column beside the existing
iroh control RTT. Use stable per-device hover identities and concise tooltips;
missing protocols/measurements remain explicit rather than invented.

Validation on Linux through nix develop:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets: 529 passed, 3 ignored;
  inherited TSUNAGI_CONTROL_SOCKET and TSUNAGI_CONTROL_GROUP were unset
- explicit privileged kernel regression: 1 passed, using disposable namespaces,
  real TCP/UDP IPv4/IPv6, strict kernel and Netfilter RPF, first inbound packets,
  dynamic UDP binding, application exit routing/IPv6 blocking, repeated apply
  and exact cleanup with foreign Tailscale-priority rules retained
- headless egui grid/scroll-area rendering at multiple sizes and control RTT,
  mark masks/order, passive socket parsing, partial failure and cleanup tests
- git diff --check

Earlier iterations caught rtnetlink family API and nonexhaustive initializer
errors, Clippy warnings, egui's implicit minimum column width, and kernel-test
fixture issues (wildcard echo source, blocked IPv6 neighbour discovery and a
closed child stdout pipe). Corrected before final checks; the stdout-only test
fix was checked with fmt, Clippy and the explicit kernel regression afterward.
Native tray rendering and macOS/Windows checks were not run. The running host
agent was not replaced or restarted. Requested release tag: v0.1.0-rc.32.
2026-10-14 10:40:30 +01:00
Aleksandr Bogomiakov 90ef5cefec Retire offline node claims with equal network-wide cleanup rights
Offline devices reserved names and IPv4 addresses indefinitely, leaving stale
members in the device history. Give every authenticated network participant
the same right to retire another device's observed signed claim without an
owner, quorum, permanent identity ban or secret change.

Add a separately signed retirement containing the target's original signed
claim as proof. Verify both signatures and network scopes, retain the strongest
proved cutoff per target with deterministic ties, and suppress claim versions
at or below it in membership, hostname ownership and IPv4 allocation. Keep the
old signed records and range agreement, and retain markers after a newer claim
returns so old replicas cannot resurrect obsolete reservations. A returning
device signs a newer claim, allocates against current holders and resets its
previous hostname priority rather than taking a reused name with an old time.

Commit local retirement and the requester's author counter atomically before
announcing it; receivers persist proofs before applying them. Bound history to
1024 targets by default, reject additional targets without evicting protection,
and treat corrupt or over-limit mandatory storage as an explicit error. Repeat
bounded marker batches with a per-session rotating cursor so queue pressure
cannot indefinitely starve later markers. Exclude retired claims and cached
hints from history-derived discovery without preventing a fresh authenticated
device from returning.

Expose Agent::forget_node through the shared local control API. CLI command
tsng network forget-node accepts exact network names, full ids or unique id
prefixes, and exact node hostnames, ids, prefixes or overlay IPv4 addresses.
Ambiguous selections change nothing. Recheck the observed version and refuse
self, online nodes, the selected exit node and absent or changed claims.
Add Forget with an identity confirmation to offline tray device rows. Widen
Show devices to 1440x640 with an 800x400 minimum to fit its contents.

Control ALPN/version advances to tsunagi/ctrl/7 and local IPC to 21; upgrade
all peers and restart the agent with matching CLI/tray clients. Data ALPN 5,
network identity derivation, handshake encoding and existing record signing
bytes remain unchanged. SQLite schema 9 adds retirement storage while retaining
identity, secrets, settings and signed claims. Document behavior and limits.

Validation on Linux through nix develop:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets: 519 passed, 2 existing ignored
  tests; inherited TSUNAGI_CONTROL_SOCKET and TSUNAGI_CONTROL_GROUP were unset
- git diff --check and the built CLI forget-node help

Tests use real iroh authentication and SQLite. Cover restart, stale-replica
recovery, equal rights and network isolation, hostname reuse and return, twelve
marker batches through a two-message queue, malformed signatures and proofs,
invented future cutoffs, deterministic merge, capacity, migration and injected
counter-write rollback, selectors and cleanup through two real CLI processes.
Earlier iterations caught a private test API, a collapsible tray conditional
and a crash-based CLI test waiting for QUIC's idle timeout; corrected before
the final successful suite. Manual tray rendering, macOS/Windows, privileged
TUNs and public-network traversal were not run. The requested RC tag is
v0.1.0-rc.31; no push was requested.
2026-10-12 18:04:29 +01:00
Aleksandr Bogomiakov 13bdcaf98d Render protocol priority buttons with Phosphor icons
The tray protocol selection used ordinary Unicode up/down arrows for its
priority buttons. The default UI fonts lack these glyphs, so both buttons
rendered missing-glyph boxes. Use the regular Phosphor ARROW_UP and ARROW_DOWN
icons already installed in the application's proportional font fallback.

Validation on Linux through nix develop:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets, with inherited control socket
  and group overrides removed: 509 passed, 2 existing ignored tests

No new tests were added for the two glyph substitutions. Manual tray rendering
and macOS/Windows checks were not performed. No release tag was requested for
this fix.
2026-10-12 17:19:53 +01:00
Aleksandr Bogomiakov d941cdac7a Change network protocol selections at runtime
Protocol selection previously belonged to tsng up and therefore to the
service command line. A blocked or degraded carrier could only be removed
by editing the service and restarting the whole agent. Make the ordered
selection a local per-network setting instead.

Add Agent::set_protocols and a local control request shared by CLI and tray.
Keep tsng protocols without arguments as the protocol catalog; naming a
network shows its selection and supplying a comma-separated list replaces
it. Accept exact names, full ids and unique prefixes using shared selector
rules; ambiguous selectors and invalid lists change nothing. An explicit
none selects control-only operation. Offline edits take the directory lock
and apply on the next start; live edits never write behind the daemon.

Register every built-in plugin and transport in the CLI. Treat up --protocol
as ordered initial defaults for networks without an override, allowing a
protocol absent from the unit to be enabled later. Retain the targeting of
unqualified startup options and allow explicitly scoped options to configure
initially disabled protocols. Persist NULL for inherited preferences and an
empty selection distinctly in SQLite schema 8; migration preserves existing
identities, secrets, signed records and counters.

Serialize changes with network lifecycle operations and commit preferences
before applying or announcing them. Retire only the affected network's data
links and E2E channels, cancel pending opens, and reject obsolete completion
results by attempt id. Clear peer data channels when authenticated protocol
capabilities change while retaining control sessions and topology. Replay
allocations and peer identities after asynchronously prepared plugins become
ready. A control-only start defers creation of the agent's single interface
until data is enabled; plugins receive a sink that can use it later. Automatic
carrier fallback continues to preserve E2E state; explicit policy changes
renegotiate it. Identity derivation and peer wire formats are unchanged.

Add a collapsible protocols row to each tray network tile, with a catalog
provided by the daemon, descriptions, immediately applied checkboxes and
preference-order buttons. Keep editing disabled until the worker refreshes
status so a second click cannot overwrite an edit using a stale snapshot.
Local IPC wire version is 20 for the new request and report fields; upgrade
and restart agent, CLI and tray together. Crate release versions remain unchanged; the requested RC tag is v0.1.0-rc.30.

Validation on Linux through nix develop:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets: 509 passed, 2 existing ignored
  tests, with inherited TSUNAGI_CONTROL_SOCKET and TSUNAGI_CONTROL_GROUP removed

Tests use real iroh membership, SQLite, UDP, AWG and WireGuard encryption,
QUIC carriers and memory TUNs. Cover either endpoint-id role, full-size packet
delivery after switching, an unaffected second active network, saved selection
after restart, empty/invalid selections, first enablement without restart,
rapid changes racing old opens, live and offline CLI changes, startup-absent
protocols and preservation of signed state through migration. Earlier compile
and focused-test iterations caught initializer mistakes, a short test secret,
asynchronous plugin allocation readiness, and an inherited system socket
path; corrected before the successful final checks. Plain cargo was unavailable
in the host shell, so validation used the Nix toolchain. Manual tray interaction,
macOS/Windows, privileged host TUNs and public-network traversal were not run.
2026-10-12 16:19:18 +01:00
Aleksandr Bogomiakov e701986a39 Add ephemeral pairwise Amnezia transport and runtime fallback
Plain WG and QUIC can be blocked or severely degraded while the iroh control
connection still works. Add an awg carrier with one independent UDP socket,
WireGuard engine and randomized masking profile per network/peer attempt.
The smaller endpoint id negotiates fresh outer keys, PSK, header protection,
header ranges, padding and signature templates through private authenticated
control messages. Restart or fallback reentry generates a new profile;
ordinary rekeying preserves the current profile. No pair parameters enter
signed state, capabilities, persistent storage or public message events.
Private payloads and serialized control buffers redact and zeroize themselves.

Adapt the bounded packet masking engine from RunaRoo/AmneziaWG-RS at commit
51579a7d6e8882d1d8d6d00822f09e18a9423b73, retaining its Apache license and
provenance. Declare WTFPL AND Apache-2.0 in package metadata to cover both
new glue and the adapted source. Reuse boringtun instead of upstream's Node/global executors and
interface machinery. This is Tsunagi AWG wire version 1, with standard WG
headers restored before authentication; external Amnezia server compatibility
is not implemented. DNS/SIP signature generators vary fields instead of
replaying captures. Each attempt closes independently, bounds allocation,
queues, candidates and fragment assemblies, and supports the full 64 KiB
carrier contract using UDP packets at most 1200 bytes. Yield between fragment
batches so large messages do not starve local socket readers.

Keep carrier encryption separate from end-to-end tunnels so multihop relays
still forward opaque ciphertext. The system owns the sole interface, signed
addresses and admission. Plugins receive neither network secrets nor paths.
Expose a bounded opaque control sender at the transport boundary; core control
messages remain outside protocol crates. Optional STUN on the pair's actual
socket adds IPv4 public candidates in CLI direct/relay mode, with a finite
query deadline and an off/alternate-server option. Local mode remains offline.
Symmetric NAT, IPv6-only paths and arbitrary UDP blocking can still require
fallback; no AWG-over-QUIC or hidden AWG relay is introduced.

Default carrier order is wg, awg, wg-quic, tcp-tls. Advance the fallback cycle
after setup failures and sustained runtime loss, even after earlier cooldowns
expire. Authenticated delivery probes traverse the actual encrypted tunnel,
fit the interface MTU and never enter the TUN. Retire after a 20-second warmup
and at least 60% loss over at least 15 completed recent observations. Preserve
logical tunnels and control sessions while explicitly closing physical links,
including TCP reader/writer tasks. Retain the newest private probe settings
across independently queued control negotiation and inbound installation.
CLI/tray reports keep end-to-end protocol and actual carrier separate.

Control ALPN/version becomes tsunagi/ctrl/6 for the new private message;
upgrade all members together. Data ALPN/envelopes remain version 5. Network
identity derivation, transcript encoding, device identities, signed records,
saved network configuration and release versions are unchanged.

Validation on Linux through nix develop:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets, with the inherited
  TSUNAGI_CONTROL_SOCKET override removed: 504 passed, 2 pre-existing ignored

Tests use real iroh membership, SQLite, UDP sockets and WireGuard encryption
with memory TUNs. Cover three independent pairs, full-size IP and carrier
frames, restart freshness/socket release, 80% carrier datagram loss, fallback
to real iroh, fresh retries with working delivery checks, unequal small MTUs,
malformed negotiations/profiles, role and resource bounds, probe forgery and
STUN parsing. Earlier compile/lint iterations and focused tests caught RNG
API/initializer mistakes, a retry assertion racing path installation, and a
large-fragment burst overflowing loopback buffers; corrected before these
successful checks. Normalized upstream license line endings for diff checks.
Public NAT/STUN connectivity, actual DPI effectiveness, WAN performance,
per-pair memory measurement, macOS/Windows, privileged TUN operations and
manual tray interaction were not exercised.
2026-10-11 13:52:10 +01:00
Aleksandr Bogomiakov ed28e86748 Derive default network ranges and switch overlapping networks
Every first network previously proposed 10.13.37.0/24. Independently created
networks therefore collided when a device joined more than one of them.
Use the existing stable NetworkId-derived /24 in 10/8 for every new network,
independent of activation order or peer availability. Legacy and explicit
signed ranges outrank the derived default; remaining range disagreements
still use author-id ordering. The derivation, identity labels, handshake and
signed record encoding stay unchanged. There is no creator, timestamp or vote.

Reserve ranges before starting network actors and serialise start, stop and
switching through the agent lifecycle lock. Refuse equal or nested overlaps
without changing a network's subnet locally. A late authenticated range that
collides suspends only its network before updating plugins or the interface.
Coalesced watch notifications let the agent clean up outside the network actor
and reconsider suspended networks when ranges change.

An explicit switch stops every blocker before activating the chosen network.
Suspended networks retain their startup request and resume whenever their
ranges become free, including switching from a wide range to a narrow one.
A manual stop cancels that request even for an already suspended network.
Persist preference order and enabling together in an SQLite transaction so
the user's selection survives restart; no database schema migration is needed.

CLI status and network listing show blocker names, ids, ranges and the start
command. Network start switches explicitly and reports suspended networks;
joining an overlapping network reports it as configured but inactive. The
tray adds conflict details, an amber icon, Switch to this network and Keep
stopped actions. Local IPC wire version is 19 for the extended reports, so
restart the agent and tray together. Release versions and peer wire formats
are unchanged. Update the user documentation and compatibility tests.

Validation on Linux through nix develop:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets with TSUNAGI_CONTROL_SOCKET
  removed from the test environment: 486 passed, 2 pre-existing ignored tests
- final focused range_conflicts integration suite after making discovery
  fixtures deterministic: 6 passed

Earlier validation attempts caught outdated diagnostic assertions, a new
test helper scope error, and the inherited system control socket override.
Those were corrected before the successful runs. Plain cargo was unavailable
in the host shell, so validation used the Nix development toolchain. macOS,
Windows, privileged host TUN operations and manual tray interaction were not
exercised.
2026-10-11 11:58:27 +01:00
Aleksandr Bogomiakov 781e359775 Make tunnel and transport layers explicit in status
The tray called the end-to-end tunnel proto and the current route link, then put the tunnel handshake age beside the route. A valid wg tunnel over a tcp-tls transport consequently looked like contradictory state. The terminal status used similarly terse wording.\n\nThe tray now separates end-to-end from data path, renders direct paths as direct over TRANSPORT, keeps handshake or uptime beside the tunnel, and explains both layers in hover text. Terminal status uses the same end-to-end tunnel, data path, transport detail, and control path vocabulary. Routing, protocol selection, IPC, and wire behavior are unchanged.\n\nPresentation tests cover wg over tcp-tls, tcp-tls uptime, relayed and missing paths, a missing handshake, and offline devices. The WireGuard broadcast checksum test uses the current slice-array iterator spelling required by Clippy; its behavior is unchanged.\n\nChecks: cargo fmt --all -- --check; cargo clippy --locked --workspace --all-targets -- -D warnings; cargo test --locked --workspace --all-targets with TSUNAGI_CONTROL_SOCKET removed from the test environment so integration agents use their temporary control sockets. All passed on Linux.
2026-10-08 16:03:20 +01:00
Aleksandr Bogomiakov d5e02ec256 fixed gitignore 2026-10-08 15:35:38 +01:00
296 changed files with 70428 additions and 8347 deletions

No files matched your search

+3 -3
View File
@@ -127,7 +127,7 @@ jobs:
# (x86_64 only) against the runner's glibc.
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libgtk-3-dev libayatana-appindicator3-dev libxdo-dev
libgtk-3-dev libayatana-appindicator3-dev
cargo build --release --locked \
--target "${{ matrix.gnu_target }}" --bin tsunagi-tray
else
@@ -237,7 +237,7 @@ jobs:
run: |
set -euo pipefail
version="${GITHUB_REF_NAME#v}"
pkgver="${version//-/_}"
pkgver="${version//-/}"
bash dist/arch/build-pkg.sh \
"target/${{ matrix.target }}/release/tsng" \
"${{ matrix.pkg_arch }}" \
@@ -252,7 +252,7 @@ jobs:
run: |
set -euo pipefail
version="${GITHUB_REF_NAME#v}"
pkgver="${version//-/_}"
pkgver="${version//-/}"
tray="target/${{ matrix.gnu_target }}/release/tsunagi-tray"
bash dist/deb/build-deb.sh \
"target/${{ matrix.target }}/release/tsng" \
+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 }})
+269 -9
View File
@@ -1,9 +1,7 @@
name: Release
# GitHub version of the release pipeline. The build half mirrors the Gitea one
# in .gitea/workflows/release.yml (static musl Linux via cargo-zigbuild, native
# macOS and Windows); only the publish half differs: it uses the current
# artifact actions (Node 24) and fills the release with `gh`.
# Desktop builds mirror .gitea/workflows/release.yml. GitHub also builds and
# signs the Android APK and attaches all platform packages to the tag with gh.
#
# Every job is gated on `github.server_url == 'https://github.com'`, so this file
# runs only on GitHub. Gitea runs its own copy in .gitea/workflows (which pins
@@ -30,7 +28,7 @@ jobs:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
- os: ubuntu-26.04
target: x86_64-unknown-linux-musl
asset: tsunagi-linux-x86_64
archive: tar.gz
@@ -129,7 +127,7 @@ jobs:
# (x86_64 only) against the runner's glibc.
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libgtk-3-dev libayatana-appindicator3-dev libxdo-dev
libgtk-3-dev libayatana-appindicator3-dev
cargo build --release --locked \
--target "${{ matrix.gnu_target }}" --bin tsunagi-tray
else
@@ -239,7 +237,7 @@ jobs:
run: |
set -euo pipefail
version="${GITHUB_REF_NAME#v}"
pkgver="${version//-/_}"
pkgver="${version//-/}"
bash dist/arch/build-pkg.sh \
"target/${{ matrix.target }}/release/tsng" \
"${{ matrix.pkg_arch }}" \
@@ -254,7 +252,7 @@ jobs:
run: |
set -euo pipefail
version="${GITHUB_REF_NAME#v}"
pkgver="${version//-/_}"
pkgver="${version//-/}"
tray="target/${{ matrix.gnu_target }}/release/tsunagi-tray"
bash dist/deb/build-deb.sh \
"target/${{ matrix.target }}/release/tsng" \
@@ -276,9 +274,77 @@ jobs:
tsunagi-setup-*.exe
if-no-files-found: error
android:
name: Android ARM64 APK
if: ${{ github.server_url == 'https://github.com' }}
runs-on: ubuntu-24.04
permissions:
contents: read
env:
NDK_VERSION: '30.0.16248370'
BUILD_TOOLS_VERSION: '36.0.0'
steps:
- uses: actions/checkout@v5
with:
persist-credentials: false
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version: '21'
- uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-linux-android
- uses: Swatinem/rust-cache@v2
with:
key: android-arm64-${{ env.NDK_VERSION }}
- name: Install Android build tools
run: |
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \
'platforms;android-35' "build-tools;$BUILD_TOOLS_VERSION" "ndk;$NDK_VERSION"
echo "ANDROID_NDK_HOME=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV"
cargo install --locked --version 4.1.2 cargo-ndk
- name: Build the ARM64 release APK
run: |
android/gradlew -p android --no-daemon :app:assembleRelease \
"-PtsunagiVersionName=${GITHUB_REF_NAME#v}" "-PtsunagiVersionCode=$GITHUB_RUN_NUMBER"
- name: Sign the APK
id: sign
env:
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
run: |
set -euo pipefail
: "${ANDROID_KEYSTORE_BASE64:?Set the ANDROID_KEYSTORE_BASE64 Actions secret}"
: "${ANDROID_KEYSTORE_PASSWORD:?Set the ANDROID_KEYSTORE_PASSWORD Actions secret}"
umask 077
keystore=$(mktemp "$RUNNER_TEMP/tsunagi-keystore.XXXXXXXX")
trap 'rm -f "$keystore"' EXIT
printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 --decode > "$keystore"
apk="$RUNNER_TEMP/tsunagi-android-${GITHUB_REF_NAME#v}-arm64-v8a.apk"
"$ANDROID_HOME/build-tools/$BUILD_TOOLS_VERSION/apksigner" sign \
--ks "$keystore" --ks-pass env:ANDROID_KEYSTORE_PASSWORD --key-pass env:ANDROID_KEYSTORE_PASSWORD \
--v4-signing-enabled false --out "$apk" android/app/build/outputs/apk/release/app-release-unsigned.apk
echo "apk=$apk" >> "$GITHUB_OUTPUT"
- name: Test the signed APK
env:
APK: ${{ steps.sign.outputs.apk }}
run: |
bash android/test-release-apk.sh "$APK" "${GITHUB_REF_NAME#v}" "$GITHUB_RUN_NUMBER" \
"$ANDROID_HOME/build-tools/$BUILD_TOOLS_VERSION"
- uses: actions/upload-artifact@v7
with:
name: tsunagi-android
path: ${{ steps.sign.outputs.apk }}
if-no-files-found: error
publish:
name: Publish release
needs: build
needs: [build, android]
if: ${{ github.server_url == 'https://github.com' }}
runs-on: ubuntu-latest
permissions:
@@ -303,6 +369,9 @@ jobs:
# download-artifact nests each artifact under its own directory, so
# the archives are artifacts/<asset>/<file>.
mapfile -t files < <(find artifacts -type f \( -name '*.tar.gz' -o -name '*.zip' -o -name '*.deb' -o -name '*.pkg.tar.zst' -o -name 'tsunagi-setup-*.exe' \))
apk="artifacts/tsunagi-android/tsunagi-android-${TAG#v}-arm64-v8a.apk"
[[ -s "$apk" ]] || { echo "::error::Missing release APK at $apk"; exit 1; }
files+=("$apk")
printf 'asset: %s\n' "${files[@]}"
prerelease=()
@@ -320,3 +389,194 @@ jobs:
--verify-tag \
"${prerelease[@]}"
fi
notify-arch-repository:
name: Publish packages to the Arch repository
needs: publish
if: ${{ github.server_url == 'https://github.com' }}
runs-on: ubuntu-latest
permissions: {}
steps:
- name: Notify arch_repo of the completed release
shell: bash
env:
GH_TOKEN: ${{ secrets.ARCH_REPO_TOKEN }}
RELEASE_TAG: ${{ github.ref_name }}
run: |
set -euo pipefail
if [[ -z "$GH_TOKEN" ]]; then
echo '::error::Set the ARCH_REPO_TOKEN Actions secret with Contents: write access to house-of-vanity/arch_repo.'
exit 1
fi
jq -n --arg repository "$GITHUB_REPOSITORY" --arg tag "$RELEASE_TAG" \
'{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
if: github.server_url == 'https://github.com'
runs-on: ubuntu-26.04
permissions:
contents: read
id-token: write
env:
OA_SERVER: https://repo.hexor.cy
APT_SUITE: resolute
steps:
- name: Download packages attached to this release
env:
GH_TOKEN: ${{ github.token }}
run: |
gh release download "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" \
--pattern '*.deb' --pattern '*.pkg.tar.zst' --dir packages
- name: Publish packages
shell: bash
run: |
set -euo pipefail
id_token=$(curl -fsS -G --data-urlencode "audience=$OA_SERVER" \
-H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
"$ACTIONS_ID_TOKEN_REQUEST_URL" | jq -er '.value')
oa_token=$(jq -n --arg token "$id_token" \
'{token:$token,policy:"github-tsunagi-release"}' | \
curl -fsS --json @- "$OA_SERVER/api/v1/auth/oidc/exchange" | jq -er '.access_token')
echo "::add-mask::$oa_token"
auth=(-H "Authorization: Bearer $oa_token")
for file in packages/*.deb packages/*.pkg.tar.zst; do
[[ -f "$file" ]] || { echo "Missing release artifact: $file"; exit 1; }
name=${file##*/}
case "$name" in
*.deb)
arch=$(dpkg-deb -f "$file" Architecture)
status=$(curl -sS -o "$RUNNER_TEMP/oa-upload.json" -w '%{http_code}' \
"${auth[@]}" -F "file=@$file" -F "distribution=$APT_SUITE" -F component=main \
"$OA_SERVER/api/v1/repositories/hexor-apt/debs")
;;
*.pkg.tar.zst)
# 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")
;;
esac
case "$status" in
2??) echo "Published $name" ;;
409)
# An immutable version may already exist after a partial run.
digest=$(sha256sum "$file" | cut -d ' ' -f1)
if [[ "$name" == *.deb ]]; then
index="$OA_SERVER/repos/hexor-apt/dists/$APT_SUITE/main/binary-$arch/Packages"
curl -fsS "${auth[@]}" "$index" | grep -Fx "SHA256: $digest" >/dev/null || {
echo "Existing $name has different contents or is outside $APT_SUITE" >&2
exit 1
}
else
remote=$(curl -fsS "${auth[@]}" "$url" | sha256sum | cut -d ' ' -f1)
[[ "$remote" == "$digest" ]] || { echo "Different bytes for $name"; exit 1; }
fi
echo "Already published with matching SHA-256: $name"
;;
*) echo "Upload of $name returned HTTP $status" >&2; exit 1 ;;
esac
done
+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
+1
View File
@@ -1 +1,2 @@
/target
/.claude
+1 -1
View File
@@ -162,7 +162,7 @@ Keep these separate. Crossing them is the main thing to review for.
| `crates/tsunagi-core/src/overlay/` | the one interface an agent owns: provisioning, the TUN, routing, source checks, broadcast host rules |
| `crates/tsunagi-core/src/dataplane/` | the protocol contract and the authenticated packet transport |
| `crates/tsunagi-core/src/dns/` | the DNS view of a network: zone, server, resolver publication |
| `crates/tsunagi-wg-quic/` | the `wg-quic` protocol: its keys, its announcement, its tunnels |
| `crates/tsunagi-wg-quic/` | the single internal WireGuard cipher, keys and opaque announcement; historical crate name |
| `crates/tsunagi/` | the command line agent, built as `tsng`; the only place that owns a runtime, a logger and signals |
| `tests/` | integration tests; `tests/common/` is the shared harness |
Generated
+160 -52
View File
@@ -601,6 +601,12 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
@@ -1171,6 +1177,46 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "defmt"
version = "0.3.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4deef977660e373c458df605a913d4ab121db0ccd18d1ad6976dff7d37cddb53"
dependencies = [
"defmt 1.2.0",
]
[[package]]
name = "defmt"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1"
dependencies = [
"bitflags 1.3.2",
"defmt-macros",
]
[[package]]
name = "defmt-macros"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366"
dependencies = [
"defmt-parser",
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "defmt-parser"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0"
dependencies = [
"thiserror 2.0.20",
]
[[package]]
name = "der"
version = "0.8.2"
@@ -2366,6 +2412,15 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "hash32"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606"
dependencies = [
"byteorder",
]
[[package]]
name = "hashbrown"
version = "0.15.5"
@@ -2404,6 +2459,16 @@ dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "heapless"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
dependencies = [
"hash32",
"stable_deref_trait",
]
[[package]]
name = "heck"
version = "0.4.1"
@@ -2806,8 +2871,6 @@ checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
[[package]]
name = "iroh"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2f8d1cfffc83efe39a1031aab423ce09cb8048071baba550508931e9a81ce46"
dependencies = [
"backon",
"blake3",
@@ -3190,25 +3253,6 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "libxdo"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00333b8756a3d28e78def82067a377de7fa61b24909000aeaa2b446a948d14db"
dependencies = [
"libxdo-sys",
]
[[package]]
name = "libxdo-sys"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db23b9e7e2b7831bbd8aac0bbeeeb7b68cbebc162b227e7052e8e55829a09212"
dependencies = [
"libc",
"x11",
]
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
@@ -3317,6 +3361,12 @@ dependencies = [
"libc",
]
[[package]]
name = "managed"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ca88d725a0a943b096803bd34e73a4437208b6077654cc4ecb2947a5f91618d"
[[package]]
name = "matchers"
version = "0.2.0"
@@ -3422,7 +3472,6 @@ dependencies = [
"dpi",
"gtk",
"keyboard-types",
"libxdo",
"objc2 0.6.4",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
@@ -5518,6 +5567,20 @@ dependencies = [
"serde",
]
[[package]]
name = "smoltcp"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dad095989c1533c1c266d9b1e8d70a1329dd3723c3edac6d03bbd67e7bf6f4bb"
dependencies = [
"bitflags 1.3.2",
"byteorder",
"cfg-if",
"defmt 0.3.101",
"heapless",
"managed",
]
[[package]]
name = "socket2"
version = "0.6.5"
@@ -6233,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tsunagi"
version = "0.1.0"
version = "1.0.5"
dependencies = [
"anstream",
"anstyle",
@@ -6241,21 +6304,62 @@ dependencies = [
"iroh",
"netwatch",
"nix 0.31.3",
"serde_json",
"simple-dns",
"tempfile",
"tokio",
"tracing",
"tracing-subscriber",
"tsunagi-core",
"tsunagi-runtime",
"tsunagi-tcp-tls",
"tsunagi-wg-quic",
"tsunagi-wireguard",
"windows-service",
]
[[package]]
name = "tsunagi-android"
version = "1.0.5"
dependencies = [
"bytes",
"egui",
"egui-phosphor",
"egui_glow",
"iroh",
"jni 0.21.1",
"jni 0.22.4",
"rand 0.10.3",
"rustls-platform-verifier",
"simple-dns",
"smoltcp",
"tempfile",
"tokio",
"tsunagi-core",
"tsunagi-runtime",
"tsunagi-ui",
"tsunagi-wg-quic",
"zeroize",
]
[[package]]
name = "tsunagi-awg"
version = "1.0.5"
dependencies = [
"bytes",
"iroh",
"rand 0.10.3",
"smoltcp",
"tempfile",
"tokio",
"tsunagi-core",
"tsunagi-wg-quic",
"tsunagi-wireguard",
]
[[package]]
name = "tsunagi-core"
version = "0.1.0"
version = "1.0.5"
dependencies = [
"arc-swap",
"bytes",
@@ -6280,6 +6384,7 @@ dependencies = [
"serde",
"sha2",
"simple-dns",
"smoltcp",
"subtle",
"tempfile",
"thiserror 2.0.20",
@@ -6295,38 +6400,42 @@ dependencies = [
"zeroize",
]
[[package]]
name = "tsunagi-runtime"
version = "1.0.5"
dependencies = [
"tokio",
"tracing",
"tsunagi-awg",
"tsunagi-core",
"tsunagi-tcp-tls",
"tsunagi-wg-quic",
"tsunagi-wireguard",
]
[[package]]
name = "tsunagi-tcp-tls"
version = "0.1.0"
version = "1.0.5"
dependencies = [
"bytes",
"caps",
"chacha20poly1305",
"hex",
"hkdf",
"iroh",
"netdev 0.46.3",
"postcard",
"rand 0.10.3",
"rcgen",
"rustls",
"serde",
"sha2",
"subtle",
"tempfile",
"thiserror 2.0.20",
"tokio",
"tokio-rustls",
"tracing",
"tracing-subscriber",
"tsunagi-core",
"x25519-dalek",
"zeroize",
]
[[package]]
name = "tsunagi-tray"
version = "0.1.0"
version = "1.0.5"
dependencies = [
"eframe",
"egui-phosphor",
@@ -6336,12 +6445,23 @@ dependencies = [
"tracing-subscriber",
"tray-icon",
"tsunagi-core",
"tsunagi-ui",
"winit",
]
[[package]]
name = "tsunagi-ui"
version = "1.0.5"
dependencies = [
"egui",
"egui-phosphor",
"tsunagi-core",
"zeroize",
]
[[package]]
name = "tsunagi-wg-quic"
version = "0.1.0"
version = "1.0.5"
dependencies = [
"boringtun",
"bytes",
@@ -6361,26 +6481,24 @@ dependencies = [
"tracing",
"tracing-subscriber",
"tsunagi-core",
"tsunagi-tcp-tls",
"tsunagi-wireguard",
"zeroize",
]
[[package]]
name = "tsunagi-wireguard"
version = "0.1.0"
version = "1.0.5"
dependencies = [
"boringtun",
"bytes",
"data-encoding",
"hex",
"chacha20 0.9.1",
"iroh",
"netdev 0.46.3",
"postcard",
"rand 0.10.3",
"rusqlite",
"serde",
"subtle",
"tempfile",
"thiserror 2.0.20",
"tokio",
"tracing",
"tracing-subscriber",
@@ -7536,16 +7654,6 @@ dependencies = [
"web-sys",
]
[[package]]
name = "x11"
version = "2.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e"
dependencies = [
"libc",
"pkg-config",
]
[[package]]
name = "x11-dl"
version = "2.21.0"
+3 -1
View File
@@ -4,12 +4,14 @@
[workspace]
resolver = "3"
members = ["crates/*"]
exclude = ["vendor/mainline"]
exclude = ["vendor/mainline", "vendor/iroh"]
# Mainline 8.0.0 treats Windows UDP read timeouts as socket failures.
# Keep the small receive-loop correction reproducible until an upstream fix.
[patch.crates-io]
mainline = { path = "vendor/mainline" }
# Backport bounded path retries until an iroh release includes the OOM fix.
iroh = { path = "vendor/iroh" }
[workspace.package]
edition = "2024"
+104 -3
View File
@@ -55,6 +55,7 @@ with relay fallback), and keep the network state among themselves.
- **LAN games:** UDP broadcasts are relayed, so "LAN" lobbies show up across the mesh.
- **Several networks at once** on one device.
- **Tray app** for Windows, macOS and Linux; a command line for everything.
- **Android prototype** for ARM64 phones, with the same egui forms and a foreground VPN service. [Build and run the Android client](android/README.md).
## Install
@@ -63,6 +64,7 @@ Grab a build from the [latest release](https://github.com/house-of-vanity/tsunag
| Platform | How |
| --------------------- | -------------------------------------------------------------------------------- |
| **Windows** | Run `tsunagi-setup-<version>-x86_64.exe`. Installs the service, the tray and `tsng`. |
| **Android** | Open `tsunagi-android-<version>-arm64-v8a.apk` on an ARM64 phone running Android 8 or later. |
| **macOS** | `brew tap house-of-vanity/tap && brew install --cask tsunagi-gui`<br>CLI only: `brew install tsunagi` |
| **Debian / Ubuntu** | `sudo apt install ./tsunagi-gui_<version>_amd64.deb` (`tsunagi_…` for no tray) |
| **Arch** | `sudo pacman -U tsunagi-gui-<version>-1-x86_64.pkg.tar.zst` |
@@ -81,22 +83,101 @@ tsng join -n home -s tsn1… # every other machine
tsng status # who is online, over which path
```
Every member gets an address in `10.13.37.0/24` and a name like `<host>.home`.
Every new network gets a stable pseudorandom `/24` in `10.0.0.0/8`, derived
from its network id. Its members agree on that range even when starting offline,
and each gets a name like `<host>.home`. Existing signed ranges are preserved.
If two configured networks have overlapping ranges, the agent runs only one.
`tsng status`, `tsng network` and the tray show which network blocks the
other. `tsng network start <name-or-id>` or the tray’s “Switch to this network”
button suspends the conflicting networks. They resume automatically when the
selected network stops; the selection survives restarting the agent. Explicitly
stopping a suspended network cancels its automatic resume.
Machines are called `tsunagi-<id>` until you rename them: `tsng id hostname laptop`.
### Virtual services
```sh
tsng vip create home api
tsng vip port add home api tcp/443 --backend server1:6443 --backend server2:7443
tsng vip status home api --watch
```
Use `api.home:443`. Each client selects the available backend with the lowest
measured data-plane RTT. A VIP can have multiple independent TCP and UDP ports.
Every member may edit it; the tray's **VIP** button opens a draft editor with
explicit Save. [Commands, health, metrics and limits](docs/vip.md).
### Exit nodes
```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 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).
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 # 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 or on Android, click the network
name to expand its card. Open **data transports** to enable transports and set
their initial preference order. **Show devices** lists peers and their reported
Tsunagi versions. On Android, tap a device to see its version and traffic.
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.
Changing transport or moving direct → relay → direct preserves that channel,
addresses and interface. An existing TCP connection can resume after temporary
loss, subject to its own timeouts. `tsng up --protocol` supplies the
initial defaults for networks without a saved choice; it does not restrict
which built-in protocols can be enabled later.
Remove an obsolete offline device from a network's shared history:
```sh
tsng network forget-node home old-laptop
tsng network forget-node home 10.13.37.143
```
Networks accept exact names, full ids or unique id prefixes; nodes accept those
id selectors, exact hostnames or overlay IPv4 addresses. Ambiguous selectors
change nothing. Start the network first if it is stopped. In **Show devices**,
click **Forget** beside an offline node and confirm its identity.
Every member has the same cleanup right. The signed cleanup frees the observed
claim's name and IPv4 reservation, survives restarts and reaches offline replicas
when they reconnect. It does not ban the device: a newer signed claim can return.
Online nodes and the currently selected exit node cannot be forgotten.
[State and limits](docs/sync-model.md#offline-node-cleanup).
## Platforms
| Platform | Build | CLI `tsng` | Tray | Exit node: offer / use | Packages |
@@ -112,7 +193,8 @@ through it, so use only members you trust.
² Newer and less battle-tested than on Linux.
³ Builds from source, not covered by CI.</sup>
The Linux CLI is a single static binary: it runs on any distribution.
The Linux release CLI is a single static musl binary, independent of the
distribution's libc. The tray uses dynamic desktop libraries.
## NixOS
@@ -144,6 +226,11 @@ Just trying it: `nix run github:house-of-vanity/tsunagi#tsunagi-cli -- --help`.
`packages.<system>.tsunagi` (with the tray) and `tsunagi-cli` are also exported,
along with `overlays.default`.
For development from a checkout, `nix develop` also exposes the tray's native
runtime libraries, including AppIndicator and graphics/windowing libraries.
Cargo-built binaries such as `target/debug/tsunagi-tray` can run directly inside
this shell, without installing the packaged wrapper.
## Build from source
Rust 1.91 or newer.
@@ -153,6 +240,18 @@ cargo build --release --bin tsng # the agent and CLI
cargo build --release --bin tsunagi-tray # the tray (Linux needs GTK 3 and libayatana-appindicator)
```
These commands use the host target. On a glibc-based Linux distribution,
`target/release/tsng` is dynamically linked. For the static x86_64 Linux CLI,
release CI uses Zig 0.14.1 and `cargo-zigbuild` (with CMake, Clang and libclang
installed):
```sh
rustup target add x86_64-unknown-linux-musl
cargo zigbuild --release --locked --target x86_64-unknown-linux-musl --bin tsng
```
The static binary is `target/x86_64-unknown-linux-musl/release/tsng`.
Windows needs [Wintun](https://www.wintun.net) next to `tsng.exe`.
Per-platform notes: [Linux](dist/linux/README.md), [Arch](dist/arch/README.md),
[macOS](dist/macos/README.md), [Windows](dist/windows/README.md).
@@ -174,8 +273,10 @@ The [threat model](docs/threat-model.md) says what this does and doesn't protect
[Architecture](docs/architecture.md) ·
[Protocol](docs/protocol.md) ·
[WireGuard data plane](docs/wireguard.md) ·
[Pairwise Amnezia transport](docs/amnezia.md) ·
[Routing](docs/routing.md) ·
[Exit nodes](docs/exit-node.md) ·
[Virtual services](docs/vip.md) ·
[Threat model](docs/threat-model.md) ·
[Contributing](AGENTS.md)
+2
View File
@@ -0,0 +1,2 @@
gradlew text eol=lf
gradlew.bat text eol=crlf
+5
View File
@@ -0,0 +1,5 @@
.gradle/
.kotlin/
.idea/
local.properties
**/build/
+65
View File
@@ -0,0 +1,65 @@
# Android client
Download `tsunagi-android-<version>-arm64-v8a.apk` from the project's GitHub release and open it on an ARM64 phone running Android 8 or later. If prompted, allow the app that opened the file to install it. Later releases can update the installed app and preserve the mesh identity. A prototype signed with a local debug key requires a fresh install to switch to the release signer. Uninstalling the prototype removes its local identity and saved networks. [GitHub Releases](https://github.com/house-of-vanity/tsunagi/releases)
## Build from source
Open this directory in Android Studio. The debug prototype targets ARM64 devices running Android 8 or later with OpenGL ES 3. Install SDK Platform 35 and the NDK with the SDK Manager. Point `ANDROID_HOME` at your SDK and `ANDROID_NDK_HOME` at the installed NDK directory. The Gradle launcher needs a JDK, such as the one bundled with Android Studio.
From the repository root, with Cargo and cargo-ndk on your PATH:
```sh
rustup target add aarch64-linux-android
cargo install cargo-ndk --version 4.1.2 --locked
cd android
./gradlew :app:assembleDebug
adb install -r app/build/outputs/apk/debug/app-debug.apk
```
Open **tsunagi** to start the agent. On first launch, accept Android’s VPN permission prompt so the agent can create its mesh interface. Join with the existing network name and secret. The service continues when the activity closes. Mesh changes update split DNS and the selected-exit notification in the background. Opening the activity also requests live traffic counters. **About → Stop Tsunagi Agent** keeps it stopped across launches. After stopping or declining consent, tap **Start Tsunagi Agent** to enable automatic startup again. The app-private state directory holds the device identity and its saved networks.
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.
Rotate the phone to select a network on the left and see its settings on the right. **Show devices** opens a table sized to the screen. Tap a peer for its version, data path and traffic. A green check marks a ready data channel, an amber spinning arc indicates a pending connection, and a red warning opens the error details. Hold an icon for its label. Rotating the phone keeps the selected peer and any edits in the VIP editor.
Tap the network name to expand its card, then open **Exit node…** 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)
To switch the exit from the notification shade, edit Android Quick Settings and add **Tsunagi Exit**. The first tap opens the exit chooser if you have never used one. Subsequent taps disconnect the selected exit or reconnect the last peer in its original network. The tile shows the peer name and whether the selected peer is offline. Mesh access stays available when the exit is off.
## 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
The GitHub `Release` workflow builds and signs the ARM64 APK for each `v*` tag. The tag supplies the version name and the workflow run number supplies the Android version code. A rerun of the same workflow run keeps that code. The publish job attaches the verified APK alongside the desktop packages.
Before the first release, configure two repository Actions secrets. Use a dedicated single-key PKCS12 keystore with the same password for the keystore and key. Keep a private backup of the file and password so future releases can update existing installations. To create the first key, run this command once.
```sh
keytool -genkeypair -storetype PKCS12 -keystore "$HOME/tsunagi-release.p12" \
-alias tsunagi -keyalg RSA -keysize 3072 -validity 10000
```
From this repository, upload the keystore. Enter its password when the second command prompts for it.
```sh
base64 < "$HOME/tsunagi-release.p12" | gh secret set ANDROID_KEYSTORE_BASE64
gh secret set ANDROID_KEYSTORE_PASSWORD
```
Missing signing credentials or a failed APK check stop publication. After correcting the secrets, rerun the failed release jobs for the same tag.
+88
View File
@@ -0,0 +1,88 @@
import groovy.json.JsonSlurper
plugins { id 'com.android.application' version '9.2.1' }
def workspace = rootProject.projectDir.parentFile
def abi = 'arm64-v8a'
android {
namespace 'cy.hexor.tsunagi'
compileSdk 35
def cargoNdk = providers.environmentVariable('ANDROID_NDK_HOME')
if (cargoNdk.isPresent()) {
ndkPath = cargoNdk.get()
def ndkProperties = new Properties()
file("$ndkPath/source.properties").withInputStream { ndkProperties.load(it) }
ndkVersion = ndkProperties.getProperty('Pkg.Revision')
}
// Cargo also builds standalone cdylibs for these dependencies. Their code
// is linked into tsunagi_android; the JVM loads only the application library.
packaging.jniLibs.excludes += ['**/libboringtun.so', '**/libiroh.so', '**/libiroh_relay.so']
defaultConfig {
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.5')
ndk { abiFilters abi }
}
}
// rustls ships its Android trust manager as an AAR in the locked Cargo package.
def metadata = providers.exec {
workingDir workspace
commandLine 'cargo', 'metadata', '--locked', '--format-version', '1', '--filter-platform', 'aarch64-linux-android'
}.standardOutput.asText.get()
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')
metadataSources { mavenPom() }
content { includeModule 'rustls', 'rustls-platform-verifier' }
}
google()
mavenCentral()
}
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()
}
androidComponents.onVariants(androidComponents.selector().all()) { variant ->
def mode = variant.buildType
def libs = layout.buildDirectory.dir("generated/rust/${mode}")
def nativeBuild = tasks.register("cargo${mode.capitalize()}", BuildRust) {
workingDir workspace
inputs.files(fileTree(workspace) {
include 'Cargo.toml', 'Cargo.lock', '.cargo/**', 'crates/**/Cargo.toml', 'crates/**/src/**', 'vendor/**'
})
jniLibs.set(libs)
commandLine 'cargo', 'ndk', '--target', abi, '--platform', '26', '-o', libs.get().asFile,
'build', '--locked', '--lib', '-p', 'tsunagi-android'
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,51 @@
package cy.hexor.tsunagi
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.net.VpnService
import android.os.SystemClock
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Test
class AgentStartupTest {
@Suppress("DEPRECATION")
@Test fun launchStartsAgentAndExplicitStopSurvivesReopening() {
val test = InstrumentationRegistry.getInstrumentation()
val context = test.targetContext
check(VpnService.prepare(context) == null) { "Grant VPN consent on the test emulator first" }
val manager = context.getSystemService(ActivityManager::class.java)
fun running() = manager.getRunningServices(Int.MAX_VALUE).any {
it.service.className == MeshVpn::class.java.name && it.started
}
fun awaitRunning(expected: Boolean) {
val deadline = SystemClock.elapsedRealtime() + 5000
while (running() != expected) {
check(SystemClock.elapsedRealtime() < deadline) { "Agent did not reach started=$expected" }
SystemClock.sleep(25)
}
}
fun launch() = test.startActivitySync(Intent(context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) as MainActivity
val settings = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
val old = settings.getBoolean("auto_start", true)
var activity: MainActivity? = null
try {
settings.edit().remove("auto_start").commit()
activity = launch()
awaitRunning(true)
test.runOnMainSync { activity!!.stopAgent(); activity!!.finish() }
awaitRunning(false)
activity = launch()
test.waitForIdleSync()
check(!running())
test.runOnMainSync { activity!!.requestAgent() }
awaitRunning(true)
} finally {
test.runOnMainSync { activity?.stopAgent(); activity?.finish() }
awaitRunning(false)
settings.edit().putBoolean("auto_start", old).commit()
}
}
}
@@ -0,0 +1,33 @@
package cy.hexor.tsunagi
import android.content.ComponentName
import android.content.Context
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Test
class ExitTileTest {
@Test fun tileKeepsTheExactLastSelectionOnlyAfterTheAgentConfirmsIt() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val info = context.packageManager.getServiceInfo(ComponentName(context, ExitTile::class.java), 0)
check(info.permission == "android.permission.BIND_QUICK_SETTINGS_TILE")
check(!context.packageManager.getActivityInfo(ExitTile.entry(context), 0).exported)
check(Native.tileExit(0, "network", "peer", true, false) == "Tsunagi Agent stopped")
val isolated = context.createDeviceProtectedStorageContext()
val settings = isolated.getSharedPreferences("exit_tile", Context.MODE_PRIVATE)
settings.edit().clear().commit()
val first = ExitTile.Target("network-a", "peer", "Gateway")
val last = ExitTile.Target("network-b", "peer", "Gateway")
try {
check(ExitTile.last(isolated) == null)
ExitTile.publish(isolated, 1L, first, true)
ExitTile.publish(isolated, 1L, last, true)
ExitTile.publish(isolated, 1L, null, false)
check(ExitTile.last(isolated) == last)
ExitTile.reset(isolated)
check(ExitTile.last(isolated) == last)
} finally {
ExitTile.reset(isolated)
settings.edit().clear().commit()
}
}
}
@@ -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) }
}
}
}
+33
View File
@@ -0,0 +1,33 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
<uses-feature android:glEsVersion="0x00030000" android:required="true" />
<application android:label="tsunagi" android:icon="@drawable/tsunagi"
android:enableOnBackInvokedCallback="false" android:allowBackup="false" android:theme="@android:style/Theme.Material.NoActionBar">
<activity android:name=".MainActivity" android:exported="true"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity-alias android:name=".OpenExit" android:targetActivity=".MainActivity" android:exported="false" />
<service android:name=".MeshVpn" android:permission="android.permission.BIND_VPN_SERVICE"
android:foregroundServiceType="systemExempted" android:exported="false">
<intent-filter><action android:name="android.net.VpnService" /></intent-filter>
<meta-data android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON" android:value="false" />
</service>
<service android:name=".ExitTile" android:exported="true"
android:label="Tsunagi Exit" android:icon="@drawable/exit_tile"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
<intent-filter><action android:name="android.service.quicksettings.action.QS_TILE" /></intent-filter>
<meta-data android:name="android.service.quicksettings.ACTIVE_TILE" android:value="true" />
<meta-data android:name="android.service.quicksettings.TOGGLEABLE_TILE" android:value="true" />
</service>
</application>
</manifest>
@@ -0,0 +1,113 @@
package cy.hexor.tsunagi
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import android.widget.Toast
/** Quick Settings changes the internet exit of the existing mesh agent. */
class ExitTile : TileService() {
internal data class Target(val network: String, val peer: String, val name: String)
private data class Snapshot(val session: Long, val active: Target?, val online: Boolean)
companion object {
internal fun entry(context: Context) = ComponentName(context, "${context.packageName}.OpenExit")
private var live = Snapshot(0, null, false)
private var pending = false
private val main = Handler(Looper.getMainLooper())
internal fun last(context: Context): Target? {
val prefs = context.getSharedPreferences("exit_tile", Context.MODE_PRIVATE)
val network = prefs.getString("network", null) ?: return null
val peer = prefs.getString("peer", null) ?: return null
return Target(network, peer, prefs.getString("name", null) ?: peer.take(12))
}
private fun refresh(context: Context) {
requestListeningState(context, ComponentName(context, ExitTile::class.java))
}
internal fun publish(context: Context, session: Long, active: Target?, online: Boolean) {
// Only confirmed agent status updates the last selection. Clearing an exit or
// stopping the process leaves the exact network and peer available for reuse.
if (active != null && last(context) != active) {
context.getSharedPreferences("exit_tile", Context.MODE_PRIVATE).edit()
.putString("network", active.network).putString("peer", active.peer)
.putString("name", active.name).apply()
}
live = Snapshot(session, active, online)
refresh(context)
}
internal fun reset(context: Context) {
live = Snapshot(0, null, false)
refresh(context)
}
internal fun restoreIfReady(context: Context, target: Target): Boolean {
if (live.session == 0L) return false
if (live.active == null) change(context, live.session, target, true, waitForDiscovery = true)
return true
}
private fun change(context: Context, session: Long, target: Target, connect: Boolean, waitForDiscovery: Boolean = false) {
if (pending) return
pending = true
refresh(context)
val app = context.applicationContext
Thread({
val error = Native.tileExit(session, target.network, target.peer, connect, waitForDiscovery)
main.post {
pending = false
if (error != null) Toast.makeText(app, error, Toast.LENGTH_LONG).show()
refresh(app)
}
}, "tsunagi-exit-tile").start()
}
}
private var displayed = live
private var remembered: Target? = null
override fun onStartListening() {
super.onStartListening()
displayed = live
remembered = last(this)
val tile = qsTile ?: return
val active = displayed.active
val peer = active ?: remembered
val subtitle = when {
pending -> "Updating…"
active != null && !displayed.online -> "${active.name} · offline"
peer != null -> peer.name
else -> "Choose exit node"
}
tile.state = when {
pending -> Tile.STATE_UNAVAILABLE
active != null -> Tile.STATE_ACTIVE
else -> Tile.STATE_INACTIVE
}
tile.label = if (Build.VERSION.SDK_INT < 29 && peer != null) "Exit · ${peer.name}" else "Tsunagi Exit"
if (Build.VERSION.SDK_INT >= 29) tile.subtitle = subtitle
tile.contentDescription = "Tsunagi exit node, $subtitle"
tile.updateTile()
}
@Suppress("DEPRECATION")
override fun onClick() {
super.onClick()
if (pending || displayed != live) { onStartListening(); return }
val target = displayed.active ?: remembered
if (displayed.session != 0L && target != null) {
change(this, displayed.session, target, displayed.active == null)
return
}
// Consent, a stopped service, or the first selection needs an activity.
val open = Intent().setComponent(entry(this))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
if (Build.VERSION.SDK_INT >= 34) {
startActivityAndCollapse(PendingIntent.getActivity(this, 2, open, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT))
} else startActivityAndCollapse(open)
}
}
@@ -0,0 +1,101 @@
package cy.hexor.tsunagi
import android.app.Activity
import android.content.Intent
import android.net.VpnService
import android.os.Build
import android.os.Bundle
import android.view.WindowInsets
import android.widget.FrameLayout
class MainActivity : Activity() {
private val settings by lazy { getSharedPreferences("agent", MODE_PRIVATE) }
private var checkedAutoStart = false
private var consentPending = false
private var tileRequested = false
private var askedForNotifications = false
internal fun requestExitNotifications() {
if (Build.VERSION.SDK_INT >= 33 && !askedForNotifications &&
checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
askedForNotifications = true
requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), 2)
}
}
private lateinit var surface: MeshSurface
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
consentPending = savedInstanceState?.getBoolean("consent_pending") == true
tileRequested = savedInstanceState?.getBoolean("exit_tile") ?: (intent.component == ExitTile.entry(this))
surface = MeshSurface(this)
val root = FrameLayout(this)
if (Build.VERSION.SDK_INT >= 30) {
window.setDecorFitsSystemWindows(false)
root.setOnApplyWindowInsetsListener { view, insets ->
val area = insets.getInsets(WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout() or WindowInsets.Type.ime())
view.setPadding(area.left, area.top, area.right, area.bottom)
insets
}
} else root.fitsSystemWindows = true
root.addView(surface)
setContentView(root)
}
override fun onPostResume() {
super.onPostResume()
if (tileRequested && !consentPending) {
checkedAutoStart = true
requestAgent()
return
}
if (checkedAutoStart) return
checkedAutoStart = true
if (!MeshVpn.started && settings.getBoolean("auto_start", true)) requestAgent()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean("consent_pending", consentPending)
outState.putBoolean("exit_tile", tileRequested)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
if (intent.component == ExitTile.entry(this)) tileRequested = true
}
internal fun requestAgent() {
if (consentPending) return
val consent = VpnService.prepare(this)
if (consent == null) startAgent() else {
consentPending = true
startActivityForResult(consent, 1)
}
}
private fun startAgent() {
settings.edit().putBoolean("auto_start", true).apply()
val service = Intent(this, MeshVpn::class.java)
if (tileRequested) {
tileRequested = false
if (ExitTile.last(this) != null) service.action = MeshVpn.RESTORE_EXIT
else surface.openExitPicker()
}
// A retry of an existing service may already have left foreground mode.
if (MeshVpn.started) startService(service) else startForegroundService(service)
}
internal fun stopAgent() {
settings.edit().putBoolean("auto_start", false).apply()
startService(Intent(this, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN))
}
@Deprecated("Platform consent result")
override fun onActivityResult(request: Int, result: Int, data: Intent?) {
super.onActivityResult(request, result, data)
if (request == 1) {
consentPending = false
if (result == RESULT_OK) startAgent() else {
tileRequested = false
settings.edit().putBoolean("auto_start", false).apply()
surface.input(5, "Android VPN permission was declined")
}
}
}
@Deprecated("Forward system Back to the current Rust view")
override fun onBackPressed() { surface.dispatchBack() }
override fun onResume() { super.onResume(); surface.onResume() }
override fun onPause() { surface.onPause(); super.onPause() }
}
@@ -0,0 +1,151 @@
package cy.hexor.tsunagi
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.opengl.GLSurfaceView
import android.text.InputType
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.inputmethod.BaseInputConnection
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputMethodManager
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
/** Surface, input connection and clipboard bridge for egui. */
class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity), GLSurfaceView.Renderer {
private val density get() = resources.displayMetrics.density
private val imm = activity.getSystemService(InputMethodManager::class.java)
private var imeMode = 0
private var widthPx = 0
private var heightPx = 0
private val repaint = Runnable { requestRender() }
private val pickExit = java.util.concurrent.atomic.AtomicBoolean()
fun openExitPicker() { pickExit.set(true); requestRender() }
init {
setEGLContextClientVersion(3)
preserveEGLContextOnPause = true
setRenderer(this)
renderMode = RENDERMODE_WHEN_DIRTY
isFocusableInTouchMode = true
requestFocus()
}
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface()
override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h }
override fun onDrawFrame(gl: GL10?) {
if (pickExit.getAndSet(false)) Native.input(6, "")
val landscape = resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE
val delay = Native.draw(this, widthPx, heightPx, density, MeshVpn.started, landscape)
removeCallbacks(repaint)
postDelayed(repaint, delay.coerceAtLeast(16))
}
override fun onPause() { super.onPause(); removeCallbacks(repaint) }
override fun onTouchEvent(e: MotionEvent): Boolean {
val phase = when (e.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> 0
MotionEvent.ACTION_MOVE -> 1
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> 2
MotionEvent.ACTION_CANCEL -> 3
else -> return false
}
for (i in 0 until e.pointerCount) {
if ((phase == 0 || phase == 2) && i != e.actionIndex) continue
val id = e.getPointerId(i)
val x = e.getX(i) / density
val y = e.getY(i) / density
queueEvent { Native.touch(phase, id, x, y) }
}
requestRender()
return true
}
fun startAgent() { post { activity.requestAgent() } }
fun stopAgent() { post { activity.stopAgent() } }
fun requestExitNotifications() { post { activity.requestExitNotifications() } }
fun closeScreen() { post { activity.finish() } }
fun openUrl(url: String) { post {
val uri = android.net.Uri.parse(url)
if (uri.scheme == "https") {
try { activity.startActivity(Intent(Intent.ACTION_VIEW, uri)) }
catch (_: android.content.ActivityNotFoundException) { }
}
} }
fun dispatchBack() { queueEvent { Native.back(this) }; requestRender() }
fun copyText(value: String) { post {
activity.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("tsunagi", value))
} }
fun copySecret(value: String) { post {
val clip = ClipData.newPlainText("tsunagi", value)
clip.description.extras = android.os.PersistableBundle().apply { putBoolean("android.content.extra.IS_SENSITIVE", true) }
activity.getSystemService(ClipboardManager::class.java).setPrimaryClip(clip)
} }
fun pasteSecret() { post {
val clip = activity.getSystemService(ClipboardManager::class.java).primaryClip
val text = clip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text
if (text != null && text.length <= 2048) input(4, text.toString())
} }
fun keyboard(mode: Int) { post {
imeMode = mode
if (mode == 0) {
imm.hideSoftInputFromWindow(windowToken, 0)
imm.restartInput(this)
}
else {
requestFocus()
imm.restartInput(this)
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
} }
fun input(kind: Int, value: String) {
queueEvent { Native.input(kind, value) }
requestRender()
}
private fun key(code: Int) { queueEvent { Native.key(code) }; requestRender() }
override fun onCheckIsTextEditor(): Boolean = imeMode != 0
override fun onCreateInputConnection(info: EditorInfo): InputConnection? {
if (imeMode == 0) return null
info.inputType = InputType.TYPE_CLASS_TEXT or (if (imeMode == 2) InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS)
info.imeOptions = EditorInfo.IME_ACTION_DONE or EditorInfo.IME_FLAG_NO_EXTRACT_UI or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
return object : BaseInputConnection(this, false) {
private var composing: String? = null
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean {
if (composing == null) input(1, "")
composing = text?.toString().orEmpty()
input(2, composing.orEmpty())
return true
}
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
input(if (composing == null) 0 else 3, text?.toString().orEmpty())
composing = null
return true
}
override fun finishComposingText(): Boolean {
composing?.let { input(3, it) }
composing = null
return true
}
override fun deleteSurroundingText(before: Int, after: Int): Boolean {
repeat(before.coerceIn(0, 2048)) { key(KeyEvent.KEYCODE_DEL) }
repeat(after.coerceIn(0, 2048)) { key(KeyEvent.KEYCODE_FORWARD_DEL) }
return true
}
override fun sendKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event)
override fun performEditorAction(action: Int): Boolean { key(KeyEvent.KEYCODE_ENTER); return true }
}
}
override fun onKeyDown(code: Int, event: KeyEvent): Boolean {
when (code) {
KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_TAB, KeyEvent.KEYCODE_DEL,
KeyEvent.KEYCODE_FORWARD_DEL, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> key(code)
else -> {
val point = event.unicodeChar
if (point <= 0) return super.onKeyDown(code, event)
input(0, String(Character.toChars(point)))
}
}
return true
}
}
@@ -0,0 +1,214 @@
package cy.hexor.tsunagi
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.net.ConnectivityManager
import android.net.DnsResolver
import android.net.Network
import android.net.LinkProperties
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.VpnService
import android.os.Handler
import android.os.Build
import android.os.CancellationSignal
import android.os.Looper
import android.os.ParcelFileDescriptor
import android.system.OsConstants
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
class MeshVpn : VpnService() {
companion object {
const val STOP_VPN = "cy.hexor.tsunagi.STOP_VPN"
const val RESTORE_EXIT = "cy.hexor.tsunagi.RESTORE_EXIT"
private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT"
private const val NOTIFICATION_ID = 1
private const val EXIT_CHANNEL = "exit-node"
@Volatile var started = false
private set
}
private val main = Handler(Looper.getMainLooper())
private val notifications by lazy { getSystemService(NotificationManager::class.java) }
@Volatile private var instance = 0L
private var closed = false
private var restore: ExitTile.Target? = null
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
@Volatile private var upstream: Network? = null
private val changes = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) = useUnderlay(network)
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
if (network == upstream && !closed) updateAddresses(properties)
}
override fun onLost(network: Network) {
if (network != upstream || closed) return
upstream = null
// Keep the binding to the lost network until its replacement is ready.
// Falling back to the default network here could send iroh into its own TUN.
setUnderlyingNetworks(emptyArray())
physicalAddresses = ""
Native.networkChanged(instance, "")
}
}
private var physicalAddresses = ""
private fun addresses(properties: LinkProperties?) = properties?.linkAddresses.orEmpty()
.mapNotNull { it.address.hostAddress?.substringBefore('%') }.distinct().take(32).joinToString(",")
private fun updateAddresses(properties: LinkProperties) {
val next = addresses(properties)
if (next == physicalAddresses) return
physicalAddresses = next
Native.networkChanged(instance, next)
}
@Synchronized private fun useUnderlay(network: Network) {
if (closed || !connectivity.bindProcessToNetwork(network)) return
upstream = network
setUnderlyingNetworks(arrayOf(network))
physicalAddresses = addresses(connectivity.getLinkProperties(network))
if (instance == 0L) {
Native.trust(applicationContext)
instance = Native.start(this, applicationContext, noBackupFilesDir.absolutePath, cacheDir.absolutePath, physicalAddresses)
} else Native.networkChanged(instance, physicalAddresses)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
STOP_VPN -> { shutdown(); stopSelf(startId); return START_NOT_STICKY }
RESTORE_EXIT -> {
restore = ExitTile.last(this)
restore?.let { if (ExitTile.restoreIfReady(this, it)) restore = null }
}
DISCONNECT_EXIT -> {
val ids = intent.data?.pathSegments.orEmpty()
if (started && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) {
if (!Native.disconnectExit(instance, ids[0], ids[1])) {
android.widget.Toast.makeText(this, "Exit node is busy. Try again.", android.widget.Toast.LENGTH_SHORT).show()
}
} else if (!started) stopSelf(startId)
return START_NOT_STICKY
}
}
if (started) {
if (Native.failed(instance)) {
Native.stop(instance)
instance = 0
upstream?.let(::useUnderlay)
}
return START_NOT_STICKY
}
closed = false
notifications.createNotificationChannel(NotificationChannel("vpn", "Tsunagi Agent", NotificationManager.IMPORTANCE_LOW))
notifications.createNotificationChannel(NotificationChannel(EXIT_CHANNEL, "Exit node", NotificationManager.IMPORTANCE_LOW))
val startup = notification("vpn").setContentTitle("Starting Tsunagi Agent")
if (Build.VERSION.SDK_INT >= 31) startup.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_DEFERRED)
startForeground(NOTIFICATION_ID, startup.build())
started = true
connectivity.requestNetwork(NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(), changes, Handler(Looper.getMainLooper()))
return START_NOT_STICKY
}
private fun notification(channel: String): Notification.Builder {
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return Notification.Builder(this, channel).setSmallIcon(R.drawable.tsunagi)
.setContentIntent(open).setOngoing(true).setOnlyAlertOnce(true).setShowWhen(false)
.setCategory(Notification.CATEGORY_SERVICE)
}
// Rust publishes a change even when the activity is closed. Android holds its
// own service binding for an established TUN, so mesh-only mode can leave
// foreground promotion and remove the app's notification.
fun updateExitNotification(session: Long, network: String, peer: String, title: String, text: String, name: String, online: Boolean) {
main.post {
if (closed || session != instance) return@post
val selected = if (peer.isEmpty()) null else ExitTile.Target(network, peer, name)
ExitTile.publish(this, session, selected, online)
restore?.let { if (ExitTile.restoreIfReady(this, it)) restore = null }
if (peer.isEmpty()) {
stopForeground(STOP_FOREGROUND_REMOVE)
return@post
}
val target = android.net.Uri.Builder().scheme("tsunagi").authority("exit")
.appendPath(network).appendPath(peer).build()
val disconnect = PendingIntent.getService(this, 1,
Intent(this, MeshVpn::class.java).setAction(DISCONNECT_EXIT).setData(target).putExtra("instance", session),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val notice = notification(EXIT_CHANNEL).setContentTitle(title).setContentText(text)
.addAction(Notification.Action.Builder(null, "Disconnect exit node", disconnect).build())
if (Build.VERSION.SDK_INT >= 31) notice.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)
startForeground(NOTIFICATION_ID, notice.build())
}
}
// Called from Rust with the exhaustive local plan; detachFd transfers ownership.
@Synchronized fun establishTun(addresses: String, routes: String, dns: String, mtu: Int, fullTunnel: Boolean): Int {
if (closed) return -1
val builder = Builder().setSession("tsunagi").setMtu(mtu).setBlocking(false)
builder.setUnderlyingNetworks(upstream?.let { arrayOf(it) } ?: emptyArray())
addresses.split(',').forEach { builder.addAddress(it.substringBefore('/'), it.substringAfter('/').toInt()) }
routes.split(',').forEach { builder.addRoute(it.substringBefore('/'), it.substringAfter('/').toInt()) }
if (dns.isNotEmpty()) builder.addDnsServer(dns)
// Mesh exits currently carry IPv4. Android blocks an unconfigured family
// unless explicitly allowed. In split mode ordinary IPv6 should pass.
if (!fullTunnel) builder.allowFamily(OsConstants.AF_INET6)
return builder.establish()?.detachFd() ?: -1
}
// Called on a bounded Rust blocking worker, never on the UI or TUN reader.
@android.annotation.TargetApi(29)
fun resolveDns(query: ByteArray): ByteArray? {
val network = upstream ?: return null
val result = CompletableFuture<ByteArray>()
val cancel = CancellationSignal()
return try {
DnsResolver.getInstance().rawQuery(network, query, DnsResolver.FLAG_EMPTY, { it.run() }, cancel,
object : DnsResolver.Callback<ByteArray> {
override fun onAnswer(answer: ByteArray, rcode: Int) { result.complete(answer) }
override fun onError(error: DnsResolver.DnsException) { result.completeExceptionally(error) }
})
result.get(4, TimeUnit.SECONDS)
} catch (_: Exception) { null } finally { cancel.cancel() }
}
// Android 8 and 9 expose only address lookups through their system resolver.
fun resolveAddresses(host: String): String? = try {
upstream?.getAllByName(host)?.mapNotNull { it.hostAddress }?.joinToString(",")
} catch (_: java.net.UnknownHostException) { null }
// The endpoint uses the physical network. This one explicitly selected TCP
// socket must instead follow the same VPN as applications using the VIP.
@Suppress("DEPRECATION")
fun bindOverlaySocket(fd: Int, source: String): Boolean {
val vpn = connectivity.allNetworks.firstOrNull { network ->
connectivity.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true &&
connectivity.getLinkProperties(network)?.linkAddresses?.any { it.address.hostAddress == source } == true
} ?: return false
return try {
ParcelFileDescriptor.fromFd(fd).use { vpn.bindSocket(it.fileDescriptor) }
true
} catch (_: java.io.IOException) { false }
}
override fun onRevoke() { shutdown(); stopSelf() }
override fun onDestroy() { shutdown(); super.onDestroy() }
@Synchronized private fun shutdown() {
if (closed) return
closed = true
restore = null
ExitTile.reset(this)
if (started) connectivity.unregisterNetworkCallback(changes)
started = false
if (instance != 0L) Native.stop(instance)
instance = 0L
upstream = null
physicalAddresses = ""
connectivity.bindProcessToNetwork(null)
stopForeground(STOP_FOREGROUND_REMOVE)
}
}
@@ -0,0 +1,22 @@
package cy.hexor.tsunagi
import android.content.Context
/** OS entry points. Network commands and all views live in the Rust library. */
internal object Native {
init { System.loadLibrary("tsunagi_android") }
external fun trust(context: Context)
external fun start(service: MeshVpn, context: Context, state: String, cache: String, addresses: String): Long
external fun failed(instance: Long): Boolean
external fun stop(instance: Long)
external fun disconnectExit(instance: Long, network: String, peer: String): Boolean
external fun tileExit(instance: Long, network: String, peer: String, connect: Boolean, waitForDiscovery: Boolean): String?
external fun networkChanged(instance: Long, addresses: String)
external fun surface()
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float, serviceStarted: Boolean, landscape: Boolean): Long
external fun touch(action: Int, id: Int, x: Float, y: Float)
external fun input(kind: Int, value: String)
external fun key(key: Int)
external fun back(host: MeshSurface)
}
@@ -0,0 +1,6 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
<path android:strokeColor="#ffffff" android:strokeWidth="2"
android:strokeLineCap="round" android:strokeLineJoin="round"
android:pathData="M12,3H4v18h8 M9,12h12 M17,8l4,4l-4,4" />
</vector>
@@ -0,0 +1,6 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp" android:height="48dp" android:viewportWidth="128" android:viewportHeight="128">
<path android:fillColor="#2f80d8" android:pathData="M64,8a56,56 0,1 1,0 112a56,56 0,1 1,0 -112" />
<path android:strokeColor="#ffffff" android:strokeWidth="7" android:pathData="M64,34a30,30 0,1 1,0 60a30,30 0,1 1,0 -60" />
<path android:fillColor="#ffffff" android:pathData="M64,55a9,9 0,1 1,0 18a9,9 0,1 1,0 -18" />
</vector>
+2
View File
@@ -0,0 +1,2 @@
android.useAndroidX=true
org.gradle.jvmargs=-Xmx1536m -Dfile.encoding=UTF-8
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+93
View File
@@ -0,0 +1,93 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+3
View File
@@ -0,0 +1,3 @@
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
rootProject.name = 'tsunagi-android'
include ':app'
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env bash
set -euo pipefail
apk=${1:?expected an APK}
version_name=${2:?expected the release version}
version_code=${3:?expected the Android version code}
build_tools=${4:?expected the Android SDK Build Tools directory}
badging=$("$build_tools/aapt" dump badging "$apk")
package="package: name='cy.hexor.tsunagi' versionCode='$version_code' versionName='$version_name'"
if [[ "$badging" != "$package "* ]]; then
echo "Expected tsunagi $version_name (version code $version_code) in the APK manifest" >&2
exit 1
fi
if grep -Fxq 'application-debuggable' <<< "$badging"; then
echo "The release APK enables Android debugging" >&2
exit 1
fi
if ! grep -Fxq "native-code: 'arm64-v8a'" <<< "$badging"; then
echo "Expected an arm64-v8a APK" >&2
exit 1
fi
library=$(mktemp)
trap 'rm -f "$library"' EXIT
unzip -p "$apk" lib/arm64-v8a/libtsunagi_android.so > "$library"
if [[ "$(LC_ALL=C file -b "$library")" != *"ARM aarch64"*", stripped"* ]]; then
echo "Expected a stripped ARM64 tsunagi native library" >&2
exit 1
fi
"$build_tools/zipalign" -c -P 16 4 "$apk"
"$build_tools/apksigner" verify --verbose --print-certs "$apk"
+46
View File
@@ -0,0 +1,46 @@
[package]
name = "tsunagi-android"
version = "1.0.5"
description = "Android VPN client and egui views for tsunagi."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish = false
[lib]
crate-type = ["cdylib", "rlib"]
[[example]]
name = "vpn_source_probe"
crate-type = ["cdylib"]
[dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.5" }
tsunagi-ui = { path = "../tsunagi-ui" }
tsunagi-core = { path = "../tsunagi-core" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
egui = "0.31"
egui-phosphor = "0.9"
tokio.workspace = true
bytes.workspace = true
zeroize = "1.9"
simple-dns = "0.12"
[target.'cfg(unix)'.dependencies]
rand = "0.10"
smoltcp = { version = "0.12", default-features = false, features = ["std", "medium-ip", "proto-ipv4", "socket-tcp", "socket-udp"] }
[target.'cfg(target_os = "android")'.dependencies]
egui_glow = { version = "0.31", default-features = false }
jni = "0.21"
iroh.workspace = true
jni-verifier = { package = "jni", version = "0.22" }
rustls-platform-verifier = "0.7"
[dev-dependencies]
tempfile.workspace = true
tsunagi-core = { path = "../tsunagi-core", features = ["testing"] }
[lints]
workspace = true
@@ -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(())
}
@@ -0,0 +1,279 @@
//! Android owns the GLES surface, keyboard and clipboard. egui owns the widgets.
use crate::view::{Phone, SystemAction};
use egui::{
Event, ImeEvent, Key, Modifiers, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase,
};
use egui_glow::{Painter, glow};
use jni::{
JNIEnv,
objects::{JObject, JString, JValue},
sys::{jboolean, jfloat, jint, jlong},
};
use std::{
cell::RefCell,
ffi::{c_char, c_void},
sync::Arc,
time::Instant,
};
#[link(name = "EGL")]
unsafe extern "C" {
fn eglGetProcAddress(name: *const c_char) -> *const c_void;
}
struct Display {
painter: Painter,
ctx: egui::Context,
ui: Phone,
events: Vec<Event>,
primary: Option<i32>,
start: Instant,
ime: i32,
exit_active: bool,
}
thread_local! { static DISPLAY: RefCell<Option<Display>> = const {RefCell::new(None)}; }
fn with_display<T: Default>(f: impl FnOnce(&mut Display) -> T) -> T {
DISPLAY.with_borrow_mut(|d| d.as_mut().map(f).unwrap_or_default())
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObject) {
// SAFETY: GLSurfaceView invokes this callback on the GL thread with its ES3 context current.
let gl = unsafe {
glow::Context::from_loader_function_cstr(|name| eglGetProcAddress(name.as_ptr()))
};
let Ok(painter) = Painter::new(Arc::new(gl), "", None, false) else {
let _ = env.throw_new(
"java/lang/IllegalStateException",
"Could not initialise OpenGL ES",
);
return;
};
let ctx = egui::Context::default();
crate::view::configure(&ctx);
DISPLAY.with_borrow_mut(|d| {
// If Android discarded the old EGL context, its GPU resources are already gone.
let ui = d
.take()
.map(|old| {
// A rotation can recreate EGL. Keep expanded peers and scroll positions
// while the new context uploads its own font atlas.
let data = old.ctx.data_mut(std::mem::take);
ctx.data_mut(|current| *current = data);
old.ui
})
.unwrap_or_default();
*d = Some(Display {
painter,
ctx,
ui,
events: Vec::new(),
primary: None,
start: Instant::now(),
ime: -1,
exit_active: false,
});
});
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
mut env: JNIEnv,
_: JObject,
host: JObject,
w: jint,
h: jint,
scale: jfloat,
service_started: jboolean,
landscape: jboolean,
) -> jlong {
with_display(|d| {
tsunagi_ui::widgets::set_landscape(&d.ctx, landscape != 0);
let size = egui::vec2(w as f32, h as f32) / scale;
let mut input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)),
events: std::mem::take(&mut d.events),
time: Some(d.start.elapsed().as_secs_f64()),
..Default::default()
};
if let Some(info) = input.viewports.get_mut(&egui::ViewportId::ROOT) {
info.native_pixels_per_point = Some(scale);
}
let mut action = None;
let state = match super::status() {
crate::service::State::Off if service_started != 0 => crate::service::State::Starting,
state => state,
};
let exit_active = matches!(&state, crate::service::State::Ready(report, _) if report.networks.iter().any(|n| n.active && n.exit.via.is_some()));
if exit_active && !d.exit_active {
let _ = env.call_method(&host, "requestExitNotifications", "()V", &[]);
}
d.exit_active = exit_active;
let output = d.ctx.run(input, |ctx| {
action = d.ui.draw(ctx, &state, super::send).or(action);
});
if let Some(action) = action {
let method = match action {
SystemAction::Start => "startAgent",
SystemAction::Stop => "stopAgent",
SystemAction::PasteSecret => "pasteSecret",
SystemAction::Finish => "closeScreen",
};
let _ = env.call_method(&host, method, "()V", &[]);
}
if let Some(secret) = d.ui.take_copied_secret()
&& let Ok(text) = env.new_string(secret.as_str())
{
let _ = env.call_method(
&host,
"copySecret",
"(Ljava/lang/String;)V",
&[JValue::Object(&text)],
);
}
for command in output.platform_output.commands {
let (method, value) = match command {
egui::OutputCommand::CopyText(text) => ("copyText", text),
egui::OutputCommand::OpenUrl(url) => ("openUrl", url.url),
_ => continue,
};
if let Ok(text) = env.new_string(value) {
let _ = env.call_method(
&host,
method,
"(Ljava/lang/String;)V",
&[JValue::Object(&text)],
);
}
}
let ime = if output.platform_output.ime.is_none() {
0
} else if d.ui.secret_focused(&d.ctx) {
2
} else {
1
};
if ime != d.ime {
d.ime = ime;
let _ = env.call_method(&host, "keyboard", "(I)V", &[JValue::Int(ime)]);
}
let ppp = output.pixels_per_point;
let primitives = d.ctx.tessellate(output.shapes, ppp);
let pixels = [w as u32, h as u32];
d.painter.clear(pixels, [0.1, 0.1, 0.1, 1.0]);
d.painter
.paint_and_update_textures(pixels, ppp, &primitives, &output.textures_delta);
output
.viewport_output
.get(&egui::ViewportId::ROOT)
.map_or(1000, |v| {
v.repaint_delay.as_millis().clamp(16, 1000) as jlong
})
})
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_touch(
_: JNIEnv,
_: JObject,
action: jint,
id: jint,
x: jfloat,
y: jfloat,
) {
with_display(|d| {
let pos = egui::pos2(x, y);
let phase = match action {
0 => TouchPhase::Start,
1 => TouchPhase::Move,
2 => TouchPhase::End,
_ => TouchPhase::Cancel,
};
d.events.push(Event::Touch {
device_id: TouchDeviceId(0),
id: TouchId(id as u64),
phase,
pos,
force: None,
});
if phase == TouchPhase::Start && d.primary.is_none() {
d.primary = Some(id);
}
if d.primary != Some(id) {
return;
}
if phase != TouchPhase::Cancel {
d.events.push(Event::PointerMoved(pos));
}
if phase != TouchPhase::Move {
if phase == TouchPhase::Cancel {
d.events.push(Event::PointerGone);
}
d.events.push(Event::PointerButton {
pos,
button: PointerButton::Primary,
pressed: phase == TouchPhase::Start,
modifiers: Modifiers::NONE,
});
}
if matches!(phase, TouchPhase::Cancel | TouchPhase::End) {
d.events.push(Event::PointerGone);
d.primary = None;
}
});
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_input(
mut env: JNIEnv,
_: JObject,
kind: jint,
value: JString,
) {
let Ok(text) = env.get_string(&value) else {
return;
};
let text = String::from(text);
with_display(|d| match kind {
0 => d.events.push(Event::Text(text)),
1 => d.events.push(Event::Ime(ImeEvent::Enabled)),
2 => d.events.push(Event::Ime(ImeEvent::Preedit(text))),
3 => {
d.events.push(Event::Ime(ImeEvent::Commit(text)));
d.events.push(Event::Ime(ImeEvent::Disabled));
}
4 => d.ui.paste_secret(text),
5 => d.ui.error(text),
6 => d.ui.request_exit_picker(),
_ => {}
});
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_key(_: JNIEnv, _: JObject, key: jint) {
let key = match key {
67 => Key::Backspace,
112 => Key::Delete,
66 => Key::Enter,
21 => Key::ArrowLeft,
22 => Key::ArrowRight,
61 => Key::Tab,
_ => return,
};
with_display(|d| {
for pressed in [true, false] {
d.events.push(Event::Key {
key,
physical_key: None,
pressed,
repeat: false,
modifiers: Modifiers::NONE,
});
}
});
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_back(mut env: JNIEnv, _: JObject, host: JObject) {
with_display(|d| {
if d.ui.back() == Some(SystemAction::Finish) {
let _ = env.call_method(&host, "closeScreen", "()V", &[]);
}
});
}
+90
View File
@@ -0,0 +1,90 @@
//! Android's physical-network resolver, including its Private DNS policy.
use crate::dns::Resolver;
use jni::{
JNIEnv, JavaVM,
objects::{GlobalRef, JByteArray, JString, JValue},
};
use simple_dns::{CLASS, Packet, PacketFlag, QTYPE, RCODE, ResourceRecord, TYPE, rdata::RData};
use std::{net::IpAddr, sync::Arc};
pub(super) fn resolver(vm: Arc<JavaVM>, service: GlobalRef, sdk: i32) -> Resolver {
Resolver::new(move |query| {
let mut env = vm.attach_current_thread().ok()?;
let response = env.with_local_frame(6, |env| {
if sdk < 29 {
return legacy(env, &service, query);
}
let bytes = env.byte_array_from_slice(query)?;
let reply = env
.call_method(&service, "resolveDns", "([B)[B", &[JValue::Object(&bytes)])?
.l()?;
if reply.is_null() {
return Ok(None);
}
let reply = JByteArray::from(reply);
if env.get_array_length(&reply)? > i32::from(u16::MAX) {
return Ok(None);
}
env.convert_byte_array(reply).map(Some)
});
if env.exception_check().unwrap_or(false) {
let _ = env.exception_clear();
return None;
}
response.ok().flatten()
})
}
fn legacy(
env: &mut JNIEnv<'_>,
service: &GlobalRef,
query: &[u8],
) -> jni::errors::Result<Option<Vec<u8>>> {
let Some(packet) = Packet::parse(query).ok() else {
return Ok(None);
};
let [question] = packet.questions.as_slice() else {
return Ok(None);
};
let mut reply = Packet::new_reply(packet.id());
reply.questions.push(question.clone());
reply.set_flags(PacketFlag::RECURSION_AVAILABLE);
if packet.has_flags(PacketFlag::RECURSION_DESIRED) {
reply.set_flags(PacketFlag::RECURSION_DESIRED);
}
if matches!(question.qtype, QTYPE::TYPE(TYPE::A | TYPE::AAAA)) {
let name = env.new_string(format!("{}.", question.qname))?;
let addresses = env
.call_method(
service,
"resolveAddresses",
"(Ljava/lang/String;)Ljava/lang/String;",
&[JValue::Object(&name)],
)?
.l()?;
if addresses.is_null() {
return Ok(None);
}
let addresses: String = env.get_string(&JString::from(addresses))?.into();
for address in addresses
.split(',')
.take(128)
.filter_map(|s| s.parse::<IpAddr>().ok())
{
let data = match (question.qtype, address) {
(QTYPE::TYPE(TYPE::A), IpAddr::V4(v4)) => RData::A(v4.into()),
(QTYPE::TYPE(TYPE::AAAA), IpAddr::V6(v6)) => RData::AAAA(v6.into()),
_ => continue,
};
reply.answers.push(ResourceRecord::new(
question.qname.clone(),
CLASS::IN,
0,
data,
));
}
} else {
*reply.rcode_mut() = RCODE::NotImplemented;
}
Ok(reply.build_bytes_vec_compressed().ok())
}
+429
View File
@@ -0,0 +1,429 @@
//! Android process entry points. JNI owns references here, never in the core.
#![allow(unsafe_code)]
mod display;
mod dns;
use crate::{
plan::VpnPlan,
service::{Reply, Request, Response, State},
tun::AndroidTun,
};
use jni::{
JNIEnv, JavaVM,
objects::{GlobalRef, JObject, JString, JValue},
sys::jlong,
};
use std::{
fs::File,
io,
os::fd::{AsRawFd, FromRawFd, OwnedFd},
path::PathBuf,
sync::{Arc, Mutex, OnceLock},
};
use tokio::sync::{mpsc, oneshot, watch};
use tsunagi::{Agent, AgentConfig, StoragePaths, TransportPolicy, discovery::MainlineDiscovery};
use tsunagi_wg_quic::{DEFAULT_MTU, WireguardConfig, WireguardPlugin};
struct Session {
id: i64,
last_refresh: Option<std::time::Instant>,
commands: mpsc::Sender<(Request, Reply)>,
state: watch::Receiver<State>,
underlay: watch::Sender<Vec<std::net::IpAddr>>,
stop: watch::Sender<bool>,
}
static SESSION: Mutex<Option<Session>> = Mutex::new(None);
// Stop/start can cross on the Android main thread. The previous agent closes
// its fd, endpoint and directory lock before its successor opens that identity.
static LIFETIME: Mutex<()> = Mutex::new(());
fn current() -> std::sync::MutexGuard<'static, Option<Session>> {
SESSION.lock().unwrap_or_else(|e| e.into_inner())
}
fn status() -> State {
let mut current = current();
let Some(session) = current.as_mut() else {
return State::Off;
};
if session
.last_refresh
.is_none_or(|last| last.elapsed() >= std::time::Duration::from_secs(2))
&& session
.commands
.try_send((Request::Refresh, oneshot::channel().0))
.is_ok()
{
session.last_refresh = Some(std::time::Instant::now());
}
session.state.borrow().clone()
}
fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
let (reply, result) = oneshot::channel();
current()
.as_ref()
.ok_or("Tsunagi Agent stopped")?
.commands
.try_send((Request::Action(cmd), reply))
.map_err(|_| "Tsunagi Agent is busy or stopped".to_owned())?;
Ok(result)
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_trust(
mut env: jni_verifier::EnvUnowned,
_: jni_verifier::objects::JObject,
app: jni_verifier::objects::JObject,
) {
env.with_env(|env| rustls_platform_verifier::android::init_with_env(env, app))
.resolve::<jni_verifier::errors::ThrowRuntimeExAndDefault>();
}
fn establish(vm: &JavaVM, service: &GlobalRef, plan: &VpnPlan) -> io::Result<File> {
let mut env = vm.attach_current_thread().map_err(io::Error::other)?;
let addresses = plan
.addresses_in_order()
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(",");
let routes = plan.routes().join(",");
let result = env.with_local_frame(6, |env| -> jni::errors::Result<i32> {
let addresses = env.new_string(addresses)?;
let routes = env.new_string(routes)?;
let dns = env.new_string(
plan.dns_address()
.map(|a| a.to_string())
.unwrap_or_default(),
)?;
env.call_method(
service,
"establishTun",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)I",
&[
JValue::Object(&addresses),
JValue::Object(&routes),
JValue::Object(&dns),
JValue::Int(plan.mtu as i32),
JValue::Bool(plan.full_tunnel.into()),
],
)?
.i()
});
if env.exception_check().unwrap_or(false) {
let _ = env.exception_clear();
return Err(io::Error::other(
"Android could not establish the VPN. Check the VPN permission.",
));
}
let fd = result.map_err(io::Error::other)?;
if fd < 0 {
return Err(io::Error::other("Android revoked the VPN permission"));
}
// SAFETY: establishTun transferred exclusive ownership with detachFd().
Ok(File::from(unsafe { OwnedFd::from_raw_fd(fd) }))
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_start(
mut env: JNIEnv,
_: JObject,
service: JObject,
app: JObject,
state_dir: JString,
cache_dir: JString,
addresses: JString,
) -> jlong {
let result = (|| -> Result<i64, Box<dyn std::error::Error>> {
// Keep the application (never an activity) alive for DNS throughout the process.
static APPLICATION: OnceLock<GlobalRef> = OnceLock::new();
let vm = Arc::new(env.get_java_vm()?);
let application = env.new_global_ref(app)?;
if APPLICATION.set(application.clone()).is_ok() {
// SAFETY: the VM and this stored global reference live until process exit.
unsafe {
iroh::dns::install_android_jni_context(
vm.get_java_vm_pointer().cast(),
application.as_obj().as_raw().cast(),
);
}
}
let service = env.new_global_ref(service)?;
let state_dir: String = env.get_string(&state_dir)?.into();
let cache_dir: String = env.get_string(&cache_dir)?.into();
let paths = StoragePaths::new(PathBuf::from(state_dir), PathBuf::from(cache_dir));
let tun_vm = vm.clone();
let tun_service = service.clone();
let notice_vm = vm.clone();
let notice_service = service.clone();
let sdk = env
.get_static_field("android/os/Build$VERSION", "SDK_INT", "I")?
.i()?;
let dns = dns::resolver(vm.clone(), service.clone(), sdk);
let factory = AndroidTun::new(
dns.clone(),
move |plan| establish(&tun_vm, &tun_service, plan),
move |socket, source| {
let mut env = vm.attach_current_thread().map_err(io::Error::other)?;
let result = env.with_local_frame(3, |env| -> jni::errors::Result<bool> {
let source = env.new_string(source.to_string())?;
env.call_method(
&service,
"bindOverlaySocket",
"(ILjava/lang/String;)Z",
&[JValue::Int(socket.as_raw_fd()), JValue::Object(&source)],
)?
.z()
});
if env.exception_check().unwrap_or(false) {
let _ = env.exception_clear();
return Err(io::Error::other("VPN socket binding failed"));
}
if result.map_err(io::Error::other)? {
Ok(())
} else {
Err(io::Error::other("VPN network is unavailable"))
}
},
);
let addresses: String = env.get_string(&addresses)?.into();
let (underlay, physical) = watch::channel(underlay_ips(&addresses));
let (commands, rx) = mpsc::channel(16);
let (state, state_rx) = watch::channel(State::Starting);
let (stop, stopped) = watch::channel(false);
static NEXT: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut slot = current();
if let Some(old) = slot.as_ref() {
old.stop.send_replace(true);
}
std::thread::Builder::new()
.name("tsunagi-agent".into())
.spawn(move || {
let _lifetime = LIFETIME.lock().unwrap_or_else(|e| e.into_inner());
if *stopped.borrow() {
return;
}
let run = || -> Result<(), Box<dyn std::error::Error>> {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()?;
runtime.block_on(async {
let wg = WireguardPlugin::open(WireguardConfig::new(
paths.state_dir.join("wg-quic"),
))
.await?;
let config = AgentConfig::new(paths)
.with_transport(TransportPolicy::N0Defaults)
.with_dht(MainlineDiscovery::default())
.with_interface(Arc::new(factory), "tsunagi-vpn", DEFAULT_MTU)
.with_tunnel(wg.clone());
let (config, carriers) = tsunagi_runtime::Carriers::configure(
config,
&[],
Some(physical),
|_| Vec::new(),
)
.await?;
let agent = Agent::spawn(config).await?;
let _listeners = carriers.listen(&agent);
crate::service::serve(agent, wg, dns, rx, &state, stopped, |notice| {
update_exit_notification(&notice_vm, &notice_service, id, notice);
})
.await;
Ok(())
})
};
if let Err(e) = run() {
state.send_replace(State::Error(e.to_string()));
}
})?;
*slot = Some(Session {
id,
last_refresh: None,
commands,
state: state_rx,
underlay,
stop,
});
Ok(id)
})();
match result {
Ok(id) => id,
Err(e) => {
let _ = env.throw_new("java/lang/IllegalStateException", e.to_string());
0
}
}
}
fn update_exit_notification(
vm: &JavaVM,
service: &GlobalRef,
id: i64,
notice: Option<&crate::service::ExitNotice>,
) {
let Ok(mut env) = vm.attach_current_thread() else {
return;
};
let _ = env.with_local_frame(8, |env| -> jni::errors::Result<()> {
let network = env.new_string(notice.map_or("", |n| &n.network))?;
let peer = env.new_string(notice.map_or("", |n| &n.peer))?;
let name = env.new_string(notice.map_or("", |n| &n.name))?;
let title = env.new_string(
notice
.map(|n| format!("Exit node · {}", n.name))
.unwrap_or_default(),
)?;
let text = env.new_string(
notice
.map(|n| {
if n.online {
format!("IPv4 internet via {}", n.network_name)
} else {
format!(
"{} · Exit offline. IPv4 internet is blocked.",
n.network_name
)
}
})
.unwrap_or_default(),
)?;
env.call_method(
service,
"updateExitNotification",
"(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V",
&[
JValue::Long(id),
JValue::Object(&network),
JValue::Object(&peer),
JValue::Object(&title),
JValue::Object(&text),
JValue::Object(&name),
JValue::Bool(notice.is_some_and(|n| n.online).into()),
],
)?;
Ok(())
});
if env.exception_check().unwrap_or(false) {
let _ = env.exception_clear();
}
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_disconnectExit(
mut env: JNIEnv,
_: JObject,
id: jlong,
network: JString,
peer: JString,
) -> jni::sys::jboolean {
let (Ok(network), Ok(peer)) = (env.get_string(&network), env.get_string(&peer)) else {
return false.into();
};
current()
.as_ref()
.filter(|s| s.id == id)
.is_some_and(|s| {
s.commands
.try_send((
Request::DisconnectExit {
network: network.into(),
peer: peer.into(),
},
oneshot::channel().0,
))
.is_ok()
})
.into()
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_tileExit(
mut env: JNIEnv,
_: JObject,
id: jlong,
network: JString,
peer: JString,
connect: jni::sys::jboolean,
wait_for_discovery: jni::sys::jboolean,
) -> jni::sys::jstring {
// Called on the tile's background worker. Never hold the session lock while awaiting the agent.
let mut run = || -> Result<(), String> {
let network: String = env.get_string(&network).map_err(|e| e.to_string())?.into();
let peer: String = env.get_string(&peer).map_err(|e| e.to_string())?.into();
let (commands, mut state) = current()
.as_ref()
.filter(|s| s.id == id)
.map(|s| (s.commands.clone(), s.state.clone()))
.ok_or("Tsunagi Agent stopped")?;
if connect != 0 && wait_for_discovery != 0 {
tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.map_err(|e| e.to_string())?
.block_on(crate::service::wait_for_exit_offer(
&mut state, &network, &peer,
))?;
}
let request = if connect != 0 {
Request::RestoreExit { network, peer }
} else {
Request::DisconnectExit { network, peer }
};
let (reply, result) = oneshot::channel();
commands
.try_send((request, reply))
.map_err(|_| "Tsunagi Agent is busy or stopped")?;
result
.blocking_recv()
.map_err(|_| "Tsunagi Agent stopped")??;
Ok(())
};
run()
.err()
.and_then(|e| env.new_string(e).ok())
.map_or(std::ptr::null_mut(), JString::into_raw)
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_failed(
_: JNIEnv,
_: JObject,
id: jlong,
) -> jni::sys::jboolean {
current()
.as_ref()
.is_some_and(|s| s.id == id && matches!(*s.state.borrow(), State::Error(_)))
.into()
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_stop(_: JNIEnv, _: JObject, id: jlong) {
let mut slot = current();
if slot.as_ref().is_some_and(|s| s.id == id)
&& let Some(session) = slot.take()
{
session.stop.send_replace(true);
}
}
fn underlay_ips(addresses: &str) -> Vec<std::net::IpAddr> {
addresses
.split(',')
.take(32)
.filter_map(|s| s.parse().ok())
.collect()
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_networkChanged(
mut env: JNIEnv,
_: JObject,
id: jlong,
addresses: JString,
) {
let Ok(raw) = env.get_string(&addresses) else {
return;
};
if let Some(s) = current().as_ref().filter(|s| s.id == id) {
s.underlay.send_replace(underlay_ips(&String::from(raw)));
let _ = s
.commands
.try_send((Request::NetworkChanged, oneshot::channel().0));
}
}
+129
View File
@@ -0,0 +1,129 @@
//! Device-local split DNS. Only questions outside the signed mesh zones reach Android's resolver.
use simple_dns::{Packet, PacketFlag, RCODE};
use std::{net::Ipv4Addr, sync::Arc, time::Duration};
use tokio::sync::{Semaphore, watch};
use tsunagi::dns::{
Zones,
server::{MAX_MESSAGE_LEN, Resolution, parse_message, resolve},
};
#[cfg(unix)]
pub(crate) mod stack;
type Upstream = dyn Fn(&[u8]) -> Option<Vec<u8>> + Send + Sync;
/// One view of all joined zones, shared across TUN replacements.
#[derive(Clone)]
pub struct Resolver {
zones: watch::Sender<Option<Arc<Zones>>>,
listening: watch::Sender<Option<Ipv4Addr>>,
upstream: Arc<Upstream>,
pending: Arc<Semaphore>,
}
impl Resolver {
/// The platform callback resolves a wire question on the selected physical network.
pub fn new(upstream: impl Fn(&[u8]) -> Option<Vec<u8>> + Send + Sync + 'static) -> Self {
Self {
zones: watch::channel(None).0,
listening: watch::channel(None).0,
upstream: Arc::new(upstream),
pending: Arc::new(Semaphore::new(16)),
}
}
/// Withhold forwarding while configured zones are loading or changing.
pub fn replace(&self, zones: Option<Zones>) {
self.zones.send_replace(zones.map(Arc::new));
}
#[cfg(unix)]
pub(crate) fn publish(&self, address: Option<Ipv4Addr>) {
self.listening.send_replace(address);
}
pub(crate) fn refresh(&self, networks: &[tsunagi::NetworkStatus]) -> tsunagi::ipc::DnsReport {
let view = tsunagi::dns::RosterZones::from_networks(networks);
let names = view.zones.names() as u32;
self.replace(Some(view.zones));
tsunagi::ipc::DnsReport {
zones: view.labels,
zone_warnings: view.warnings,
names,
..Default::default()
}
}
pub(crate) fn with_listener(
&self,
mut report: tsunagi::ipc::DnsReport,
) -> tsunagi::ipc::DnsReport {
let address = *self.listening.borrow();
report.listening = address.map(|ip| format!("{ip}:53")).into_iter().collect();
report.publish_error = (address.is_none() && !report.zones.is_empty())
.then(|| "Waiting for a VPN interface with a DNS address.".into());
report
}
/// Answer a local DNS request. Slow public lookups never block a mesh answer.
pub async fn answer(&self, query: &[u8]) -> Option<Vec<u8>> {
if query.len() > MAX_MESSAGE_LEN {
return None;
}
let zones = self.zones.borrow().clone();
let Some(zones) = zones else {
let question = parse_message(query)?;
if question.has_flags(PacketFlag::RESPONSE) {
return None;
}
return error_reply(&question, RCODE::ServerFailure);
};
match resolve(&zones, query)? {
Resolution::Local(reply) => Some(reply),
Resolution::Outside(_) => {
let question = parse_message(query)?;
if let Ok(permit) = self.pending.clone().try_acquire_owned() {
let upstream = self.upstream.clone();
let wire = query.to_vec();
let job = tokio::task::spawn_blocking(move || {
let _permit = permit;
upstream(&wire)
});
if let Ok(Ok(Some(mut wire))) =
tokio::time::timeout(Duration::from_secs(5), job).await
&& wire.len() <= usize::from(u16::MAX)
&& parse_message(&wire).is_some_and(|p| {
let [received] = p.questions.as_slice() else {
return false;
};
let sent = &question.questions[0]; // Resolution::Outside has exactly one IN question.
p.has_flags(PacketFlag::RESPONSE)
&& received.qtype == sent.qtype
&& received.qclass == sent.qclass
&& received
.qname
.to_string()
.eq_ignore_ascii_case(&sent.qname.to_string())
})
{
// Android's upstream transaction may have used its own ID.
wire[..2].copy_from_slice(&question.id().to_be_bytes());
return Some(wire);
}
}
error_reply(&question, RCODE::ServerFailure)
}
}
}
}
fn error_reply(query: &Packet<'_>, code: RCODE) -> Option<Vec<u8>> {
let mut answer = Packet::new_reply(query.id());
answer.questions.clone_from(&query.questions);
if query.has_flags(PacketFlag::RECURSION_DESIRED) {
answer.set_flags(PacketFlag::RECURSION_DESIRED);
}
answer.set_flags(PacketFlag::RECURSION_AVAILABLE);
*answer.rcode_mut() = code;
answer.build_bytes_vec_compressed().ok()
}
+311
View File
@@ -0,0 +1,311 @@
//! A DNS-only endpoint on the application side of one Android TUN descriptor.
//! The kernel reserves port 53. smoltcp terminates UDP and TCP without root.
use super::Resolver;
use smoltcp::{
iface::{Config, Interface, SocketHandle, SocketSet},
phy::{self, Device, DeviceCapabilities, Medium},
socket::{tcp, udp},
time::Instant as NetTime,
wire::{HardwareAddress, IpAddress, IpCidr, IpEndpoint},
};
use std::{
collections::VecDeque,
fs::File,
io::Write,
net::{IpAddr, Ipv4Addr},
sync::Arc,
time::{Duration, Instant},
};
use tokio::{
io::{Interest, unix::AsyncFd},
sync::mpsc,
task::{JoinHandle, JoinSet},
};
use tsunagi::dns::server::{MAX_MESSAGE_LEN, truncate_for_udp};
const PORT: u16 = 53;
const QUEUE: usize = 32;
const TCP_CLIENTS: usize = 8;
#[cfg(test)]
mod tests;
pub(crate) struct DnsPort {
address: Ipv4Addr,
input: mpsc::Sender<Vec<u8>>,
worker: JoinHandle<()>,
}
impl DnsPort {
pub(crate) fn start(
address: Ipv4Addr,
mtu: usize,
resolver: Resolver,
fd: Arc<AsyncFd<File>>,
) -> Self {
let (input, packets) = mpsc::channel(QUEUE);
let worker = tokio::spawn(run(address, mtu, resolver, packets, fd));
Self {
address,
input,
worker,
}
}
/// Consume only packets sent to our private endpoint by a local VPN address.
pub(crate) fn intercept(&self, bytes: &[u8], local: &[IpAddr]) -> bool {
let Ok(packet) = smoltcp::wire::Ipv4Packet::new_checked(bytes) else {
return false;
};
if packet.version() != 4 || packet.dst_addr() != self.address {
return false;
}
if local.contains(&IpAddr::V4(packet.src_addr())) {
let _ = self.input.try_send(bytes.to_vec());
}
true
}
}
impl Drop for DnsPort {
fn drop(&mut self) {
self.worker.abort();
}
}
struct Wire {
mtu: usize,
input: Option<Vec<u8>>,
output: VecDeque<Vec<u8>>,
}
struct Rx(Vec<u8>);
impl phy::RxToken for Rx {
fn consume<R, F: FnOnce(&[u8]) -> R>(self, f: F) -> R {
f(&self.0)
}
}
struct Tx<'a>(&'a mut VecDeque<Vec<u8>>);
impl phy::TxToken for Tx<'_> {
fn consume<R, F: FnOnce(&mut [u8]) -> R>(self, len: usize, f: F) -> R {
let mut packet = vec![0; len];
let result = f(&mut packet);
self.0.push_back(packet);
result
}
}
impl Device for Wire {
type RxToken<'a> = Rx;
type TxToken<'a> = Tx<'a>;
fn receive(&mut self, _: NetTime) -> Option<(Rx, Tx<'_>)> {
self.input
.take()
.map(|packet| (Rx(packet), Tx(&mut self.output)))
}
fn transmit(&mut self, _: NetTime) -> Option<Tx<'_>> {
(self.output.len() < QUEUE).then_some(Tx(&mut self.output))
}
fn capabilities(&self) -> DeviceCapabilities {
let mut caps = DeviceCapabilities::default();
caps.medium = Medium::Ip;
caps.max_transmission_unit = self.mtu;
caps
}
}
struct TcpSlot {
handle: SocketHandle,
pending: Option<u64>,
}
enum Client {
Udp(IpEndpoint),
Tcp { slot: usize, request: u64 },
}
type Jobs = JoinSet<(Client, Option<Vec<u8>>)>;
struct Stack {
iface: Interface,
wire: Wire,
sockets: SocketSet<'static>,
udp: SocketHandle,
tcp: Vec<TcpSlot>,
next_request: u64,
}
impl Stack {
fn new(address: Ipv4Addr, mtu: usize) -> Self {
let mut wire = Wire {
mtu,
input: None,
output: VecDeque::new(),
};
let mut config = Config::new(HardwareAddress::Ip);
config.random_seed = rand::random();
let mut iface = Interface::new(config, &mut wire, NetTime::from_millis(0));
// This is a point-to-point IP device. Its only neighbour is Android, whatever
// the OS chose as the source address among the attached networks.
iface.update_ip_addrs(|addrs| {
let _ = addrs.push(IpCidr::new(IpAddress::Ipv4(address), 0));
});
let mut sockets = SocketSet::new(Vec::new());
let datagrams = || {
udp::PacketBuffer::new(
vec![udp::PacketMetadata::EMPTY; QUEUE],
vec![0; QUEUE * mtu],
)
};
let mut socket = udp::Socket::new(datagrams(), datagrams());
let _ = socket.bind(PORT);
let udp = sockets.add(socket);
let tcp = (0..TCP_CLIENTS)
.map(|_| {
let mut socket = tcp::Socket::new(
tcp::SocketBuffer::new(vec![0; MAX_MESSAGE_LEN + 2]),
tcp::SocketBuffer::new(vec![0; usize::from(u16::MAX) + 2]),
);
socket.set_timeout(Some(smoltcp::time::Duration::from_secs(10)));
let _ = socket.listen(PORT);
TcpSlot {
handle: sockets.add(socket),
pending: None,
}
})
.collect();
Self {
iface,
wire,
sockets,
udp,
tcp,
next_request: 0,
}
}
fn poll(&mut self, now: NetTime) {
self.iface.poll(now, &mut self.wire, &mut self.sockets);
}
fn dispatch(&mut self, resolver: &Resolver, jobs: &mut Jobs) {
let udp = self.sockets.get_mut::<udp::Socket>(self.udp);
while let Ok((wire, metadata)) = udp.recv() {
if jobs.len() >= QUEUE || wire.len() > MAX_MESSAGE_LEN {
continue;
}
let resolver = resolver.clone();
let query = wire.to_vec();
let limit = self.wire.mtu.saturating_sub(28);
jobs.spawn(async move {
let reply = resolver
.answer(&query)
.await
.map(|reply| truncate_for_udp(&query, reply, limit));
(Client::Udp(metadata.endpoint), reply)
});
}
for (index, slot) in self.tcp.iter_mut().enumerate() {
let tcp = self.sockets.get_mut::<tcp::Socket>(slot.handle);
if !tcp.is_open() {
slot.pending = None;
let _ = tcp.listen(PORT);
}
if slot.pending.is_some() || tcp.send_queue() != 0 {
continue;
}
if tcp.state() == tcp::State::CloseWait && tcp.recv_queue() < 2 {
tcp.close();
continue;
}
let mut header = [0; 2];
if tcp.peek_slice(&mut header) != Ok(2) {
continue;
}
let len = usize::from(u16::from_be_bytes(header));
if !(12..=MAX_MESSAGE_LEN).contains(&len) {
tcp.abort();
continue;
}
if tcp.recv_queue() < len + 2 || jobs.len() >= QUEUE {
continue;
}
let mut query = vec![0; len];
if tcp.recv_slice(&mut header) != Ok(2) || tcp.recv_slice(&mut query) != Ok(len) {
tcp.abort();
continue;
}
self.next_request = self.next_request.wrapping_add(1);
let request = self.next_request;
slot.pending = Some(request);
let resolver = resolver.clone();
jobs.spawn(async move {
(
Client::Tcp {
slot: index,
request,
},
resolver.answer(&query).await,
)
});
}
}
fn deliver(&mut self, client: Client, reply: Option<Vec<u8>>) {
match client {
Client::Udp(peer) => {
if let Some(reply) = reply {
let _ = self
.sockets
.get_mut::<udp::Socket>(self.udp)
.send_slice(&reply, peer);
}
}
Client::Tcp { slot, request } => {
let slot = &mut self.tcp[slot];
if slot.pending != Some(request) {
return;
}
slot.pending = None;
let tcp = self.sockets.get_mut::<tcp::Socket>(slot.handle);
if let Some(reply) = reply
&& let Ok(len) = u16::try_from(reply.len())
&& tcp.send_slice(&len.to_be_bytes()) == Ok(2)
&& tcp.send_slice(&reply) == Ok(reply.len())
{
return;
}
tcp.abort();
}
}
}
}
async fn run(
address: Ipv4Addr,
mtu: usize,
resolver: Resolver,
mut input: mpsc::Receiver<Vec<u8>>,
fd: Arc<AsyncFd<File>>,
) {
let mut stack = Stack::new(address, mtu);
let mut jobs = Jobs::new();
let start = Instant::now();
loop {
let now = NetTime::from_millis(start.elapsed().as_millis() as i64);
stack.poll(now);
stack.dispatch(&resolver, &mut jobs);
stack.poll(now);
while let Some(packet) = stack.wire.output.pop_front() {
if !matches!(fd.async_io(Interest::WRITABLE, |mut file| file.write(&packet)).await, Ok(n) if n == packet.len())
{
return;
}
}
let delay = stack
.iface
.poll_delay(now, &stack.sockets)
.map(Duration::from);
tokio::select! {
packet = input.recv() => match packet { Some(packet) => stack.wire.input = Some(packet), None => return },
Some(Ok((client, reply))) = jobs.join_next(), if !jobs.is_empty() => stack.deliver(client, reply),
_ = async { if let Some(delay) = delay { tokio::time::sleep(delay).await } else { std::future::pending().await } } => {}
}
}
}
@@ -0,0 +1,105 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use simple_dns::{CLASS, Name, Packet, PacketFlag, Question, TYPE};
use std::os::{fd::OwnedFd, unix::net::UnixDatagram};
use tsunagi::dns::{Zone, ZoneName, Zones};
#[tokio::test]
async fn android_tun_dns_truncates_udp_and_returns_the_complete_answer_over_tcp() {
let address = Ipv4Addr::new(192, 0, 2, 53);
let phone = Ipv4Addr::new(10, 10, 0, 1);
let (fd, os) = UnixDatagram::pair().unwrap();
fd.set_nonblocking(true).unwrap();
os.set_nonblocking(true).unwrap();
let fd = AsyncFd::new(File::from(OwnedFd::from(fd))).unwrap();
let os = tokio::net::UnixDatagram::from_std(os).unwrap();
let resolver = Resolver::new(|_| panic!("a mesh name went upstream"));
resolver.replace(Some(Zones::new([Zone::new(
ZoneName::new("tsng").unwrap(),
(1..=90).map(|host| ("api".into(), Ipv4Addr::new(10, 1, 2, host))),
)])));
let port = DnsPort::start(address, 1280, resolver, Arc::new(fd));
let mut wire = Wire {
mtu: 1280,
input: None,
output: VecDeque::new(),
};
let mut iface = Interface::new(
Config::new(HardwareAddress::Ip),
&mut wire,
NetTime::from_millis(0),
);
iface.update_ip_addrs(|a| a.push(IpCidr::new(IpAddress::Ipv4(phone), 0)).unwrap());
let mut sockets = SocketSet::new(Vec::new());
let buf = || udp::PacketBuffer::new(vec![udp::PacketMetadata::EMPTY; 4], vec![0; 4096]);
let mut datagram = udp::Socket::new(buf(), buf());
datagram.bind(41000).unwrap();
let mut packet = Packet::new_query(42);
packet.questions.push(Question::new(
Name::new("api.tsng").unwrap(),
TYPE::A.into(),
CLASS::IN.into(),
false,
));
let query = packet.build_bytes_vec().unwrap();
datagram.send_slice(&query, (address, PORT)).unwrap();
let udp = sockets.add(datagram);
let tcp = sockets.add(tcp::Socket::new(
tcp::SocketBuffer::new(vec![0; 8192]),
tcp::SocketBuffer::new(vec![0; 512]),
));
let mut sent = false;
let mut received = Vec::new();
let mut buf = [0; 1500];
let start = Instant::now();
tokio::time::timeout(Duration::from_secs(4), async {
loop {
let now = NetTime::from_millis(start.elapsed().as_millis() as i64);
iface.poll(now, &mut wire, &mut sockets);
if let Ok((reply, from)) = sockets.get_mut::<udp::Socket>(udp).recv() {
assert_eq!(from.endpoint, (address, PORT).into());
let reply = Packet::parse(reply).unwrap();
assert_eq!(reply.id(), 42);
assert!(reply.has_flags(PacketFlag::TRUNCATION | PacketFlag::AUTHORITATIVE_ANSWER));
sockets
.get_mut::<tcp::Socket>(tcp)
.connect(iface.context(), (address, PORT), 41001)
.unwrap();
}
let stream = sockets.get_mut::<tcp::Socket>(tcp);
if stream.can_send() && !sent {
let mut frame = (query.len() as u16).to_be_bytes().to_vec();
frame.extend_from_slice(&query);
assert_eq!(stream.send_slice(&frame).unwrap(), frame.len());
sent = true;
}
while stream.can_recv() {
let n = stream.recv_slice(&mut buf).unwrap();
received.extend_from_slice(&buf[..n]);
}
if let Some(prefix) = received.first_chunk::<2>()
&& received.len() == 2 + usize::from(u16::from_be_bytes(*prefix))
{
break;
}
iface.poll(now, &mut wire, &mut sockets);
for outgoing in wire.output.drain(..) {
assert!(port.intercept(&outgoing, &[phone.into()]));
}
let delay = iface
.poll_delay(now, &sockets)
.map(Duration::from)
.unwrap_or(Duration::from_secs(4));
tokio::select! {
n = os.recv(&mut buf) => wire.input = Some(buf[..n.unwrap()].to_vec()),
_ = tokio::time::sleep(delay) => {}
}
}
})
.await
.expect("DNS over the Android packet device must complete");
let reply = Packet::parse(&received[2..]).unwrap();
assert_eq!(reply.id(), 42);
assert!(!reply.has_flags(PacketFlag::TRUNCATION));
assert_eq!(reply.answers.len(), 90);
}
+13
View File
@@ -0,0 +1,13 @@
//! The Android application. Mesh state belongs to one service-owned Rust agent.
pub mod dns;
pub mod plan;
#[cfg(target_os = "android")]
mod android;
pub mod service;
#[cfg(test)]
mod tests;
#[cfg(unix)]
pub mod tun;
pub mod view;
+85
View File
@@ -0,0 +1,85 @@
//! All addresses and routes installed in the one Android VPN.
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use tsunagi::overlay::Cidr;
/// An exhaustive VpnService configuration, derived from local core policy.
#[derive(Clone, Default, Debug, PartialEq, Eq)]
pub struct VpnPlan {
/// One address in each active, non-overlapping network.
pub addresses: Vec<Cidr>,
/// Payload MTU for every attached network.
pub mtu: u32,
/// Capture IPv4 traffic outside the mesh.
pub full_tunnel: bool,
/// Preferred IPv4 source for the default route.
pub exit: Option<IpAddr>,
/// Capture the limited broadcast when requested by the core.
pub broadcast: bool,
}
impl VpnPlan {
/// Device-local DNS endpoint. Never take an address from a joined mesh.
pub fn dns_address(&self) -> Option<Ipv4Addr> {
if self.addresses.is_empty() {
return None;
}
[
Ipv4Addr::new(192, 0, 2, 53),
Ipv4Addr::new(198, 51, 100, 53),
Ipv4Addr::new(203, 0, 113, 53),
]
.into_iter()
.find(|candidate| {
!self.addresses.iter().any(|cidr| {
let IpAddr::V4(base) = cidr.addr else {
return false;
};
tsunagi::state::Ipv4Range {
base,
prefix_len: cidr.prefix_len,
}
.contains(*candidate)
})
})
}
/// Android uses the first address as primary for unscoped IPv4 traffic.
pub fn addresses_in_order(&self) -> Vec<Cidr> {
let mut ordered = self.addresses.clone();
ordered.sort_by_key(|cidr| (Some(cidr.addr) != self.exit, *cidr));
ordered
}
/// Explicitly route the entire agreed subnet, including its virtual services.
pub fn routes(&self) -> Vec<String> {
let mut routes: Vec<_> = self
.addresses
.iter()
.map(|cidr| {
let p = cidr.prefix_len;
let base = match cidr.addr {
IpAddr::V4(a) => IpAddr::V4(Ipv4Addr::from(
u32::from(a) & u32::MAX.checked_shl(u32::from(32 - p)).unwrap_or(0),
)),
IpAddr::V6(a) => IpAddr::V6(Ipv6Addr::from(
u128::from(a) & u128::MAX.checked_shl(u32::from(128 - p)).unwrap_or(0),
)),
};
format!("{base}/{p}")
})
.collect();
if let Some(dns) = self.dns_address() {
routes.push(format!("{dns}/32"));
}
if self.full_tunnel {
routes.push("0.0.0.0/0".into());
}
if self.broadcast {
routes.push("255.255.255.255/32".into());
}
routes.sort();
routes.dedup();
routes
}
}
+366
View File
@@ -0,0 +1,366 @@
//! Actions and status for the service-owned Rust agent.
use std::{sync::Arc, time::Instant};
use tokio::sync::{mpsc, watch};
use tsunagi::{
Agent, NetworkName, NetworkSecret,
ipc::{DnsReport, PrivilegeReport, ProtocolReport, StatusReport},
vip::VipStatus,
};
use tsunagi_ui::client::Command;
use tsunagi_wg_quic::WireguardPlugin;
use zeroize::Zeroizing;
/// A platform notification or user gesture.
pub enum Request {
/// A command from the same form used by the tray.
Action(Command),
/// The visible activity requested current counters.
Refresh,
/// The physical network changed.
NetworkChanged,
/// Disable only the exit identified by the notification the user tapped.
DisconnectExit {
/// Network id captured in the immutable action.
network: String,
/// Endpoint id captured at the same time.
peer: String,
},
/// Restore a remembered network/peer pair only while no other exit is selected.
RestoreExit {
/// Network saved at the last successful selection.
network: String,
/// Peer used in that network.
peer: String,
},
}
/// A configured default route stays visible if its remote peer goes offline.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExitNotice {
/// Active network identity for the notification action.
pub network: String,
/// Selected remote device identity.
pub peer: String,
/// Human-readable mesh name.
pub network_name: String,
/// Same name shown in the exit chooser.
pub name: String,
/// Whether the peer still offers its exit.
pub online: bool,
}
/// Only an active network with a selected remote exit needs an ongoing notice.
pub fn exit_notice(report: &StatusReport) -> Option<ExitNotice> {
report.networks.iter().filter(|n| n.active).find_map(|n| {
let peer = n.exit.via.as_ref()?;
Some(ExitNotice {
network: n.network_id.clone(),
peer: peer.clone(),
network_name: n.name.clone(),
name: tsunagi_ui::devices::name_of(n, peer),
online: n.exit.via_online,
})
})
}
/// Actions are serialized in the service command loop. An old PendingIntent cannot
/// clear a replacement exit selected in this or another network.
pub async fn disconnect_exit(
agent: &Agent,
network: &str,
peer: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let network = network.parse()?;
let peer = peer.parse()?;
if agent.is_active(network).await && agent.network_status(network).await?.exit_via == Some(peer)
{
agent.set_exit_via(network, None).await?;
}
Ok(())
}
async fn restore_exit(agent: &Agent, network: &str, peer: &str) -> Result<Outcome, String> {
let network = network.parse().map_err(|_| "Invalid saved network ID")?;
let peer = peer.parse().map_err(|_| "Invalid saved peer ID")?;
let status = agent.status().await.map_err(|e| e.to_string())?;
for n in &status.networks {
if n.state == tsunagi::agent::NetworkState::Active
&& let Some(current) = n.exit_via
{
return if n.network_id == network && current == peer {
Ok(Outcome::Applied)
} else {
Err("Another exit is already selected".into())
};
}
}
agent
.set_exit_via(network, Some(peer))
.await
.map_err(|e| e.to_string())?;
Ok(Outcome::Applied)
}
// On cold start the first snapshot often precedes peer discovery. Wait on the
// service's roster notifications, outside the command loop, then let the usual
// serialized command validate the selection again before touching the route.
#[cfg(any(target_os = "android", test))]
pub(crate) async fn wait_for_exit_offer(
state: &mut watch::Receiver<State>,
network: &str,
peer: &str,
) -> Result<(), String> {
tokio::time::timeout(std::time::Duration::from_secs(15), async {
loop {
match &*state.borrow_and_update() {
State::Ready(report, _) => {
let n = report
.networks
.iter()
.find(|n| n.network_id == network && n.active)
.ok_or("The saved exit network is no longer active")?;
if report
.networks
.iter()
.any(|n| n.active && n.exit.via.is_some())
|| n.peers.iter().any(|p| p.endpoint_id == peer && p.exit_node)
{
return Ok(());
}
}
State::Off => return Err("Tsunagi Agent stopped".into()),
State::Error(error) => return Err(error.clone()),
State::Starting => {}
}
state.changed().await.map_err(|_| "Tsunagi Agent stopped")?;
}
})
.await
.map_err(|_| "The saved peer is offline or no longer offers an exit")?
}
/// Private reply delivered only to the UI that requested the action.
pub enum Outcome {
/// The agent has applied the action.
Applied,
/// Revisions returned by a successful signed write.
Saved(Vec<VipStatus>),
/// A user-requested, single-use clipboard export.
Clipboard(Zeroizing<String>),
}
/// Delivery channel for a request.
pub type Reply = tokio::sync::oneshot::Sender<Result<Outcome, String>>;
/// Pending acknowledgement of a UI action.
pub type Response = tokio::sync::oneshot::Receiver<Result<Outcome, String>>;
/// Execute exactly the selection and revision supplied by the form.
pub async fn apply(
command: Command,
agent: &Agent,
) -> Result<Outcome, Box<dyn std::error::Error + Send + Sync>> {
match command {
Command::Join { name, secret } => {
agent
.join_network(&NetworkName::new(name)?, &NetworkSecret::decode(&secret)?)
.await?;
}
Command::SetActive { network_id, active } => {
let id = network_id.parse()?;
if active {
agent.switch_network(id).await?;
} else {
agent.pause_network(id).await?;
}
}
Command::Leave { network_id } => {
agent.leave_network(network_id.parse()?).await?;
}
Command::SetBroadcast {
network_id,
enabled,
} => agent.set_broadcast(network_id.parse()?, enabled).await?,
Command::SetProtocols {
network_id,
protocols,
} => agent.set_protocols(network_id.parse()?, protocols).await?,
Command::SetHostname(hostname) => {
agent.set_hostname(&hostname).await?;
}
Command::ForgetNode {
network_id,
peer,
expected_version,
} => {
agent
.forget_node(network_id.parse()?, peer.parse()?, expected_version)
.await?;
}
Command::SetExitNode { network_id, peer } => {
agent
.set_exit_via(network_id.parse()?, peer.map(|p| p.parse()).transpose()?)
.await?
}
Command::SetExitOffer { .. } => {
return Err("This phone can only use a remote exit node.".into());
}
Command::SaveVip {
network_id,
config,
expected,
delete,
..
} => {
return Ok(Outcome::Saved(
agent
.save_vip(network_id.parse()?, config, expected, delete)
.await?,
));
}
Command::CopySecret { network_id } => {
return Ok(Outcome::Clipboard(
agent.network_secret(network_id.parse()?).await?.encode(),
));
}
}
Ok(Outcome::Applied)
}
/// State visible to an activity which may be recreated while the service runs.
#[derive(Clone, Default)]
pub enum State {
/// The user can start the VPN.
#[default]
Off,
/// Opening the endpoint or waiting for connectivity.
Starting,
/// The last complete snapshot and its monotonic observation time.
Ready(Arc<StatusReport>, Instant),
/// Actionable startup or status error.
Error(String),
}
/// Build the same network and counter reports used by the desktop client.
pub async fn report(
agent: &Agent,
wg: Option<&WireguardPlugin>,
dns: &crate::dns::Resolver,
) -> tsunagi::Result<StatusReport> {
snapshot(agent, wg, dns, None).await
}
async fn snapshot(
agent: &Agent,
wg: Option<&WireguardPlugin>,
dns: &crate::dns::Resolver,
cached_zones: Option<DnsReport>,
) -> tsunagi::Result<StatusReport> {
let status = agent.status().await?;
let overlay = agent.overlay();
Ok(StatusReport {
networks: tsunagi_runtime::report::networks(&status, overlay.as_ref(), wg),
overlay_config_error: overlay.and_then(|state| state.address_error),
dns: Some(dns.with_listener(cached_zones.unwrap_or_else(|| dns.refresh(&status.networks)))),
endpoint_id: status.endpoint_id.to_string(),
hostname: status.hostname,
bound_sockets: status
.bound_sockets
.iter()
.map(ToString::to_string)
.collect(),
cache_healthy: status.cache_healthy,
available_protocols: tsunagi_runtime::PROTOCOLS
.iter()
.map(|spec| ProtocolReport {
name: spec.name.into(),
summary: spec.summary.into(),
})
.collect(),
protocols: tsunagi_runtime::PROTOCOLS
.iter()
.map(|spec| format!("{} v{}", spec.name, spec.version))
.collect(),
privilege: PrivilegeReport::Available,
version: env!("CARGO_PKG_VERSION").into(),
..Default::default()
})
}
/// Drive the agent until Android stops this service instance.
pub async fn serve(
agent: Agent,
wg: Arc<WireguardPlugin>,
dns: crate::dns::Resolver,
mut commands: mpsc::Receiver<(Request, Reply)>,
state: &watch::Sender<State>,
mut stop: watch::Receiver<bool>,
mut publish_exit: impl FnMut(Option<&ExitNotice>),
) {
let mut roster = agent.watch_roster();
roster.mark_changed(); // Load the initial zones before waiting for any actions.
let mut cached_zones = None;
let mut retry = false;
let mut published_exit = None;
loop {
let (reply, mut refresh_zones) = tokio::select! {
biased;
_ = async { drop(stop.wait_for(|stopped| *stopped).await) } => break,
command = commands.recv() => {
let Some((request, reply)) = command else { break };
let refresh_zones = !matches!(request, Request::Refresh);
let result = match request {
Request::Refresh => Ok(Outcome::Applied),
Request::Action(cmd) => {
if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) {
dns.replace(None);
}
apply(cmd, &agent).await.map_err(|e| e.to_string())
}
Request::NetworkChanged => {
agent.endpoint().network_change().await;
agent.recheck().await;
Ok(Outcome::Applied)
}
Request::DisconnectExit {network, peer} => disconnect_exit(&agent, &network, &peer).await
.map(|()| Outcome::Applied).map_err(|e| e.to_string()),
Request::RestoreExit {network, peer} => restore_exit(&agent, &network, &peer).await,
};
(Some((reply, result)), refresh_zones)
}
changed = roster.changed() => {
if changed.is_err() { break; }
(None, true)
}
_ = tokio::time::sleep(std::time::Duration::from_secs(2)), if retry => (None, true),
};
// A command may itself have changed the roster. Consume notifications
// before taking the snapshot so changes during the read stay pending.
refresh_zones |= roster.has_changed().unwrap_or(false);
if refresh_zones {
roster.borrow_and_update();
cached_zones = None;
}
state.send_replace(
match snapshot(&agent, Some(&wg), &dns, cached_zones.take()).await {
Ok(report) => {
retry = false;
cached_zones.clone_from(&report.dns);
let notice = exit_notice(&report);
if published_exit.as_ref() != Some(&notice) {
publish_exit(notice.as_ref());
published_exit = Some(notice);
}
State::Ready(Arc::new(report), Instant::now())
}
Err(error) => {
retry = true;
State::Error(error.to_string())
}
},
);
if let Some((reply, outcome)) = reply {
let _ = reply.send(outcome);
}
}
agent.shutdown().await;
}
+929
View File
@@ -0,0 +1,929 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::plan::VpnPlan;
use std::net::{IpAddr, Ipv4Addr};
use tsunagi::overlay::Cidr;
fn addr(octet: u8) -> Cidr {
Cidr::new(IpAddr::V4(Ipv4Addr::new(10, octet, 42, 19)), 24).unwrap()
}
#[tokio::test]
async fn a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand() {
use crate::service::{Request, State, serve};
use std::time::Duration;
use tokio::sync::{mpsc, oneshot, watch};
use tsunagi::{
discovery::SharedMemoryDiscovery,
testing::{TestAgent, network},
};
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
let discovery = SharedMemoryDiscovery::new();
let phone = TestAgent::spawn(&discovery).await.unwrap();
let wg = WireguardPlugin::open(WireguardConfig::new(phone.dir.path().join("wg")))
.await
.unwrap();
let (state, mut snapshots) = watch::channel(State::Starting);
let (stop, stopped) = watch::channel(false);
let (commands, requests) = mpsc::channel(4);
let agent = phone.agent.clone();
let task = tokio::spawn(async move {
serve(
agent,
wg,
crate::dns::Resolver::new(|_| None),
requests,
&state,
stopped,
|_| {},
)
.await;
});
tokio::time::timeout(Duration::from_secs(5), snapshots.changed())
.await
.unwrap()
.unwrap();
assert!(matches!(*snapshots.borrow_and_update(), State::Ready(..)));
assert!(
tokio::time::timeout(Duration::from_millis(2200), snapshots.changed())
.await
.is_err(),
"a hidden, idle service rebuilt the status"
);
let (tx, rx) = oneshot::channel();
commands.send((Request::Refresh, tx)).await.unwrap();
rx.await.unwrap().unwrap();
assert!(snapshots.has_changed().unwrap());
let (name, secret) = network("background-mesh");
phone.agent.join_network(&name, &secret).await.unwrap();
tokio::time::timeout(Duration::from_secs(5), snapshots.wait_for(|s| {
matches!(s, State::Ready(r, _) if r.dns.as_ref().is_some_and(|d| d.zones.iter().any(|z| z == "background-mesh")))
})).await.unwrap().unwrap();
stop.send_replace(true);
task.await.unwrap();
}
#[tokio::test]
async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_current_route() {
use crate::service::{ExitNotice, Request, State, disconnect_exit, serve, wait_for_exit_offer};
use tokio::sync::{mpsc, oneshot, watch};
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
async fn notice_matching(
notices: &mut watch::Receiver<Option<ExitNotice>>,
predicate: impl Fn(&Option<ExitNotice>) -> bool,
) -> Option<ExitNotice> {
tokio::time::timeout(
std::time::Duration::from_secs(5),
notices.wait_for(predicate),
)
.await
.unwrap()
.unwrap()
.clone()
}
use tsunagi::{
discovery::SharedMemoryDiscovery,
testing::{TestAgent, network, wait_until},
};
let discovery = SharedMemoryDiscovery::new();
let phone = TestAgent::spawn(&discovery).await.unwrap();
let rules = std::sync::Arc::new(tsunagi::overlay::MockHostRules::new());
let tuns = tsunagi::overlay::MemoryTunFactory::new().with_host_rules(rules);
let exit = TestAgent::spawn_with(
|cfg| cfg.with_interface(std::sync::Arc::new(tuns), "gateway", 1280),
&discovery,
)
.await
.unwrap();
let (name, secret) = network("travel");
let id = phone.agent.join_network(&name, &secret).await.unwrap();
exit.agent.set_hostname("gateway").await.unwrap();
exit.agent.join_network(&name, &secret).await.unwrap();
exit.agent.set_exit_offer(id, true).await.unwrap();
let peer = exit.agent.endpoint_id();
wait_until("authenticated exit offer", || async {
phone
.agent
.network_status(id)
.await
.ok()?
.peers
.iter()
.any(|p| p.endpoint_id == peer && p.exit_node)
.then_some(())
})
.await;
let wg = WireguardPlugin::open(WireguardConfig::new(phone.dir.path().join("wg")))
.await
.unwrap();
let agent = phone.agent.clone();
let (commands, requests) = mpsc::channel(4);
let (stop, stopped) = watch::channel(false);
let (published, mut notices) = watch::channel(None);
let (state, mut live) = watch::channel(State::Starting);
let task = tokio::spawn(async move {
serve(
agent,
wg,
crate::dns::Resolver::new(|_| None),
requests,
&state,
stopped,
|notice| {
published.send_replace(notice.cloned());
},
)
.await;
});
phone.agent.set_exit_via(id, Some(peer)).await.unwrap();
let notice = notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| n.online))
.await
.unwrap();
assert_eq!(notice.name, "gateway");
assert_eq!(notice.network_name, "travel");
assert!(notice.online);
let restore = |peer: String| {
let commands = commands.clone();
let network = notice.network.clone();
async move {
let (reply, result) = oneshot::channel();
commands
.send((Request::RestoreExit { network, peer }, reply))
.await
.unwrap();
result.await.unwrap()
}
};
disconnect_exit(&phone.agent, &notice.network, &notice.peer)
.await
.unwrap();
notice_matching(&mut notices, Option::is_none).await;
assert!(
restore(phone.agent.endpoint_id().to_string())
.await
.is_err()
);
assert!(
phone
.agent
.network_status(id)
.await
.unwrap()
.exit_via
.is_none()
);
// A cold service can publish its first status before the gateway advertises.
// Keep the command loop available while waiting for this exact peer.
exit.agent.set_exit_offer(id, false).await.unwrap();
drop(
tokio::time::timeout(
std::time::Duration::from_secs(5),
live.wait_for(|s| {
matches!(s, State::Ready(report, _) if
report.networks[0].peers.iter().any(|p| p.endpoint_id == notice.peer && !p.exit_node))
}),
)
.await
.unwrap()
.unwrap(),
);
let waiting = wait_for_exit_offer(&mut live, &notice.network, &notice.peer);
tokio::pin!(waiting);
tokio::select! {
biased;
_ = &mut waiting => panic!("restored before the peer offered an exit"),
result = exit.agent.set_exit_offer(id, true) => result.unwrap(),
}
waiting.await.unwrap();
assert!(restore(notice.peer.clone()).await.is_ok());
notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| n.online)).await;
assert!(
restore(phone.agent.endpoint_id().to_string())
.await
.is_err()
);
disconnect_exit(
&phone.agent,
&id.to_string(),
&phone.agent.endpoint_id().to_string(),
)
.await
.unwrap();
assert_eq!(
phone.agent.network_status(id).await.unwrap().exit_via,
Some(peer)
);
exit.agent.set_hostname("renamed-gateway").await.unwrap();
notice_matching(&mut notices, |n| {
n.as_ref().is_some_and(|n| n.name == "renamed-gateway")
})
.await;
exit.stop().await;
notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| !n.online)).await;
disconnect_exit(&phone.agent, &notice.network, &notice.peer)
.await
.unwrap();
notice_matching(&mut notices, Option::is_none).await;
assert!(phone.agent.is_active(id).await);
stop.send_replace(true);
task.await.unwrap();
}
#[tokio::test]
async fn vpn_dns_answers_hosts_and_vips_in_each_zone_and_only_forwards_external_names() {
use crate::dns::Resolver;
use simple_dns::{CLASS, Name, Packet, PacketFlag, Question, RCODE, TYPE, rdata::RData};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use tsunagi::dns::{Zone, ZoneName, Zones};
fn query(name: &str, kind: TYPE) -> Vec<u8> {
let mut packet = Packet::new_query(119);
packet.set_flags(PacketFlag::RECURSION_DESIRED);
packet.questions.push(Question::new(
Name::new(name).unwrap(),
kind.into(),
CLASS::IN.into(),
false,
));
packet.build_bytes_vec().unwrap()
}
let calls = Arc::new(AtomicUsize::new(0));
let forwarded = calls.clone();
let resolver = Resolver::new(move |wire| {
forwarded.fetch_add(1, Ordering::Relaxed);
let query = Packet::parse(wire).unwrap();
let mut answer = Packet::new_reply(999);
answer.questions = query.questions;
answer.build_bytes_vec().ok()
});
let private = query("k8s.tsng", TYPE::A);
let answer = resolver.answer(&private).await.unwrap();
assert_eq!(
Packet::parse(&answer).unwrap().rcode(),
RCODE::ServerFailure
);
let lab = |name, members| Zone::new(ZoneName::new(name).unwrap(), members);
resolver.replace(Some(Zones::new([
lab(
"tsng",
vec![
("ai".into(), [10, 1, 1, 100].into()),
("k8s".into(), [10, 1, 1, 106].into()),
],
),
lab("lab", vec![("ai".into(), [10, 2, 1, 100].into())]),
])));
for (name, ip) in [
("AI.TSNG", [10, 1, 1, 100]),
("k8s.tsng", [10, 1, 1, 106]),
("ai.lab", [10, 2, 1, 100]),
] {
let reply = resolver.answer(&query(name, TYPE::A)).await.unwrap();
let packet = Packet::parse(&reply).unwrap();
assert!(packet.has_flags(PacketFlag::AUTHORITATIVE_ANSWER));
assert!(
matches!(&packet.answers[0].rdata, RData::A(a) if Ipv4Addr::from(a.address) == Ipv4Addr::from(ip))
);
}
for (name, kind, code) in [
("missing.tsng", TYPE::A, RCODE::NameError),
("k8s.tsng", TYPE::AAAA, RCODE::NoError),
] {
let reply = resolver.answer(&query(name, kind)).await.unwrap();
let packet = Packet::parse(&reply).unwrap();
assert_eq!(packet.rcode(), code);
assert!(packet.answers.is_empty());
assert!(packet.has_flags(PacketFlag::AUTHORITATIVE_ANSWER));
}
assert!(resolver.answer(b"invalid").await.is_none());
assert_eq!(calls.load(Ordering::Relaxed), 0);
let reply = resolver
.answer(&query("example.org", TYPE::HTTPS))
.await
.unwrap();
let packet = Packet::parse(&reply).unwrap();
assert_eq!(packet.id(), 119);
assert_eq!(packet.questions[0].qtype, TYPE::HTTPS.into());
assert_eq!(calls.load(Ordering::Relaxed), 1);
}
#[test]
fn local_dns_address_is_routed_and_cannot_claim_an_overlay_ip() {
let mut plan = VpnPlan {
addresses: vec![addr(1)],
..Default::default()
};
let dns = plan.dns_address().unwrap();
assert!(plan.routes().contains(&format!("{dns}/32")));
plan.addresses.push(Cidr::new(dns.into(), 24).unwrap());
let other = plan.dns_address().unwrap();
assert_ne!(other, dns);
assert!(plan.routes().contains(&format!("{other}/32")));
plan.addresses.clear();
assert!(plan.dns_address().is_none());
}
#[tokio::test]
async fn service_dns_tracks_signed_hostnames_vip_deletion_and_reverse_ranges() {
use tsunagi::{
Agent,
dns::{Answer, Query, RosterZones},
testing,
vip::VipConfig,
};
let dir = tempfile::tempdir().unwrap();
let agent = Agent::spawn(testing::local_config(dir.path()))
.await
.unwrap();
let (network, secret) = testing::network("tsng");
let id = agent.join_network(&network, &secret).await.unwrap();
agent.set_hostname("worker").await.unwrap();
let vip = agent
.save_vip(id, VipConfig::new("k8s"), None, false)
.await
.unwrap()
.remove(0);
let status = agent.status().await.unwrap();
let roster = RosterZones::from_networks(&status.networks);
let worker = status.networks[0]
.members
.iter()
.find(|m| m.hostname.as_deref() == Some("worker"))
.unwrap()
.overlay_address_v4
.unwrap();
for (name, ip) in [("worker.tsng", worker), ("k8s.tsng", vip.address.unwrap())] {
assert_eq!(
roster.zones.lookup(name, Query::A).unwrap().1,
Answer::Addresses(vec![ip])
);
let [a, b, c, d] = ip.octets();
assert_eq!(
roster
.zones
.lookup(&format!("{d}.{c}.{b}.{a}.in-addr.arpa"), Query::Ptr)
.unwrap()
.1,
Answer::Name(name.into())
);
}
assert!(
roster
.zones
.lookup("8.8.8.8.in-addr.arpa", Query::Ptr)
.is_none()
);
agent
.save_vip(id, vip.config, Some(vip.revision), true)
.await
.unwrap();
let zones = RosterZones::from_networks(&agent.status().await.unwrap().networks).zones;
assert_eq!(
zones.lookup("k8s.tsng", Query::A).unwrap().1,
Answer::NoSuchName
);
agent.shutdown().await;
}
#[test]
fn changing_the_exit_keeps_every_mesh_route_and_prefers_the_selected_source() {
let first = addr(2);
let second = addr(5);
let mut plan = VpnPlan {
addresses: vec![first, second],
mtu: 1280,
..Default::default()
};
assert_eq!(
plan.routes(),
["10.2.42.0/24", "10.5.42.0/24", "192.0.2.53/32"]
);
assert_eq!(plan.addresses_in_order(), [first, second]);
plan.full_tunnel = true;
plan.exit = Some(second.addr);
assert_eq!(plan.addresses_in_order(), [second, first]);
assert!(plan.routes().contains(&"0.0.0.0/0".into()));
assert!(plan.routes().contains(&"10.2.42.0/24".into()));
plan.full_tunnel = false;
plan.exit = None;
plan.addresses.remove(0);
assert_eq!(plan.routes(), ["10.5.42.0/24", "192.0.2.53/32"]);
}
#[test]
fn broadcast_route_is_only_present_when_requested() {
let mut plan = VpnPlan {
addresses: vec![addr(1)],
mtu: 1280,
..Default::default()
};
plan.broadcast = true;
assert!(plan.routes().contains(&"255.255.255.255/32".into()));
plan.broadcast = false;
assert_eq!(plan.routes(), ["10.1.42.0/24", "192.0.2.53/32"]);
}
#[tokio::test]
async fn all_four_desktop_carriers_register_and_each_network_keeps_its_preference() {
use tsunagi::{Agent, testing};
use tsunagi_runtime::{Carriers, PROTOCOLS};
let dir = tempfile::tempdir().unwrap();
let names = ["wg", "awg", "wg-quic", "tcp-tls"];
let (network, secret) = testing::network("carriers");
for restart in [false, true] {
let config = testing::local_config(dir.path());
let (config, carriers) = Carriers::configure(config, &[], None, |spec| {
if spec.name == "tcp-tls" {
vec![("port".into(), "0".into())]
} else {
Vec::new()
}
})
.await
.unwrap();
assert_eq!(
config
.carriers
.iter()
.map(|c| c.protocol_id())
.collect::<Vec<_>>(),
names
);
assert!(
config
.carriers
.iter()
.zip(PROTOCOLS)
.all(|(c, spec)| c.protocol_version() == spec.version)
);
let agent = Agent::spawn(config).await.unwrap();
let _listeners = carriers.listen(&agent);
let id = agent.join_network(&network, &secret).await.unwrap();
let saved = agent.network_status(id).await.unwrap().protocols;
if restart {
assert_eq!(saved, ["tcp-tls", "wg"]);
} else {
assert_eq!(saved, names);
agent
.set_protocols(id, vec!["tcp-tls".into(), "wg".into()])
.await
.unwrap();
let (other, secret) = testing::network("other");
let second = agent.join_network(&other, &secret).await.unwrap();
assert_eq!(agent.network_status(second).await.unwrap().protocols, names);
}
agent.shutdown().await;
}
}
#[tokio::test]
async fn commands_scope_vip_edits_and_leaving_to_the_selected_network() {
use crate::service::apply;
use tsunagi::vip::VipConfig;
use tsunagi::{Agent, NetworkName, NetworkSecret, testing};
use tsunagi_ui::client::Command;
let dir = tempfile::tempdir().unwrap();
let agent = Agent::spawn(testing::local_config(dir.path()))
.await
.unwrap();
let name = NetworkName::new("shared-name").unwrap();
let one = NetworkSecret::generate();
let two = NetworkSecret::generate();
for secret in [&one, &two] {
apply(
Command::Join {
name: name.to_string(),
secret: secret.encode(),
},
&agent,
)
.await
.unwrap();
}
let first = tsunagi::identity::NetworkKeys::derive(&name, &one)
.network_id()
.to_string();
let second = tsunagi::identity::NetworkKeys::derive(&name, &two).network_id();
let config = VipConfig::new("web");
let save = |expected, delete| Command::SaveVip {
token: "draft".into(),
network_id: first.clone(),
config: config.clone(),
expected,
delete,
};
apply(save(None, false), &agent).await.unwrap();
assert!(
apply(save(Some("stale".into()), true), &agent)
.await
.is_err()
);
assert_eq!(
agent
.network_status(first.parse().unwrap())
.await
.unwrap()
.vips
.len(),
1
);
assert!(agent.network_status(second).await.unwrap().vips.is_empty());
assert!(
apply(
Command::SetExitNode {
network_id: second.to_string(),
peer: Some(agent.endpoint_id().to_string())
},
&agent
)
.await
.is_err()
);
assert!(
apply(
Command::SetExitOffer {
network_id: second.to_string(),
enabled: true
},
&agent
)
.await
.is_err()
);
apply(Command::Leave { network_id: first }, &agent)
.await
.unwrap();
let saved = agent.list_networks().await.unwrap();
assert_eq!(saved.len(), 1);
assert_eq!(saved[0].network_id, second);
agent.shutdown().await;
}
#[cfg(unix)]
#[tokio::test]
async fn tun_reader_survives_address_changes_failed_establish_and_last_network_leaving() {
use std::io;
use std::os::{fd::OwnedFd, unix::net::UnixDatagram};
use std::sync::{Arc, Mutex};
use tsunagi::overlay::{TunFactory, TunRequest};
let sockets = Arc::new(Mutex::new(Vec::new()));
let peers = sockets.clone();
let factory = crate::tun::AndroidTun::new(
crate::dns::Resolver::new(|_| None),
move |plan| {
if plan.addresses.contains(&addr(9)) {
return Err(io::Error::other("permission revoked"));
}
let (dev, os) = UnixDatagram::pair()?;
dev.set_nonblocking(true)?;
peers.lock().unwrap().push(os);
Ok(OwnedFd::from(dev).into())
},
|_, _| Ok(()),
);
let mut req = TunRequest::bare("tsun0", 1280);
let dev = factory.create(req.clone()).await.unwrap();
let reader = tokio::spawn({
let dev = dev.clone();
async move { dev.recv().await.unwrap() }
});
req.addresses = vec![addr(2)];
factory.reconfigure(req.clone()).await.unwrap();
assert_eq!(factory.assigned_addresses(), [addr(2).addr]);
req.addresses.push(addr(9));
assert!(factory.reconfigure(req.clone()).await.is_err());
assert_eq!(factory.assigned_addresses(), [addr(2).addr]);
sockets
.lock()
.unwrap()
.last()
.unwrap()
.send(b"first")
.unwrap();
assert_eq!(
&tokio::time::timeout(std::time::Duration::from_secs(2), reader)
.await
.unwrap()
.unwrap()[..],
b"first"
);
req.addresses.clear();
factory.reconfigure(req.clone()).await.unwrap();
assert!(
dev.send(bytes::Bytes::from_static(b"offline"))
.await
.is_err()
);
assert!(factory.assigned_addresses().is_empty());
req.addresses = vec![addr(5)];
factory.reconfigure(req).await.unwrap();
sockets
.lock()
.unwrap()
.last()
.unwrap()
.send(b"second")
.unwrap();
assert_eq!(&dev.recv().await.unwrap()[..], b"second");
}
#[tokio::test]
async fn network_cards_start_closed_and_keep_exit_traffic_visible_when_folded() {
use crate::{
service::{State, report},
view::{Phone, configure},
};
use egui::epaint::Shape;
use std::{sync::Arc, time::Instant};
let dir = tempfile::tempdir().unwrap();
let agent = tsunagi::Agent::spawn(tsunagi::testing::local_config(dir.path()))
.await
.unwrap();
let (name, secret) = tsunagi::testing::network("layout");
agent.join_network(&name, &secret).await.unwrap();
let mut sample = report(&agent, None, &crate::dns::Resolver::new(|_| None))
.await
.unwrap();
sample.networks[0].overlay = Some(tsunagi::ipc::OverlayReport {
address: Some("10.1.2.3".into()),
..Default::default()
});
let mut other = sample.networks[0].clone();
other.network_id = "another-network".into();
sample.networks.push(other);
sample.networks[0].peers.push(tsunagi::ipc::PeerReport {
endpoint_id: "exit-endpoint-id".into(),
hostname: Some("gateway".into()),
..Default::default()
});
sample.networks[0].exit = tsunagi::ipc::ExitReport {
via: Some("exit-endpoint-id".into()),
via_online: true,
traffic: Some(tsunagi::overlay::exit::ExitTraffic {
tx_bytes: 2048,
rx_bytes: 512,
}),
client_rules: Some(tsunagi::ipc::RuleSetReport {
ok: true,
detail: String::new(),
}),
..Default::default()
};
let state = State::Ready(Arc::new(sample), Instant::now());
let ctx = egui::Context::default();
configure(&ctx);
let mut phone = Phone::default();
let mut frame = |events| {
ctx.run(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(360., 720.),
)),
events,
..Default::default()
},
|ctx| {
phone.draw(ctx, &state, |_| {
panic!("drawing the overview issued a command")
});
},
)
};
let positions = |frame: &egui::FullOutput, label: &str| {
frame
.shapes
.iter()
.filter_map(|shape| match &shape.shape {
Shape::Text(text) if text.galley.text() == label => {
Some(text.pos + text.galley.rect.center().to_vec2())
}
_ => None,
})
.collect::<Vec<_>>()
};
frame(vec![]);
let closed = frame(vec![]);
let titles = positions(&closed, name.as_str());
assert_eq!(titles.len(), 2);
assert!(positions(&closed, "Show devices").is_empty());
use egui_phosphor::regular::{ARROW_DOWN, ARROW_UP};
let font = egui::TextStyle::Body.resolve(&ctx.style());
for icon in [ARROW_UP, ARROW_DOWN] {
assert!(ctx.fonts(|fonts| fonts.has_glyphs(&font, icon)));
}
for label in [
"Exit via gateway".to_owned(),
format!("{ARROW_UP} 2.0 kB"),
format!("{ARROW_DOWN} 512 B"),
] {
assert_eq!(positions(&closed, &label).len(), 1, "missing {label}");
}
let mut click = |pos| {
for pressed in [true, false] {
frame(vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
},
]);
}
frame(vec![])
};
let opened = click(titles[0]);
assert_eq!(positions(&opened, "Show devices").len(), 1);
use egui_phosphor::regular as icon;
let vip = format!("{} VIP", icon::NETWORK);
let y = |label: &str| positions(&opened, label)[0].y;
assert!((0.0..=26.0).contains(&(y(icon::DESKTOP_TOWER) - y(icon::FINGERPRINT))));
assert!((0.0..=26.0).contains(&(y(icon::TREE_STRUCTURE) - y(icon::HASH))));
assert!((0.0..=26.0).contains(&(y(icon::DEVICES) - y(icon::DEVICE_MOBILE))));
assert!((y(&vip) - y("Show devices")).abs() < 2.0);
assert!((y(&vip) - y(&format!("{} Copy secret", egui_phosphor::regular::COPY))).abs() < 2.0);
let folded = click(positions(&opened, name.as_str())[0]);
assert!(positions(&folded, "Show devices").is_empty());
assert_eq!(positions(&folded, "Exit via gateway").len(), 1);
agent.shutdown().await;
}
#[test]
fn the_system_tile_waits_for_the_agent_and_distinguishes_networks_with_the_same_name() {
use crate::{
service::State,
view::{Phone, configure},
};
use std::{sync::Arc, time::Instant};
use tsunagi::ipc::{NetworkReport, StatusReport};
let ctx = egui::Context::default();
configure(&ctx);
let mut phone = Phone::default();
let draw = |phone: &mut Phone, state: &State| {
let out = ctx.run(egui::RawInput::default(), |ctx| {
phone.draw(ctx, state, |_| panic!("opening the tile selected a route"));
});
out.shapes
.into_iter()
.filter_map(|s| match s.shape {
egui::Shape::Text(t) => Some(t.galley.text().to_owned()),
_ => None,
})
.collect::<Vec<_>>()
};
phone.request_exit_picker();
draw(&mut phone, &State::Starting);
let networks =
[("alpha", true), ("bravo", true), ("paused", false)].map(|(id, active)| NetworkReport {
network_id: id.into(),
name: "home".into(),
active,
..Default::default()
});
let state = State::Ready(
Arc::new(StatusReport {
networks: networks.into(),
..Default::default()
}),
Instant::now(),
);
draw(&mut phone, &state);
let chooser = draw(&mut phone, &state);
assert!(chooser.iter().any(|s| s == "home · alpha"));
assert!(chooser.iter().any(|s| s == "home · bravo"));
assert!(!chooser.iter().any(|s| s.contains("paused")));
assert!(phone.back().is_none());
assert!(draw(&mut phone, &state).iter().any(|s| s == "tsunagi"));
}
#[test]
fn rotating_the_phone_keeps_the_selected_network_and_unsaved_vip_draft() {
use crate::service::State;
use crate::view::{Phone, configure};
use egui::{Event, PointerButton, Pos2, RawInput, Rect, Shape};
use std::{sync::Arc, time::Instant};
use tsunagi::{
ipc::{NetworkReport, StatusReport},
vip::{
Backend, BackendStatus, Counters, Listener, ListenerStatus, Protocol, VipConfig,
VipStatus,
},
};
let backend = Backend {
peer: "node".into(),
port: 8080,
};
let mut config = VipConfig::new("web");
let name_field = egui::Id::new(("vip-name", &config.id));
let mut listener = Listener::new(Protocol::Tcp, 80);
listener.backends.push(backend.clone());
config.listeners.push(listener);
let network = NetworkReport {
active: true,
name: "lab".into(),
network_id: "network".into(),
vips: vec![VipStatus {
config,
address: None,
revision: "r1".into(),
error: None,
listeners: vec![ListenerStatus {
protocol: Protocol::Tcp,
port: 80,
selected: Some(backend.clone()),
counters: Counters::default(),
backends: vec![BackendStatus {
backend,
state: "ready".into(),
rtt_us: Some(1000),
measurement_age_ms: Some(1),
active_flows: 1,
counters: Counters::default(),
}],
}],
}],
..Default::default()
};
let state = State::Ready(
Arc::new(StatusReport {
networks: vec![network],
..Default::default()
}),
Instant::now(),
);
let ctx = egui::Context::default();
configure(&ctx);
let mut phone = Phone::default();
let size = std::cell::Cell::new(egui::vec2(360., 800.));
let mut frame = |events| {
ctx.run(
RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size.get())),
events,
..Default::default()
},
|ctx| {
phone.draw(ctx, &state, |_| panic!("navigation wrote to the network"));
},
)
};
let position = |output: &egui::FullOutput, label: &str| {
output
.shapes
.iter()
.find_map(|s| match &s.shape {
Shape::Text(t) if t.galley.text() == label => {
Some(t.pos + t.galley.rect.center().to_vec2())
}
_ => None,
})
.unwrap_or_else(|| panic!("missing {label}"))
};
let mut click = |label: &str| {
frame(vec![]);
let p = position(&frame(vec![]), label);
for pressed in [true, false] {
frame(vec![
Event::PointerMoved(p),
Event::PointerButton {
pos: p,
button: PointerButton::Primary,
pressed,
modifiers: Default::default(),
},
]);
}
frame(vec![])
};
click("lab");
size.set(egui::vec2(800., 360.));
let live = click(&format!("{} VIP", egui_phosphor::regular::NETWORK));
for label in ["Overview", "Configuration", "web.lab", "node:8080"] {
let p = position(&live, label);
assert!(
(0.0..800.0).contains(&p.x),
"{label} is outside the landscape view"
);
}
let editor = click("Configuration");
position(&editor, "Name");
ctx.memory_mut(|m| m.request_focus(name_field));
frame(vec![Event::Text("-draft".into())]);
size.set(egui::vec2(360., 800.));
let editor_portrait = frame(vec![]);
position(&editor_portrait, "Unsaved changes");
assert!(editor_portrait.shapes.iter().any(|s| matches!(&s.shape,
Shape::Text(t) if t.galley.text().contains("-draft"))));
for label in [
"Active TCP port checks",
"Checks and flow expiry",
"+ Backend",
"+ Listener",
] {
position(&editor_portrait, label);
}
}
+343
View File
@@ -0,0 +1,343 @@
//! A stable packet device over the file descriptors replaced by VpnService.
use crate::dns::{Resolver, stack::DnsPort};
use crate::plan::VpnPlan;
use bytes::Bytes;
use std::{
fmt,
fs::File,
io::{self, Read, Write},
sync::{Arc, Mutex as StdMutex},
};
use tokio::{
io::unix::AsyncFd,
sync::{Mutex, watch},
};
use tsunagi::{
BoxFuture,
overlay::{
OverlayError, TunDevice, TunFactory, TunRequest,
hostrules::{
BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, ExitHostPlan,
ExitHostReport, ExitHostRules, RuleOutcome,
},
source::{SourceFlows, SourceMode},
},
};
type Establish = dyn Fn(&VpnPlan) -> io::Result<File> + Send + Sync;
type BindSocket =
dyn Fn(&tokio::net::TcpSocket, std::net::Ipv4Addr) -> io::Result<()> + Send + Sync;
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>>;
/// The only OS call is supplied by the Android service. Tokio owns the detached fd.
#[derive(Clone)]
pub struct AndroidTun(Arc<Inner>);
struct Inner {
establish: Box<Establish>,
bind: Box<BindSocket>,
resolver: Resolver,
plan: Mutex<VpnPlan>,
current: watch::Sender<Descriptor>,
}
impl fmt::Debug for AndroidTun {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AndroidTun")
}
}
impl AndroidTun {
/// Attach a nonblocking device returned by Builder.establish().
pub fn new(
resolver: Resolver,
establish: impl Fn(&VpnPlan) -> io::Result<File> + Send + Sync + 'static,
bind: impl Fn(&tokio::net::TcpSocket, std::net::Ipv4Addr) -> io::Result<()>
+ Send
+ Sync
+ 'static,
) -> Self {
Self(Arc::new(Inner {
establish: Box::new(establish),
bind: Box::new(bind),
resolver,
plan: Mutex::default(),
current: watch::channel(None).0,
}))
}
async fn update(&self, edit: impl FnOnce(&mut VpnPlan)) -> Result<(), OverlayError> {
let mut applied = self.0.plan.lock().await;
let mut next = applied.clone();
edit(&mut next);
if *applied == next {
return Ok(());
}
let dns_address = next.dns_address();
let device = if next.addresses.is_empty() {
None
} else {
let address = dns_address.ok_or_else(|| OverlayError::Unavailable(
"Mesh ranges overlap every device-local DNS address. Choose a narrower mesh range.".into()
))?;
let file = (self.0.establish)(&next)
.and_then(AsyncFd::new)
.map(Arc::new)
.map_err(|err| OverlayError::Unavailable(err.to_string()))?;
let dns = DnsPort::start(
address,
next.mtu as usize,
self.0.resolver.clone(),
file.clone(),
);
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;
Ok(())
}
}
#[derive(Debug)]
struct Device {
name: String,
mtu: u32,
tun: AndroidTun,
}
impl TunDevice for Device {
fn name(&self) -> &str {
&self.name
}
fn mtu(&self) -> u32 {
self.mtu
}
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
Box::pin(async move {
let mut rx = self.tun.0.current.subscribe();
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,
read = fd.device.async_io(tokio::io::Interest::READABLE, |mut file| file.read(&mut buffer)) => read,
};
if let Ok(len @ 1..) = result {
if fd.dns.intercept(&buffer[..len], &fd.addresses) {
continue;
}
buffer.truncate(len);
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.
// A later establish wakes the same reader on the new device.
rx.changed().await.ok()?;
}
})
}
fn send<'a>(&'a self, packet: Bytes) -> BoxFuture<'a, Result<(), OverlayError>> {
Box::pin(async move {
let mut rx = self.tun.0.current.subscribe();
let fd = rx
.borrow_and_update()
.clone()
.ok_or_else(|| OverlayError::Unavailable("VPN has no addresses".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(())
})
}
}
impl TunFactory for AndroidTun {
fn name(&self) -> &str {
"Android VpnService"
}
fn bind_overlay_socket(
&self,
socket: &tokio::net::TcpSocket,
source: std::net::Ipv4Addr,
) -> io::Result<()> {
(self.0.bind)(socket, source)?;
socket.bind((source, 0).into())
}
fn assigned_addresses(&self) -> Vec<std::net::IpAddr> {
self.0
.current
.borrow()
.as_ref()
.map(|fd| fd.addresses.clone())
.unwrap_or_default()
}
fn on_host(&self) -> bool {
true
}
fn create<'a>(
&'a self,
req: TunRequest,
) -> BoxFuture<'a, Result<Arc<dyn TunDevice>, OverlayError>> {
Box::pin(async move {
let dev = Device {
name: req.name.clone(),
mtu: req.mtu,
tun: self.clone(),
};
self.reconfigure(req).await?;
Ok(Arc::new(dev) as Arc<dyn TunDevice>)
})
}
fn reconfigure<'a>(&'a self, req: TunRequest) -> BoxFuture<'a, Result<(), OverlayError>> {
Box::pin(self.update(move |plan| {
plan.addresses = req.addresses;
plan.mtu = req.mtu;
}))
}
fn host_rules(&self) -> Option<Arc<dyn BroadcastHostRules>> {
Some(Arc::new(self.clone()))
}
fn destroy<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
Box::pin(async {
let _ = self.update(|plan| *plan = VpnPlan::default()).await;
})
}
}
fn outcome(result: Result<(), OverlayError>) -> RuleOutcome {
match result {
Ok(()) => RuleOutcome::Applied,
Err(error) => RuleOutcome::Failed(error.to_string()),
}
}
impl BroadcastHostRules for AndroidTun {
fn name(&self) -> &str {
"Android VpnService"
}
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
Box::pin(async move {
let route = outcome(self.update(|p| p.broadcast = true).await);
BroadcastRulesReport {
plan: plan.clone(),
route,
// Android delivers accepted traffic directly through the VPN fd.
firewall: RuleOutcome::Applied,
}
})
}
fn clear<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
Box::pin(async {
let _ = self.update(|p| p.broadcast = false).await;
})
}
fn exit_rules(&self) -> Option<&dyn ExitHostRules> {
Some(self)
}
}
impl ExitHostRules for AndroidTun {
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
Box::pin(async move {
let result = self
.update(|p| {
p.full_tunnel = plan.client;
p.exit = plan.client_source.map(Into::into);
})
.await;
ExitHostReport {
offer: plan
.offer
.iter()
.map(|range| {
(
*range,
RuleOutcome::Failed("Android supports exit clients only".into()),
)
})
.collect(),
forwarding: None,
client: plan.client.then(|| outcome(result)),
}
})
}
fn clear<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
Box::pin(async {
let _ = self
.update(|p| {
p.full_tunnel = false;
p.exit = None;
})
.await;
})
}
}
+507
View File
@@ -0,0 +1,507 @@
//! Android supplies navigation and the VPN lifecycle to the shared egui forms.
use crate::service::{Outcome, Response, State};
use egui::{Color32, Context};
use egui_phosphor::regular as icon;
use std::cell::RefCell;
use tsunagi_ui::{
about,
client::{Client, Command, Snapshot, VipSaveResult},
devices,
home::{self, UiState},
stats::{Traffic, Unit},
vip,
};
use zeroize::{Zeroize, Zeroizing};
const BAD: Color32 = Color32::from_rgb(0xd0, 0x4a, 0x3c);
#[derive(Default, PartialEq, Eq)]
enum Page {
#[default]
Home,
About,
Join,
Devices(String),
Vips(String),
Exit(String),
ExitNetworks,
Leave(String),
}
impl Page {
fn network(&self) -> Option<&str> {
match self {
Self::Devices(id) | Self::Vips(id) | Self::Exit(id) | Self::Leave(id) => Some(id),
_ => None,
}
}
fn title(&self) -> &'static str {
match self {
Self::Home => "tsunagi",
Self::About => "About",
Self::Join => "Join a network",
Self::Devices(_) => "Devices",
Self::Vips(_) => "VIP",
Self::Exit(_) | Self::ExitNetworks => "Exit node",
Self::Leave(_) => "Leave network",
}
}
}
/// Operations that require the Android activity.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum SystemAction {
/// Request VPN consent and start the foreground service.
Start,
/// Stop the service while preserving this identity and its networks.
Stop,
/// Read the clipboard after a user gesture.
PasteSecret,
/// Return to the previous Android activity.
Finish,
}
struct Actions {
command: RefCell<Option<Command>>,
busy: bool,
}
impl Client for Actions {
fn send(&self, cmd: Command) {
if !self.busy() {
self.command.replace(Some(cmd));
}
}
fn busy(&self) -> bool {
self.busy || self.command.borrow().is_some()
}
}
struct Pending {
result: Response,
vip: Option<String>,
go_home: bool,
}
/// Presentation state of the single Android viewport.
#[derive(Default)]
pub struct Phone {
page: Page,
forms: UiState,
traffic: Traffic,
snapshot: Snapshot,
pending: Option<Pending>,
error: Option<String>,
clipboard: Option<Zeroizing<String>>,
landscape: bool,
pick_exit: bool,
before_picker: Option<Page>,
}
/// Keep reads at tray density. Extra hit area is reserved for the navigation bar.
pub fn configure(ctx: &Context) {
ctx.set_os(egui::os::OperatingSystem::Android);
ctx.set_fonts(tsunagi_ui::app_fonts());
ctx.style_mut(|style| {
style.spacing.interact_size.y = 19.0;
style.spacing.button_padding = egui::vec2(6.0, 3.0);
style.spacing.item_spacing = egui::vec2(6.0, 3.0);
});
}
impl Phone {
fn home(&mut self) {
if let Some(previous) = self.before_picker.take() {
self.forms.exit_confirm = None;
self.page = previous;
return;
}
if let Page::Vips(id) = &self.page {
self.forms.vip_windows.remove(id);
}
self.forms.join = Default::default();
self.forms.exit_confirm = None;
self.forms.forget_confirm = None;
self.page = Page::Home;
}
/// System Back and toolbar Back use the same draft and confirmation state.
pub fn back(&mut self) -> Option<SystemAction> {
if self.pending.is_some() {
return None;
}
if self.forms.exit_confirm.take().is_some() || self.forms.forget_confirm.take().is_some() {
return None;
}
if let Page::Vips(id) = &self.page
&& let Some(editor) = self.forms.vip_windows.get_mut(id)
&& editor.dirty()
{
editor.request_close();
} else if self.page == Page::Home && self.landscape && self.forms.close_selection() {
return None;
} else if self.page == Page::Home {
return Some(SystemAction::Finish);
} else {
self.home();
}
None
}
/// Accept a user-initiated paste into the join form.
pub fn paste_secret(&mut self, value: String) {
if self.page == Page::Join {
self.forms.join.secret.zeroize();
self.forms.join.secret = Zeroizing::new(value);
}
}
/// Request password input with IME suggestions disabled.
pub fn secret_focused(&self, ctx: &Context) -> bool {
ctx.memory(|m| m.has_focus("join-secret".into()))
}
/// Present an error from an Android operation.
pub fn error(&mut self, message: String) {
self.error = Some(message);
}
/// The first tile tap opens the chooser once the agent is ready.
pub fn request_exit_picker(&mut self) {
self.pick_exit = true;
}
fn exit_networks(&mut self, ui: &mut egui::Ui, networks: &[tsunagi::ipc::NetworkReport]) {
if networks.is_empty() {
ui.label("Join a network to choose an exit node.");
if ui.button("Join or create a network").clicked() {
self.page = Page::Join;
}
return;
}
if !networks.iter().any(|n| n.active) {
ui.label("Start a network to choose an exit node.");
if ui.button("Show networks").clicked() {
self.home();
}
return;
}
ui.label("Choose a network for the exit node");
for n in networks.iter().filter(|n| n.active) {
let ambiguous = networks.iter().any(|other| {
other.active && other.name == n.name && other.network_id != n.network_id
});
let label = if ambiguous {
format!("{} · {}", n.name, tsunagi_ui::format::short(&n.network_id))
} else {
n.name.clone()
};
if ui.button(label).clicked() {
self.page = Page::Exit(n.network_id.clone());
}
}
}
fn landscape_home(
&mut self,
ui: &mut egui::Ui,
actions: &Actions,
report: &tsunagi::ipc::StatusReport,
) {
let width = (ui.available_width() / 3.)
.clamp(146., 300.)
.min(ui.available_width() * 0.45);
egui::SidePanel::left("network selector")
.resizable(false)
.exact_width(width)
.show_inside(ui, |ui| {
if ui.button("Join or create a network").clicked() {
self.page = Page::Join;
}
ui.separator();
egui::ScrollArea::vertical()
.id_salt("network list")
.show(ui, |ui| {
for network in &report.networks {
home::draw_network_selector(ui, network, report, &mut self.forms);
}
});
});
egui::CentralPanel::default().show_inside(ui, |ui| {
let selected = report
.networks
.iter()
.find(|n| self.forms.selected_network.as_deref() == Some(&n.network_id));
egui::ScrollArea::vertical()
.id_salt(("network settings", selected.map(|n| &n.network_id)))
.show(ui, |ui| {
if let Some(n) = selected {
ui.heading(&n.name);
ui.push_id(&n.network_id, |ui| {
if home::draw_network_details(
ui,
actions,
&mut self.forms,
&self.traffic,
n,
report,
false,
) {
self.page = Page::Exit(n.network_id.clone());
}
});
} else {
ui.heading("This device");
ui.label("Tsunagi Agent is running");
home::draw_header(ui, actions, &mut self.forms, report);
}
});
});
}
/// Take a secret once for the platform’s sensitive clipboard.
pub fn take_copied_secret(&mut self) -> Option<Zeroizing<String>> {
self.clipboard.take()
}
fn acknowledge(&mut self) {
let Some(pending) = &mut self.pending else {
return;
};
let outcome = match pending.result.try_recv() {
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => return,
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
Err("Tsunagi Agent stopped".to_owned())
}
Ok(v) => v,
};
if let Some(token) = pending.vip.take() {
let result = outcome.and_then(|r| match r {
Outcome::Saved(vips) => Ok(vips),
_ => Err("Missing VIP save acknowledgement".into()),
});
self.snapshot.vip_result = Some(VipSaveResult { token, result });
} else {
match outcome {
Ok(Outcome::Clipboard(text)) => self.clipboard = Some(text),
Ok(_) if pending.go_home => self.home(),
Ok(_) => {}
Err(e) => self.error = Some(e),
}
}
self.pending = None;
}
/// Render a tray view in this viewport and send gestures to the service.
pub fn draw(
&mut self,
ctx: &Context,
state: &State,
mut submit: impl FnMut(Command) -> Result<Response, String>,
) -> Option<SystemAction> {
self.acknowledge();
self.landscape = tsunagi_ui::widgets::landscape(ctx);
let report = if let State::Ready(report, at) = state {
if self.snapshot.at != Some(*at) {
self.snapshot.generation = self.snapshot.generation.wrapping_add(1);
self.snapshot.at = Some(*at);
self.snapshot.status = Some(Ok(report.clone()));
self.traffic.observe(report, *at);
}
if self
.page
.network()
.is_some_and(|id| !report.networks.iter().any(|n| n.network_id == id))
{
self.home();
}
if self
.forms
.selected_network
.as_ref()
.is_some_and(|id| !report.networks.iter().any(|n| &n.network_id == id))
{
self.forms.close_selection();
}
if self.pick_exit && self.pending.is_none() {
self.pick_exit = false;
let mut active = report.networks.iter().filter(|n| n.active);
let picker = match (active.next(), active.next()) {
(Some(n), None) => Page::Exit(n.network_id.clone()),
_ => Page::ExitNetworks,
};
if !matches!(self.page, Page::Exit(_) | Page::ExitNetworks) {
self.before_picker = Some(std::mem::replace(&mut self.page, picker));
}
}
Some(report)
} else {
if self.page.network().is_some() || self.page == Page::Join {
self.home();
}
self.snapshot = Snapshot::default();
self.traffic = Traffic::default();
None
};
let actions = Actions {
command: RefCell::default(),
busy: self.pending.is_some(),
};
let mut system = None;
egui::TopBottomPanel::top("navigation").show(ctx, |ui| {
ui.horizontal(|ui| {
ui.spacing_mut().interact_size.y = 32.0;
if self.page != Page::Home
&& tsunagi_ui::widgets::icon_button(ui, icon::ARROW_LEFT, "Back").clicked()
{
system = self.back();
}
ui.heading(self.page.title());
if self.page == Page::Home {
ui.weak(env!("CARGO_PKG_VERSION"));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if tsunagi_ui::widgets::icon_button(ui, icon::INFO, "About Tsunagi")
.clicked()
{
self.page = Page::About;
}
if report.is_some() {
ui.selectable_value(&mut self.forms.unit, Unit::Bytes, "bytes");
ui.selectable_value(&mut self.forms.unit, Unit::Packets, "pkts");
}
});
} else if self.page == Page::About
&& !matches!(state, State::Off)
&& ui.button("Stop Tsunagi Agent").clicked()
{
self.home();
system = Some(SystemAction::Stop);
}
});
if let Some(error) = &self.error {
ui.colored_label(BAD, error);
}
});
let selected = self
.page
.network()
.and_then(|id| report?.networks.iter().find(|n| n.network_id == id));
match (&self.page, selected) {
(Page::About, _) => about::show(ctx, None, &self.snapshot),
(Page::Vips(id), Some(network)) => {
let editor = self.forms.vip_windows.entry(id.clone()).or_default();
if vip::show(ctx, &actions, editor, network, &self.snapshot) {
self.home();
}
}
(Page::Devices(_), Some(network)) => {
if let Some(report) = report {
devices::show(
ctx,
&actions,
&mut self.forms.unit,
(&mut self.forms.exit_confirm, &mut self.forms.forget_confirm),
network,
&report.endpoint_id,
&self.traffic,
);
}
}
_ => {
egui::CentralPanel::default().show(ctx, |ui| {
if let Some(report) = report && self.page == Page::Home && self.landscape {
self.landscape_home(ui, &actions, report);
return;
}
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
let Some(report) = report else {
match state {
State::Starting => {ui.spinner(); ui.label("Starting Tsunagi Agent…");}
_ => {
if let State::Error(e) = state {ui.colored_label(BAD, e);} else {ui.weak("Tsunagi Agent is stopped");}
if ui.button("Start Tsunagi Agent").clicked() {self.error = None; system = Some(SystemAction::Start);}
}
}
return;
};
match &self.page {
Page::Home => {
home::draw_header(ui, &actions, &mut self.forms, report);
ui.separator();
if ui.button("Join or create a network").clicked() {self.page = Page::Join;}
for n in &report.networks {
if home::draw_network(ui, &actions, &mut self.forms, &self.traffic, n, report, false) {self.page = Page::Exit(n.network_id.clone());}
}
}
Page::Join => {
home::draw_join(ui, &actions, &mut self.forms.join);
if ui.button(format!("{} Paste secret", icon::CLIPBOARD)).clicked() {system = Some(SystemAction::PasteSecret);}
}
Page::Exit(_) => {
if let Some(n) = selected && let Some(choice) = devices::choose_exit(ui, n, &report.endpoint_id) {
self.forms.exit_confirm = Some(choice);
}
}
Page::ExitNetworks => self.exit_networks(ui, &report.networks),
Page::Leave(id) => {
if let Some(n) = selected {
ui.label(format!("Leave {} on this phone? You will need its secret to join again.", n.name));
if ui.button("Leave network").clicked() {actions.send(Command::Leave {network_id: id.clone()});}
if ui.button("Cancel").clicked() {self.home();}
}
}
_ => {}
}
});
});
if let Some(report) = report
&& self.page == Page::Home
{
for n in &report.networks {
if self.forms.open_devices.remove(&n.network_id) {
self.page = Page::Devices(n.network_id.clone());
break;
}
if self.forms.vip_windows.contains_key(&n.network_id) {
self.page = Page::Vips(n.network_id.clone());
break;
}
}
}
devices::confirm_exit(ctx, &actions, &mut self.forms.exit_confirm, None);
}
}
if let Some(command) = actions.command.into_inner() {
self.error = None;
if let Command::Leave { network_id } = &command
&& !matches!(self.page, Page::Leave(_))
{
self.page = Page::Leave(network_id.clone());
} else {
let token = match &command {
Command::SaveVip { token, .. } => Some(token.clone()),
_ => None,
};
let go_home = matches!(
command,
Command::Join { .. } | Command::Leave { .. } | Command::SetExitNode { .. }
);
match submit(command) {
Ok(result) => {
self.pending = Some(Pending {
result,
vip: token,
go_home,
})
}
Err(error) => {
if let Some(token) = token {
self.snapshot.vip_result = Some(VipSaveResult {
token,
result: Err(error),
});
} else {
self.error = Some(error);
}
}
}
}
}
system
}
}
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "tsunagi-awg"
version = "1.0.5"
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
edition.workspace = true
rust-version.workspace = true
license = "WTFPL AND Apache-2.0"
repository.workspace = true
[dependencies]
tsunagi-wireguard = { path = "../tsunagi-wireguard" }
[dev-dependencies]
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
iroh.workspace = true
tokio = { workspace = true, features = ["net", "time", "sync", "macros"] }
bytes.workspace = true
rand = "0.10"
tsunagi-core = { path = "../tsunagi-core", features = ["testing"] }
tempfile.workspace = true
smoltcp = { version = "0.12", default-features = false, features = ["std", "medium-ip", "proto-ipv4", "socket-tcp"] }
[lints]
workspace = true
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Friderika Coulson (NanoBee)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+21
View File
@@ -0,0 +1,21 @@
# Amnezia packet engine
`../tsunagi-wireguard/src/masking.rs` is adapted from `src/core/amnezia.rs` in
https://github.com/RunaRoo/AmneziaWG-RS at
`51579a7d6e8882d1d8d6d00822f09e18a9423b73`, under Apache-2.0.
The upstream license is retained in both packages as `LICENSE-AmneziaWG-RS`.
The adaptation replaces configuration-file loading with bounded typed pair
profiles, updates RNG calls to rand 0.10, removes an unnecessary unwrap, and
does not embed upstream's Node, global executors, OS interface operations or
detached tasks. Noise/WireGuard is supplied by boringtun, already used by
Tsunagi. Each pair owns one socket and one cancellable packet-engine task.
This is Tsunagi AWG wire version 2, not a claim of compatibility with external
Amnezia servers. The masking engine substitutes message headers outside the
standard WireGuard state machine and restores them before Noise validation.
There are no remote file paths, shell hooks, or persisted pair profiles.
The adapted masking source remains Apache-2.0. Newly written Tsunagi code
follows the repository's WTFPL. This package declares both licenses in Cargo
metadata; the workspace license alone does not describe its copied source.
+5
View File
@@ -0,0 +1,5 @@
//! Amnezia-masked UDP carrier using the independent per-neighbour WireGuard engine.
pub use tsunagi_wireguard::{
AWG_PROTOCOL, AWG_WIRE_VERSION, PairOverview, UdpCarrier as AwgPlugin,
UdpTransport as AwgTransport, profile,
};
+221
View File
@@ -0,0 +1,221 @@
//! A real userspace TCP stack attached to each memory TUN, without host routes.
use bytes::Bytes;
use smoltcp::{
iface::{Config, Interface, SocketHandle, SocketSet},
phy::{Device, DeviceCapabilities, Medium, RxToken, TxToken},
socket::tcp,
time::Instant as TcpInstant,
wire::{HardwareAddress, IpAddress, IpCidr},
};
use std::{
collections::VecDeque,
net::Ipv4Addr,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use tsunagi::overlay::MemoryTun;
struct TunDevice {
input: Arc<Mutex<VecDeque<Vec<u8>>>>,
tun: Arc<MemoryTun>,
}
struct Rx(Vec<u8>);
impl RxToken for Rx {
fn consume<R, F: FnOnce(&[u8]) -> R>(self, f: F) -> R {
f(&self.0)
}
}
struct Tx(Arc<MemoryTun>);
impl TxToken for Tx {
fn consume<R, F: FnOnce(&mut [u8]) -> R>(self, len: usize, f: F) -> R {
let mut packet = vec![0; len];
let result = f(&mut packet);
self.0.push_from_os(Bytes::from(packet));
result
}
}
impl Device for TunDevice {
type RxToken<'a>
= Rx
where
Self: 'a;
type TxToken<'a>
= Tx
where
Self: 'a;
fn receive(&mut self, _: TcpInstant) -> Option<(Rx, Tx)> {
self.input
.lock()
.unwrap()
.pop_front()
.map(|packet| (Rx(packet), Tx(self.tun.clone())))
}
fn transmit(&mut self, _: TcpInstant) -> Option<Tx> {
Some(Tx(self.tun.clone()))
}
fn capabilities(&self) -> DeviceCapabilities {
let mut caps = DeviceCapabilities::default();
caps.medium = Medium::Ip;
caps.max_transmission_unit = 1280;
caps
}
}
struct Stack {
iface: Interface,
sockets: SocketSet<'static>,
socket: SocketHandle,
device: TunDevice,
reader: tokio::task::JoinHandle<()>,
}
impl Stack {
fn new(tun: Arc<MemoryTun>, address: Ipv4Addr) -> Self {
let input = Arc::new(Mutex::new(VecDeque::new()));
let queue = input.clone();
let received = tun.clone();
let reader = tokio::spawn(async move {
while let Some(packet) = received.pop_to_os().await {
let mut queue = queue.lock().unwrap();
assert!(queue.len() < 256);
queue.push_back(packet.to_vec());
}
});
let mut device = TunDevice { input, tun };
let mut config = Config::new(HardwareAddress::Ip);
config.random_seed = rand::random();
let mut iface = Interface::new(config, &mut device, TcpInstant::from_millis(0));
let [a, b, c, d] = address.octets();
iface.update_ip_addrs(|addresses| {
addresses
.push(IpCidr::new(IpAddress::v4(a, b, c, d), 24))
.unwrap()
});
let mut sockets = SocketSet::new(Vec::new());
let socket = sockets.add(tcp::Socket::new(
tcp::SocketBuffer::new(vec![0; 65536]),
tcp::SocketBuffer::new(vec![0; 65536]),
));
Self {
iface,
sockets,
socket,
device,
reader,
}
}
fn tcp(&mut self) -> &mut tcp::Socket<'static> {
self.sockets.get_mut(self.socket)
}
fn poll(&mut self, now: TcpInstant) {
self.iface.poll(now, &mut self.device, &mut self.sockets);
}
}
impl Drop for Stack {
fn drop(&mut self) {
self.reader.abort();
}
}
pub(super) struct TcpPair {
client: Stack,
server: Stack,
started: Instant,
}
impl TcpPair {
pub(super) async fn connect(
a: Arc<MemoryTun>,
a_ip: Ipv4Addr,
b: Arc<MemoryTun>,
b_ip: Ipv4Addr,
) -> Self {
let mut pair = Self {
client: Stack::new(a, a_ip),
server: Stack::new(b, b_ip),
started: Instant::now(),
};
pair.server.tcp().listen(22).unwrap();
let [a, b, c, d] = b_ip.octets();
pair.client
.sockets
.get_mut::<tcp::Socket>(pair.client.socket)
.connect(
pair.client.iface.context(),
(IpAddress::v4(a, b, c, d), 22),
40000,
)
.unwrap();
pair.until(|p| {
p.client.tcp().state() == tcp::State::Established
&& p.server.tcp().state() == tcp::State::Established
})
.await;
pair
}
fn poll(&mut self) {
let now = TcpInstant::from_millis(self.started.elapsed().as_millis() as i64);
self.client.poll(now);
self.server.poll(now);
}
async fn until(&mut self, mut ready: impl FnMut(&mut Self) -> bool) {
tokio::time::timeout(Duration::from_secs(10), async {
let mut ticks = tokio::time::interval(Duration::from_millis(2));
loop {
ticks.tick().await;
self.poll();
if ready(self) {
break;
}
}
})
.await
.expect("same TCP connection must progress across carrier/route changes");
}
pub(super) fn queue_while_unreachable(&mut self, payload: &[u8]) {
assert_eq!(
self.client.tcp().send_slice(payload).unwrap(),
payload.len()
);
self.poll();
}
pub(super) async fn receive_queued(&mut self, payload: &[u8]) {
let mut received = Vec::new();
self.until(|p| {
if p.server.tcp().can_recv() {
p.server
.tcp()
.recv(|bytes| {
received.extend_from_slice(bytes);
(bytes.len(), ())
})
.unwrap();
}
received.len() >= payload.len()
})
.await;
assert_eq!(received, payload);
assert_eq!(self.client.tcp().state(), tcp::State::Established);
assert_eq!(self.server.tcp().state(), tcp::State::Established);
}
pub(super) async fn exchange(&mut self, payload: &[u8]) {
self.queue_while_unreachable(payload);
self.receive_queued(payload).await;
assert_eq!(
self.server.tcp().send_slice(payload).unwrap(),
payload.len()
);
let mut received = Vec::new();
self.until(|p| {
if p.client.tcp().can_recv() {
p.client
.tcp()
.recv(|bytes| {
received.extend_from_slice(bytes);
(bytes.len(), ())
})
.unwrap();
}
received.len() >= payload.len()
})
.await;
assert_eq!(received, payload);
}
}
+950
View File
@@ -0,0 +1,950 @@
//! Real membership, UDP sockets, pair negotiation and nested WireGuard encryption.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[path = "common/tcp.rs"]
mod tcp;
use bytes::Bytes;
use std::{
net::Ipv4Addr,
path::Path,
sync::{
Arc,
atomic::{AtomicBool, AtomicU64, Ordering},
},
time::Duration,
};
use tempfile::TempDir;
use tsunagi::dataplane::IpPlugin;
use tsunagi::dataplane::transport::{
ControlSender, PacketLink, PacketTransport, SharedLink, TransportError,
};
use tsunagi::discovery::SharedMemoryDiscovery;
use tsunagi::overlay::{MemoryTun, MemoryTunFactory};
use tsunagi::testing::{config_with, network, wait_for_peers, wait_until};
use tsunagi::{Agent, BoxFuture, NetworkId};
use tsunagi_awg::{AWG_PROTOCOL, AwgPlugin, AwgTransport};
use tsunagi_wg_quic::WireguardConfig;
struct Node {
agent: Agent,
plugin: Arc<tsunagi_wg_quic::WireguardPlugin>,
transport: Arc<AwgTransport>,
tuns: MemoryTunFactory,
loss: Arc<AtomicBool>,
}
impl Node {
async fn open(root: &Path, discovery: &SharedMemoryDiscovery, interface: &str) -> Self {
Self::open_with_fallback(root, discovery, interface, false).await
}
async fn open_with_fallback(
root: &Path,
discovery: &SharedMemoryDiscovery,
interface: &str,
fallback: bool,
) -> Self {
Self::open_config(root, discovery, interface, fallback, 1280).await
}
async fn open_config(
root: &Path,
discovery: &SharedMemoryDiscovery,
interface: &str,
fallback: bool,
mtu: u32,
) -> Self {
Self::open_selected(root, discovery, interface, fallback, mtu, None).await
}
async fn open_selected(
root: &Path,
discovery: &SharedMemoryDiscovery,
interface: &str,
fallback: bool,
mtu: u32,
default_protocols: Option<Vec<String>>,
) -> Self {
let identity =
tsunagi::storage::StateStore::open(tsunagi::StoragePaths::under(root).state_db())
.unwrap()
.load_or_create_device_identity()
.unwrap();
let transport = AwgTransport::new(identity.endpoint_id(), Ipv4Addr::LOCALHOST);
let plugin = tsunagi_wg_quic::WireguardPlugin::open(
WireguardConfig::new(root.join("awg"))
.with_mtu(mtu)
.with_reconcile(Duration::from_millis(20), Duration::from_millis(250)),
)
.await
.unwrap();
let loss = Arc::new(AtomicBool::new(false));
let faults = Arc::new(FaultTransport {
inner: transport.clone(),
loss: loss.clone(),
});
let tuns = MemoryTunFactory::new();
let mut config = config_with(root, discovery)
.with_interface(Arc::new(tuns.clone()), interface, mtu)
.with_tunnel(plugin.clone() as Arc<dyn IpPlugin>)
.with_carrier(AwgPlugin::new(transport.clone()))
.with_custom_transport(AWG_PROTOCOL, faults);
if fallback {
config = config.with_carrier(Arc::new(
tsunagi::dataplane::transport::iroh_link::IrohCarrier,
));
}
config.default_protocols = default_protocols;
let agent = Agent::spawn(config).await.unwrap();
let inbound_agent = agent.clone();
let inbound_transport = transport.clone();
let inbound_loss = loss.clone();
tokio::spawn(async move {
while let Some(mut link) = inbound_transport.next_inbound().await {
link.link = impaired(link.link, inbound_loss.clone());
let _ = inbound_agent.install_inbound_link(link).await;
}
});
Self {
agent,
plugin,
transport,
tuns,
loss,
}
}
async fn ready(&self, id: NetworkId, n: usize) {
wait_until("AWG outer paths and end-to-end handshakes", || async {
(self
.transport
.overview(id)
.iter()
.filter(|p| !p.closed && !p.path.contains("establishing"))
.count()
== n
&& self
.plugin
.overview(id)?
.peers
.iter()
.filter(|p| {
p.tunnel
.as_ref()
.is_some_and(|t| t.health.is_up() && t.path.contains("awg UDP via"))
})
.count()
== n)
.then_some(())
})
.await;
}
fn tun(&self) -> Arc<MemoryTun> {
self.tuns
.device(&self.agent.overlay().unwrap().interface)
.unwrap()
}
fn addr(&self, id: NetworkId) -> Ipv4Addr {
self.plugin
.overview(id)
.unwrap()
.overlay_address_v4
.unwrap()
}
}
fn packet(source: Ipv4Addr, dest: Ipv4Addr, len: usize) -> Bytes {
let mut bytes = vec![0; len];
bytes[0] = 0x45;
bytes[2..4].copy_from_slice(&(len as u16).to_be_bytes());
bytes[8] = 64;
bytes[9] = 253;
bytes[12..16].copy_from_slice(&source.octets());
bytes[16..20].copy_from_slice(&dest.octets());
rand::fill(&mut bytes[20..]);
Bytes::from(bytes)
}
async fn exchange(a: &Node, b: &Node, id: NetworkId) {
for len in [64, 1097, 1280] {
let bytes = packet(a.addr(id), b.addr(id), len);
a.tun().push_from_os(bytes.clone());
assert_eq!(
tokio::time::timeout(Duration::from_secs(5), b.tun().pop_to_os())
.await
.unwrap()
.unwrap(),
bytes
);
}
}
#[tokio::test]
async fn a_control_only_agent_enables_real_data_without_restart_and_cancels_stale_attempts() {
let discovery = SharedMemoryDiscovery::new();
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
let a = Node::open_selected(
roots[0].path(),
&discovery,
"initial-none-a",
true,
1280,
Some(vec![]),
)
.await;
let b = Node::open_selected(
roots[1].path(),
&discovery,
"initial-none-b",
true,
1280,
Some(vec![]),
)
.await;
let (name, secret) = network("enable-after-control-only");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
wait_for_peers(&a.agent, id, 1).await;
wait_for_peers(&b.agent, id, 1).await;
assert!(a.agent.overlay().is_none());
assert!(b.agent.overlay().is_none());
for node in [&a, &b] {
assert!(
node.agent
.network_status(id)
.await
.unwrap()
.protocols
.is_empty()
);
node.agent
.set_protocols(id, vec!["awg".into()])
.await
.unwrap();
assert!(node.agent.overlay().is_some());
}
a.ready(id, 1).await;
b.ready(id, 1).await;
exchange(&a, &b, id).await;
let before = a.agent.overlay().unwrap().interface;
// Changes race unfinished opens and prepared plugin callbacks; the last
// selection must win even if an earlier open has completed in its queue.
for selection in [
vec!["wg-quic".into()],
vec![],
vec!["awg".into()],
vec![],
vec!["awg".into()],
] {
a.agent.set_protocols(id, selection).await.unwrap();
}
a.ready(id, 1).await;
b.ready(id, 1).await;
exchange(&a, &b, id).await;
assert_eq!(a.agent.overlay().unwrap().interface, before);
for node in [&a, &b] {
let status = node.agent.network_status(id).await.unwrap();
assert_eq!(status.protocols, ["awg"]);
assert_eq!(status.metrics.sessions_established, 1);
assert_eq!(status.metrics.disconnects, 0);
}
a.agent.shutdown().await;
b.agent.shutdown().await;
}
#[tokio::test]
async fn runtime_protocol_selection_preserves_real_tunnels_and_survives_restart() {
let discovery = SharedMemoryDiscovery::new();
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
let a = Node::open_with_fallback(roots[0].path(), &discovery, "runtime-a", true).await;
let b = Node::open_with_fallback(roots[1].path(), &discovery, "runtime-b", true).await;
let (name, secret) = network("runtime-protocols");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
a.ready(id, 1).await;
b.ready(id, 1).await;
exchange(&a, &b, id).await;
let original_key = a.plugin.overview(id).unwrap().public_key;
let original_stats = a.plugin.overview(id).unwrap().peers[0]
.tunnel
.as_ref()
.unwrap()
.stats;
let (other_name, other_secret, other_id) = loop {
let (name, secret) = network("unchanged-runtime-network");
let other_id = tsunagi::identity::NetworkKeys::derive(&name, &secret).network_id();
if tsunagi::state::derived_ipv4_range(id) != tsunagi::state::derived_ipv4_range(other_id) {
break (name, secret, other_id);
}
};
a.agent
.join_network(&other_name, &other_secret)
.await
.unwrap();
b.agent
.join_network(&other_name, &other_secret)
.await
.unwrap();
a.ready(other_id, 1).await;
b.ready(other_id, 1).await;
let other_before = a
.agent
.network_status(other_id)
.await
.unwrap()
.metrics
.data_links_established;
for node in [&a, &b] {
let before = node.agent.network_status(id).await.unwrap().protocols;
for invalid in [vec!["unknown".into()], vec!["awg".into(), "awg".into()]] {
assert!(node.agent.set_protocols(id, invalid).await.is_err());
assert_eq!(
node.agent.network_status(id).await.unwrap().protocols,
before
);
}
}
// Exercise updates initiated by either endpoint-id role, including an
// empty set. Membership and the control session stay alive throughout.
for node in [&a, &b] {
node.agent.set_protocols(id, Vec::new()).await.unwrap();
wait_until("peer accepts control-only selection", || async {
let other = if node.agent.endpoint_id() == a.agent.endpoint_id() {
&b
} else {
&a
};
let status = other.agent.network_status(id).await.ok()?;
(status.peers.len() == 1
&& status.peers[0].protocols.is_empty()
&& matches!(status.peers[0].data_path, tsunagi::agent::DataPath::None))
.then_some(())
})
.await;
assert_eq!(node.agent.network_status(id).await.unwrap().peers.len(), 1);
node.agent
.set_protocols(id, vec!["wg-quic".into(), "awg".into()])
.await
.unwrap();
}
a.agent
.set_protocols(id, vec!["wg-quic".into()])
.await
.unwrap();
wait_until("real QUIC replaces AWG", || async {
let a_status = a.agent.network_status(id).await.ok()?;
let b_status = b.agent.network_status(id).await.ok()?;
(a_status.peers[0].protocols == ["wg-quic"]
&& b_status.peers[0].protocols == ["wg-quic"]
&& !matches!(a_status.peers[0].data_path, tsunagi::agent::DataPath::None)
&& !matches!(b_status.peers[0].data_path, tsunagi::agent::DataPath::None)
&& a.transport.overview(id).iter().all(|p| p.closed)
&& b.transport.overview(id).iter().all(|p| p.closed))
.then_some(())
})
.await;
assert_eq!(a.plugin.overview(id).unwrap().public_key, original_key);
let stats = a.plugin.overview(id).unwrap().peers[0]
.tunnel
.as_ref()
.unwrap()
.stats;
assert_eq!(stats.counter_epoch, original_stats.counter_epoch);
assert!(stats.tx_bytes >= original_stats.tx_bytes);
assert!(stats.rx_bytes >= original_stats.rx_bytes);
assert!(a.plugin.overview(id).unwrap().peers.iter().any(|peer| {
peer.tunnel
.as_ref()
.is_some_and(|tunnel| tunnel.health.is_up())
}));
// The same internal plugin supplies addresses and counters on the new carrier.
for (source, dest) in [(&a, &b), (&b, &a)] {
wait_until("QUIC end-to-end handshake", || async {
source
.plugin
.overview(id)?
.peers
.iter()
.any(|p| p.tunnel.as_ref().is_some_and(|t| t.health.is_up()))
.then_some(())
})
.await;
let addr = |n: &Node| n.plugin.overview(id).unwrap().overlay_address_v4.unwrap();
let bytes = packet(addr(source), addr(dest), 1280);
source.tun().push_from_os(bytes.clone());
assert_eq!(
tokio::time::timeout(Duration::from_secs(5), dest.tun().pop_to_os())
.await
.unwrap()
.unwrap(),
bytes
);
}
assert_eq!(
a.agent
.network_status(other_id)
.await
.unwrap()
.metrics
.data_links_established,
other_before
);
exchange(&a, &b, other_id).await;
a.agent.shutdown().await;
let restarted = Node::open_with_fallback(roots[0].path(), &discovery, "runtime-a", true).await;
wait_for_peers(&restarted.agent, id, 1).await;
assert_eq!(
restarted.agent.network_status(id).await.unwrap().protocols,
["wg-quic"]
);
assert_eq!(
b.agent.network_status(other_id).await.unwrap().protocols,
["awg", "wg-quic"]
);
restarted.ready(other_id, 1).await;
b.ready(other_id, 1).await;
exchange(&restarted, &b, other_id).await;
restarted
.agent
.set_protocols(id, vec!["awg".into()])
.await
.unwrap();
restarted.ready(id, 1).await;
b.ready(id, 1).await;
exchange(&restarted, &b, id).await;
restarted.agent.shutdown().await;
b.agent.shutdown().await;
}
#[tokio::test]
async fn real_pairs_carry_full_size_packets_and_restart_with_fresh_profiles() {
tsunagi::testing::init_tracing();
let discovery = SharedMemoryDiscovery::new();
let roots = [
TempDir::new().unwrap(),
TempDir::new().unwrap(),
TempDir::new().unwrap(),
];
let a = Node::open(roots[0].path(), &discovery, "awga").await;
let b = Node::open(roots[1].path(), &discovery, "awgb").await;
let c = Node::open(roots[2].path(), &discovery, "awgc").await;
let (name, secret) = network("awg-pairs");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
c.agent.join_network(&name, &secret).await.unwrap();
for node in [&a, &b, &c] {
wait_for_peers(&node.agent, id, 2).await;
node.ready(id, 2).await;
}
let ids: std::collections::HashSet<_> = [&a, &b, &c]
.into_iter()
.flat_map(|n| n.transport.overview(id).into_iter().map(|p| p.attempt))
.collect();
assert_eq!(
ids.len(),
3,
"one independent profile for each of three pairs"
);
exchange(&a, &b, id).await;
exchange(&b, &a, id).await;
exchange(&a, &c, id).await;
let old_ports: Vec<_> = a
.transport
.overview(id)
.into_iter()
.filter_map(|p| p.local_port)
.collect();
a.agent.shutdown().await;
for port in old_ports {
wait_until("old pair socket released", || async {
tokio::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, port))
.await
.ok()
})
.await;
}
let restarted = Node::open(roots[0].path(), &discovery, "awga").await;
restarted.ready(id, 2).await;
assert!(
restarted
.transport
.overview(id)
.iter()
.all(|p| !ids.contains(&p.attempt))
);
exchange(&restarted, &b, id).await;
exchange(&c, &restarted, id).await;
restarted.agent.shutdown().await;
b.agent.shutdown().await;
c.agent.shutdown().await;
assert!(
tokio::time::timeout(Duration::from_secs(1), restarted.transport.next_inbound())
.await
.unwrap()
.is_none()
);
}
// Drops datagrams at the link boundary. Membership, control, sockets, crypto,
// addressing and storage remain real. This substitutes a lossy physical path.
#[derive(Debug)]
struct FaultTransport {
inner: Arc<AwgTransport>,
loss: Arc<AtomicBool>,
}
impl PacketTransport for FaultTransport {
fn name(&self) -> &str {
AWG_PROTOCOL
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn attach_control(&self, sender: Arc<dyn ControlSender>) {
self.inner.attach_control(sender);
}
fn on_control(
&self,
network: NetworkId,
peer: iroh::EndpointId,
protocol: &str,
bytes: &[u8],
) -> Result<(), TransportError> {
self.inner.on_control(network, peer, protocol, bytes)
}
fn open<'a>(
&'a self,
network: NetworkId,
peer: iroh::EndpointId,
protocol: &'a str,
) -> BoxFuture<'a, Result<SharedLink, TransportError>> {
Box::pin(async move {
Ok(impaired(
self.inner.open(network, peer, protocol).await?,
self.loss.clone(),
))
})
}
}
fn impaired(raw: SharedLink, loss: Arc<AtomicBool>) -> SharedLink {
Arc::new(FaultLink {
raw,
loss,
sequence: AtomicU64::new(0),
})
}
#[derive(Debug)]
struct FaultLink {
raw: SharedLink,
loss: Arc<AtomicBool>,
sequence: AtomicU64,
}
impl PacketLink for FaultLink {
fn confirm_delivery(&self) {
self.raw.confirm_delivery();
}
fn network(&self) -> NetworkId {
self.raw.network()
}
fn peer(&self) -> iroh::EndpointId {
self.raw.peer()
}
fn max_datagram_size(&self) -> usize {
self.raw.max_datagram_size()
}
fn send(&self, bytes: Bytes) -> Result<(), TransportError> {
if self.loss.load(Ordering::Relaxed)
&& !self
.sequence
.fetch_add(1, Ordering::Relaxed)
.is_multiple_of(5)
{
Ok(())
} else {
self.raw.send(bytes)
}
}
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
self.raw.recv()
}
fn closed(&self) -> BoxFuture<'_, ()> {
self.raw.closed()
}
fn is_closed(&self) -> bool {
self.raw.is_closed()
}
fn close(&self) {
self.raw.close();
}
fn path_description(&self) -> String {
self.raw.path_description()
}
}
#[tokio::test]
async fn persistent_runtime_loss_retires_the_pair_and_negotiates_fresh_parameters() {
let discovery = SharedMemoryDiscovery::new();
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
let a = Node::open(roots[0].path(), &discovery, "lossa").await;
let b = Node::open(roots[1].path(), &discovery, "lossb").await;
let (name, secret) = network("awg-loss");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
a.ready(id, 1).await;
b.ready(id, 1).await;
exchange(&a, &b, id).await;
let old = a.transport.overview(id)[0].attempt;
let mut events = a.agent.subscribe();
a.loss.store(true, Ordering::Relaxed);
tsunagi::testing::wait_event(&mut events, |event| match event {
tsunagi::Event::DataLinkDown {
network, reason, ..
} if *network == id && reason.contains("delivery checks") => Some(()),
_ => None,
})
.await;
a.loss.store(false, Ordering::Relaxed);
wait_until("fresh AWG profile after runtime loss", || async {
a.transport
.overview(id)
.iter()
.any(|p| p.attempt != old && !p.closed && !p.path.contains("establishing"))
.then_some(())
})
.await;
a.ready(id, 1).await;
b.ready(id, 1).await;
let initiator = if a.agent.endpoint_id().as_bytes() < b.agent.endpoint_id().as_bytes() {
&a
} else {
&b
};
let attempt = initiator.transport.overview(id)[0].attempt;
let received = initiator.transport.overview(id)[0].delivery_checks;
wait_until(
"fresh physical delivery checks answered after installation",
|| async {
(initiator.transport.overview(id).first()?.delivery_checks >= received + 3)
.then_some(())
},
)
.await;
assert_eq!(initiator.transport.overview(id)[0].attempt, attempt);
wait_for_peers(&a.agent, id, 1).await;
exchange(&a, &b, id).await;
exchange(&b, &a, id).await;
a.agent.shutdown().await;
b.agent.shutdown().await;
}
#[tokio::test]
async fn runtime_loss_falls_back_to_real_iroh_without_interrupting_control_or_ip() {
let discovery = SharedMemoryDiscovery::new();
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
let a = Node::open_with_fallback(roots[0].path(), &discovery, "fallba", true).await;
let b = Node::open_with_fallback(roots[1].path(), &discovery, "fallbb", true).await;
let (name, secret) = network("awg-fallback");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
a.ready(id, 1).await;
b.ready(id, 1).await;
exchange(&a, &b, id).await;
let mut events = a.agent.subscribe();
a.loss.store(true, Ordering::Relaxed);
tsunagi::testing::wait_event(&mut events, |event| match event {
tsunagi::Event::DataLinkDown {
network, reason, ..
} if *network == id && reason.contains("delivery checks") => Some(()),
_ => None,
})
.await;
for node in [&a, &b] {
wait_until("fallback carrier is wg-quic",||async {
let status=node.agent.status().await.ok()?;
let network=status.networks.iter().find(|n|n.network_id==id)?;
(network.members.iter().any(|m|matches!(&m.data_path,tsunagi::agent::DataPath::Direct{transport} if transport=="wg-quic"))).then_some(())
}).await;
wait_for_peers(&node.agent, id, 1).await;
}
exchange(&a, &b, id).await;
exchange(&b, &a, id).await;
a.agent.shutdown().await;
b.agent.shutdown().await;
}
#[tokio::test]
async fn opaque_pair_carrier_fragments_its_full_advertised_capacity() {
let discovery = SharedMemoryDiscovery::new();
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
let mut nodes = Vec::new();
for root in &roots {
let identity = tsunagi::storage::StateStore::open(
tsunagi::StoragePaths::under(root.path()).state_db(),
)
.unwrap()
.load_or_create_device_identity()
.unwrap();
let transport = AwgTransport::new(identity.endpoint_id(), Ipv4Addr::LOCALHOST);
let agent = Agent::spawn(
config_with(root.path(), &discovery)
.with_custom_transport(AWG_PROTOCOL, transport.clone()),
)
.await
.unwrap();
nodes.push((agent, transport));
}
let (name, secret) = network("awg-capacity");
let id = nodes[0].0.join_network(&name, &secret).await.unwrap();
nodes[1].0.join_network(&name, &secret).await.unwrap();
for (i, (agent, transport)) in nodes.iter().enumerate() {
wait_for_peers(agent, id, 1).await;
// This fixture tests only the transport contract: register the member
// after the real core has authenticated it, without an IP plugin/TUN.
transport.allow_peer(id, nodes[1 - i].0.endpoint_id());
}
nodes.sort_by_key(|(agent, _)| *agent.endpoint_id().as_bytes());
let outgoing = nodes[0]
.1
.open(id, nodes[1].0.endpoint_id(), AWG_PROTOCOL)
.await
.unwrap();
let incoming = tokio::time::timeout(Duration::from_secs(5), nodes[1].1.next_inbound())
.await
.unwrap()
.unwrap()
.link;
for (from, to) in [(&outgoing, &incoming), (&incoming, &outgoing)] {
let mut bytes = vec![0; from.max_datagram_size()];
rand::fill(&mut bytes[..]);
let bytes = Bytes::from(bytes);
from.send(bytes.clone()).unwrap();
assert_eq!(
tokio::time::timeout(Duration::from_secs(5), to.recv())
.await
.unwrap()
.unwrap(),
bytes
);
assert!(matches!(
from.send(Bytes::from(vec![0; from.max_datagram_size() + 1])),
Err(TransportError::TooLarge { .. })
));
}
outgoing.close();
incoming.close();
for (agent, transport) in nodes {
transport.shutdown();
agent.shutdown().await;
}
}
#[tokio::test]
async fn encrypted_health_checks_fit_a_smaller_peers_configured_interface_mtu() {
let discovery = SharedMemoryDiscovery::new();
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
let a = Node::open_config(roots[0].path(), &discovery, "smalla", false, 1280).await;
let b = Node::open_config(roots[1].path(), &discovery, "smallb", false, 576).await;
let (name, secret) = network("awg-small-mtu");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
a.ready(id, 1).await;
b.ready(id, 1).await;
let bytes = packet(a.addr(id), b.addr(id), 576);
a.tun().push_from_os(bytes.clone());
assert_eq!(
tokio::time::timeout(Duration::from_secs(5), b.tun().pop_to_os())
.await
.unwrap()
.unwrap(),
bytes
);
wait_until(
"physical delivery checks do not depend on overlay MTU",
|| async {
(a.transport.overview(id).first()?.delivery_checks >= 4
&& b.transport.overview(id).first()?.delivery_checks >= 4)
.then_some(())
},
)
.await;
for node in [&a, &b] {
assert_eq!(
node.plugin.overview(id).unwrap().peers[0]
.tunnel
.as_ref()
.unwrap()
.stats
.dropped_oversize,
0
);
}
a.agent.shutdown().await;
b.agent.shutdown().await;
}
#[tokio::test]
async fn disjoint_external_policies_relay_the_same_internal_tunnel_and_keep_it_when_routes_change()
{
let discovery = SharedMemoryDiscovery::new();
let roots = [
TempDir::new().unwrap(),
TempDir::new().unwrap(),
TempDir::new().unwrap(),
];
let a = Node::open_selected(
roots[0].path(),
&discovery,
"only-awg",
true,
1280,
Some(vec!["awg".into()]),
)
.await;
let b = Node::open_with_fallback(roots[1].path(), &discovery, "mixed-relay", true).await;
let c = Node::open_selected(
roots[2].path(),
&discovery,
"only-quic",
true,
1280,
Some(vec!["wg-quic".into()]),
)
.await;
let (name, secret) = network("independent-internal-encryption");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
c.agent.join_network(&name, &secret).await.unwrap();
for node in [&a, &b, &c] {
wait_for_peers(&node.agent, id, 2).await;
}
wait_until("AWG-only to QUIC-only through an authenticated mixed relay", || async {
let status = a.agent.network_status(id).await.ok()?;
let peer = status.peers.iter().find(|p| p.endpoint_id == c.agent.endpoint_id())?;
(matches!(peer.data_path, tsunagi::agent::DataPath::Relayed { via, .. } if via == b.agent.endpoint_id()) && a.plugin.overview(id)?.established_peers() == 2 && c.plugin.overview(id)?.established_peers() == 2).then_some(())
}).await;
exchange(&a, &c, id).await;
exchange(&c, &a, id).await;
let mut tcp = tcp::TcpPair::connect(a.tun(), a.addr(id), c.tun(), c.addr(id)).await;
tcp.exchange(b"SSH-like TCP stream over the initial relay")
.await;
let key = a.plugin.overview(id).unwrap().public_key;
let before = a
.plugin
.overview(id)
.unwrap()
.peers
.iter()
.find(|p| p.endpoint_id == c.agent.endpoint_id())
.unwrap()
.tunnel
.as_ref()
.unwrap()
.stats
.tx_packets;
// A's additional permission creates a direct QUIC route without replacing its IP tunnel.
a.agent
.set_protocols(id, vec!["wg-quic".into(), "awg".into()])
.await
.unwrap();
wait_until("direct carrier replaces the relay", || async {
let status = a.agent.network_status(id).await.ok()?;
matches!(
status
.peers
.iter()
.find(|p| p.endpoint_id == c.agent.endpoint_id())?
.data_path,
tsunagi::agent::DataPath::Direct { .. }
)
.then_some(())
})
.await;
tcp.exchange(b"same TCP socket after changing the carrier and next hop")
.await;
assert_eq!(a.plugin.overview(id).unwrap().public_key, key);
assert!(
a.plugin
.overview(id)
.unwrap()
.peers
.iter()
.find(|p| p.endpoint_id == c.agent.endpoint_id())
.unwrap()
.tunnel
.as_ref()
.unwrap()
.stats
.tx_packets
> before
);
a.agent.set_protocols(id, Vec::new()).await.unwrap();
// Poll the actual TCP stack while the route is absent: its first transmission is lost.
let pending = b"TCP retransmission survives the temporary absence of every data carrier";
tcp.queue_while_unreachable(pending);
a.agent.set_protocols(id, vec!["awg".into()]).await.unwrap();
wait_until("forbidden QUIC removed and relay restored", || async {
let status = a.agent.network_status(id).await.ok()?;
matches!(
status
.peers
.iter()
.find(|p| p.endpoint_id == c.agent.endpoint_id())?
.data_path,
tsunagi::agent::DataPath::Relayed { .. }
)
.then_some(())
})
.await;
assert_eq!(a.plugin.overview(id).unwrap().public_key, key);
tcp.receive_queued(pending).await;
tcp.exchange(b"same TCP connection after returning to AWG and the relay")
.await;
drop(tcp);
// Transit ciphertext must never be delivered to the middle agent's IP interface.
assert!(
tokio::time::timeout(Duration::from_millis(150), b.tun().pop_to_os())
.await
.is_err()
);
for node in [&a, &b, &c] {
node.agent.shutdown().await;
}
}
#[tokio::test]
async fn no_common_carrier_is_an_actionable_policy_error_without_disabling_control() {
let discovery = SharedMemoryDiscovery::new();
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
let a = Node::open_selected(
roots[0].path(),
&discovery,
"awg-policy",
true,
1280,
Some(vec!["awg".into()]),
)
.await;
let b = Node::open_selected(
roots[1].path(),
&discovery,
"quic-policy",
true,
1280,
Some(vec!["wg-quic".into()]),
)
.await;
let (name, secret) = network("no-common-carrier");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
wait_until("explain independent external policies", || async {
let status = a.agent.network_status(id).await.ok()?;
let peer = status.peers.first()?;
peer.data_error
.as_ref()?
.contains("no common external transport")
.then_some(())
})
.await;
assert_eq!(
a.agent
.network_status(id)
.await
.unwrap()
.metrics
.data_links_established,
0
);
a.agent.shutdown().await;
b.agent.shutdown().await;
}
+36
View File
@@ -0,0 +1,36 @@
//! Fresh and bounded masking profiles, and rejection of foreign/truncated wire packets.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use tsunagi_awg::profile::PairProfile;
#[test]
fn profiles_are_fresh_bounded_and_redacted() {
let profiles: Vec<_> = (0..128).map(|_| PairProfile::generate()).collect();
for (i, profile) in profiles.iter().enumerate() {
profile.validate().unwrap();
assert!(!format!("{profile:?}").contains(&format!("{:?}", profile.header_key())));
for other in &profiles[..i] {
assert_ne!(profile.header_key(), other.header_key());
assert_ne!(profile.id(), other.id());
}
for packet in profile.signature_packets() {
assert!(packet.len() < 1200);
}
}
}
#[test]
fn masked_packets_round_trip_and_reject_other_profiles_and_truncation() {
let profile = PairProfile::generate();
let other = PairProfile::generate();
for (kind, size) in [(1, 148), (2, 92), (3, 64), (4, 800)] {
let mut message = vec![0x7b; size];
message[..4].copy_from_slice(&(kind as u32).to_le_bytes());
let wire = profile.encode(&message).unwrap();
assert_ne!(&wire[..4], &message[..4]);
assert_eq!(profile.decode(&wire).unwrap(), message);
assert!(other.decode(&wire).is_none());
for length in 0..44 {
assert!(profile.decode(&wire[..length]).is_none());
}
}
}
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-core"
version = "0.1.0"
version = "1.0.5"
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.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -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)));
}
}
@@ -0,0 +1,152 @@
//! Each ordered stream keeps a cursor into the latest signed state. A slow or
//! reconnecting peer can catch up without a per-peer backlog of signed frames.
use super::{ControlMessage, EndpointId, MAX_RETIREMENT_LEN, Runtime};
use std::collections::BTreeMap;
use std::ops::Bound::{Excluded, Unbounded};
/// The stable identity of a signed object, including tombstones.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum SyncKey {
Claim(EndpointId),
Retirement(EndpointId),
Vip(String),
}
/// One entry per stored object, regardless of its edit count or the number of
/// peers. Revisions are local scheduling information, never persisted or sent.
#[derive(Default)]
pub(super) struct Changes {
latest: u64,
revisions: BTreeMap<SyncKey, u64>,
order: BTreeMap<u64, SyncKey>,
}
impl Changes {
fn note(&mut self, key: SyncKey) {
self.latest += 1;
if let Some(previous) = self.revisions.insert(key.clone(), self.latest) {
self.order.remove(&previous);
}
self.order.insert(self.latest, key);
}
fn after(&self, cursor: u64) -> impl Iterator<Item = (u64, &SyncKey)> {
self.order
.range((Excluded(cursor), Unbounded))
.map(|(&revision, key)| (revision, key))
}
}
impl Runtime {
pub(super) fn index_stored_state(&mut self) {
for record in self.state.records() {
if let Ok(author) = record.author_id() {
self.changes.note(SyncKey::Claim(author));
}
}
for marker in self.state.retirements() {
if let Ok(target) = marker.target.author_id() {
self.changes.note(SyncKey::Retirement(target));
}
}
for id in self.params.vips.ids() {
self.changes.note(SyncKey::Vip(id));
}
}
pub(super) fn share_changes(&mut self, keys: impl IntoIterator<Item = SyncKey>) -> usize {
for key in keys {
self.changes.note(key);
}
self.params.roster_changed.send_replace(());
self.flush_updates();
self.sessions
.values()
.filter(|session| session.state_sent == self.changes.latest)
.count()
}
pub(super) fn flush_updates(&mut self) {
let peers: Vec<_> = self
.sessions
.values()
.filter(|s| s.state_sent < self.changes.latest)
.map(|s| s.peer)
.collect();
for peer in peers {
self.flush_peer(peer);
}
}
pub(super) fn flush_peer(&mut self, peer: EndpointId) {
// A retirement contains a signed claim plus a second signature, so its
// size bound also covers a claim. VIPs are validated as complete frames.
let limits = &self.params.limits;
let batch = (limits.max_frame_len.saturating_sub(128) / MAX_RETIREMENT_LEN)
.max(1)
.min(limits.max_state_records.max(1));
while let Some(session) = self.sessions.get(&peer) {
if session.outbound.capacity() == 0 {
break;
}
let cursor = session.state_sent;
let Some((mut through, first)) = self.changes.after(cursor).next() else {
break;
};
let message = {
let pending = self.changes.after(cursor).take(batch);
match first {
SyncKey::Claim(_) => ControlMessage::State {
records: pending
.map_while(|(revision, key)| {
let SyncKey::Claim(id) = key else { return None };
through = revision;
self.state.get(id).cloned()
})
.collect(),
},
SyncKey::Retirement(_) => ControlMessage::Retirements {
markers: pending
.map_while(|(revision, key)| {
let SyncKey::Retirement(id) = key else {
return None;
};
through = revision;
self.state.retirement_of(id).cloned()
})
.collect(),
},
SyncKey::Vip(id) => ControlMessage::Vips {
entries: self.params.vips.entries(id),
},
}
};
if self.send_to(peer, message).is_err() {
break;
}
if let Some(session) = self.sessions.get_mut(&peer) {
session.state_sent = through;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slow_and_returning_sessions_each_get_the_latest_revision() {
let mut index = Changes::default();
let first = SyncKey::Vip("first".into());
let second = SyncKey::Vip("second".into());
index.note(first.clone());
let sent = index.latest;
index.note(second.clone());
index.note(first.clone());
for cursor in [0, sent] {
let pending: Vec<_> = index.after(cursor).map(|(_, key)| key.clone()).collect();
assert_eq!(pending, [second.clone(), first.clone()]);
}
assert_eq!(index.after(index.latest).count(), 0);
}
}
+14 -4
View File
@@ -68,10 +68,15 @@ pub(crate) struct Session {
pub(crate) role: Role,
pub(crate) established: Instant,
pub(crate) conn: Connection,
/// Already encoded frame payloads, so the runtime can account for the exact
/// number of control bytes it queues.
pub(crate) outbound: mpsc::Sender<Vec<u8>>,
/// Last signed-state revision queued on this ordered stream.
pub(super) state_sent: u64,
/// Prefix of the current introduction list already queued on this stream.
pub(super) introductions_sent: usize,
pub(super) reach_sent: Option<Instant>,
/// Already encoded frames, accounted for when queued.
pub(crate) outbound: mpsc::Sender<zeroize::Zeroizing<Vec<u8>>>,
pub(crate) hostname: Option<String>,
pub(crate) agent_version: Option<String>,
pub(crate) capabilities: Vec<PluginCapability>,
pub(crate) broadcast: bool,
/// The peer offers itself as an exit node in this network.
@@ -227,7 +232,11 @@ pub(crate) fn spawn(
established: Instant::now(),
conn,
outbound: outbound_tx,
state_sent: 0,
introductions_sent: 0,
reach_sent: None,
hostname: None,
agent_version: None,
capabilities: Vec::new(),
broadcast: false,
exit_node: false,
@@ -244,7 +253,7 @@ pub(crate) fn spawn(
async fn writer_task(
mut send: SendStream,
mut outbound: mpsc::Receiver<Vec<u8>>,
mut outbound: mpsc::Receiver<zeroize::Zeroizing<Vec<u8>>>,
limits: Arc<Limits>,
shutdown: Shutdown,
parent: Shutdown,
@@ -331,6 +340,7 @@ async fn reader_task(
}
};
let payload = zeroize::Zeroizing::new(payload);
let bytes = payload.len();
let envelope: Envelope = match decode(&payload) {
Ok(envelope) => envelope,
+39 -6
View File
@@ -16,6 +16,11 @@ use crate::net::{ConnectionCounters, PathAddr, PathInfo, TransportKind};
use crate::proto::handshake::Role;
use crate::storage::CacheOutcome;
/// Informational data-channel diagnostics shared by the status UI and runtime.
pub const DATA_CONNECTING: &str = "establishing external data transport";
/// Data transport was disabled by local policy.
pub const DATA_DISABLED: &str = "data transports disabled locally";
/// Whether a configured network is running locally.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NetworkState {
@@ -51,6 +56,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
@@ -108,6 +115,8 @@ pub struct HostnameConflict {
/// connected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemberStatus {
/// Current signed claim version, used to bind cleanup confirmation.
pub record_version: u64,
/// The member's device identity.
pub endpoint_id: EndpointId,
/// The IPv4 overlay address it claimed and signed for.
@@ -148,6 +157,8 @@ pub struct PeerStatus {
///
/// A mutable binding, not an identity.
pub hostname: Option<String>,
/// Software version in the peer's latest authenticated announcement.
pub agent_version: Option<String>,
/// Protocols agreed with this peer: both sides have them at the same
/// version.
///
@@ -156,6 +167,8 @@ pub struct PeerStatus {
pub protocols: Vec<String>,
/// Capabilities the peer announced. Payloads stay opaque.
pub capabilities: Vec<PluginCapability>,
/// Why no data route is available, when known.
pub data_error: Option<String>,
/// How long the session has been up.
pub connected_for: Duration,
/// Verified paths of the underlying connection.
@@ -164,6 +177,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.
@@ -209,9 +226,26 @@ pub struct NetworkMetrics {
pub data_link_failures: u64,
}
/// An active network preventing another network from starting locally.
#[derive(Debug, Clone)]
pub struct RangeConflict {
/// The blocking network's public identifier.
pub network_id: NetworkId,
/// Its configured name.
pub name: NetworkName,
/// Its overlapping overlay range.
pub range: crate::state::Ipv4Range,
}
/// Status of one network.
#[derive(Debug, Clone)]
pub struct NetworkStatus {
/// Shared service configuration with this client's routing observations.
pub vips: Vec<crate::vip::VipStatus>,
/// Enabled local data-plane protocols, in preference order.
pub protocols: Vec<String>,
/// Whether this network is requested to start or resume automatically.
pub auto_start: bool,
/// Local broadcast participation in this network.
pub broadcast: bool,
/// This agent offers itself as an exit node in this network.
@@ -220,6 +254,8 @@ pub struct NetworkStatus {
pub exit_via: Option<EndpointId>,
/// Whether that member is connected and still offering to be one.
pub exit_via_online: bool,
/// IP byte totals since this exit route was selected.
pub exit_traffic: Option<crate::overlay::exit::ExitTraffic>,
/// What the host rules for the exit settings are doing.
pub exit_rules: crate::overlay::ExitRulesReport,
/// Immutable deterministic description of the network space.
@@ -242,13 +278,10 @@ pub struct NetworkStatus {
pub hostname_conflict: Option<HostnameConflict>,
/// The overlay range this network uses, once it has one.
pub range: Option<crate::state::Ipv4Range>,
/// The range it could not have, because another network on this agent
/// already holds it.
///
/// One agent has one interface, so an address belongs to one network.
/// This network waits to adopt whatever its members settle on instead of
/// proposing something it could not route.
/// The first overlapping active range; `range_conflicts` identifies all blockers.
pub range_conflict: Option<crate::state::Ipv4Range>,
/// Active networks that would be suspended by switching to this network.
pub range_conflicts: Vec<RangeConflict>,
/// Per-network counters.
pub metrics: NetworkMetrics,
/// What has gone through a peer in the middle, in both directions.
+62 -10
View File
@@ -21,6 +21,9 @@ use crate::error::Result;
#[cfg_attr(target_os = "macos", allow(dead_code))]
const APP_NAME: &str = "tsunagi";
/// Maximum length of the optional software release label in a peer announcement.
pub const MAX_AGENT_VERSION_LEN: usize = 64;
/// Rendezvous slots per network; this bounds a discovery sample, not membership.
pub const DHT_SLOTS: u8 = 16;
/// BEP44 permits 1000 bencoded bytes; a 996-byte string has a four-byte prefix.
@@ -158,6 +161,22 @@ pub enum TransportPolicy {
/// object where that is possible (notably [`Limits::max_frame_len`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Limits {
/// Maximum active VIP identities per network.
pub max_vips: usize,
/// Maximum permanent VIP deletion tombstones per network.
pub max_vip_tombstones: usize,
/// Maximum concurrent active TCP port checks across the agent.
pub max_vip_checks: usize,
/// Maximum signed fields per VIP, including removed fields.
pub max_vip_fields: usize,
/// Maximum listeners per VIP.
pub max_vip_listeners: usize,
/// Maximum backend endpoints per listener.
pub max_vip_backends: usize,
/// Maximum simultaneous local VIP flow bindings.
pub max_vip_flows: usize,
/// Maximum incomplete IPv4 datagrams per network in VIP reassembly.
pub max_vip_fragments: usize,
/// Largest accepted control frame payload, in bytes.
pub max_frame_len: usize,
/// Largest accepted hostname, in bytes.
@@ -166,12 +185,16 @@ pub struct Limits {
pub max_capabilities: usize,
/// Largest opaque plugin payload, in bytes.
pub max_capability_data_len: usize,
/// Largest private transport negotiation payload (also hard-capped at 4096 bytes).
pub max_transport_payload_len: usize,
/// Largest accepted echo payload in a ping/pong exchange, in bytes.
pub max_echo_payload_len: usize,
/// Largest accepted free-text reason string, in bytes.
pub max_reason_len: usize,
/// Largest number of signed records accepted in one snapshot.
pub max_state_records: usize,
/// Maximum durable retirement markers retained per network.
pub max_retirements: usize,
/// Deadline for the whole handshake.
pub handshake_timeout: Duration,
/// Deadline for one outbound dial attempt.
@@ -201,13 +224,23 @@ pub struct Limits {
impl Default for Limits {
fn default() -> Self {
Self {
max_vips: 64,
max_vip_tombstones: 1024,
max_vip_checks: 32,
max_vip_fields: 192,
max_vip_listeners: 16,
max_vip_backends: 32,
max_vip_flows: 4096,
max_vip_fragments: 64,
max_frame_len: 64 * 1024,
max_hostname_len: 255,
max_capabilities: 16,
max_transport_payload_len: 4096,
max_capability_data_len: 4 * 1024,
max_echo_payload_len: 4 * 1024,
max_reason_len: 256,
max_state_records: crate::state::MAX_RECORDS_PER_MESSAGE,
max_retirements: 1024,
handshake_timeout: Duration::from_secs(10),
dial_timeout: Duration::from_secs(10),
write_timeout: Duration::from_secs(30),
@@ -323,8 +356,13 @@ pub struct AgentConfig {
pub limits: Limits,
/// Reconnect backoff policy.
pub reconnect: ReconnectPolicy,
/// IP plugins whose capabilities are announced and dispatched.
pub plugins: Vec<SharedPlugin>,
/// External data carriers whose capabilities are announced and dispatched.
pub carriers: Vec<crate::dataplane::transport::SharedCarrier>,
/// The single internal end-to-end engine, independent of carrier selection.
pub tunnel: Option<SharedPlugin>,
/// Initial ordered selection for networks without a saved override.
/// `None` enables all registered carriers; an empty list is control-only.
pub default_protocols: Option<Vec<String>>,
/// Custom packet transports registered per protocol.
pub custom_transports:
std::collections::HashMap<String, Arc<dyn crate::dataplane::PacketTransport>>,
@@ -339,7 +377,11 @@ pub struct AgentConfig {
pub interface_name: String,
/// The interface MTU.
pub interface_mtu: u32,
/// The IPv4 overlay range this agent proposes.
/// Whether new networks derive their IPv4 range from their network id.
///
/// Enabled by default. Explicit ranges and IPv4 opt-out disable this.
pub overlay_ipv4_auto: bool,
/// The IPv4 overlay range this agent proposes when automatic selection is off.
///
/// Addresses are allocated from it and recorded in signed state, so a
/// participant keeps the same one across restarts. A network that has
@@ -368,12 +410,15 @@ impl AgentConfig {
discovery_interval: Duration::from_secs(5),
limits: Limits::default(),
reconnect: ReconnectPolicy::default(),
plugins: Vec::new(),
carriers: Vec::new(),
tunnel: None,
default_protocols: None,
custom_transports: std::collections::HashMap::new(),
tun_factory: None,
interface_name: "tsun0".to_string(),
interface_mtu: 1280,
overlay_ipv4_range: Some(crate::state::DEFAULT_IPV4_RANGE),
overlay_ipv4_auto: true,
overlay_ipv4_range: None,
}
}
@@ -445,13 +490,20 @@ impl AgentConfig {
/// Sets the IPv4 overlay range this agent proposes, or disables IPv4.
pub fn with_overlay_ipv4_range(mut self, range: Option<crate::state::Ipv4Range>) -> Self {
self.overlay_ipv4_auto = false;
self.overlay_ipv4_range = range;
self
}
/// Registers an IP plugin.
pub fn with_plugin(mut self, plugin: SharedPlugin) -> Self {
self.plugins.push(plugin);
/// Registers an external data carrier.
pub fn with_carrier(mut self, plugin: crate::dataplane::transport::SharedCarrier) -> Self {
self.carriers.push(plugin);
self
}
/// Installs the internal encryption engine. It is never a selectable carrier.
pub fn with_tunnel(mut self, tunnel: SharedPlugin) -> Self {
self.tunnel = Some(tunnel);
self
}
@@ -505,9 +557,9 @@ impl std::fmt::Debug for AgentConfig {
.field("limits", &self.limits)
.field("reconnect", &self.reconnect)
.field(
"plugins",
"carriers",
&self
.plugins
.carriers
.iter()
.map(|p| p.protocol_id().to_string())
.collect::<Vec<_>>(),
+54 -24
View File
@@ -1,30 +1,21 @@
//! Boundary between the control plane core and future IP plugins.
//! Boundaries between the agent, one IP encryption tunnel, and external carriers.
//!
//! The data plane is where actual IP connectivity is created. WireGuard is the
//! first planned plugin; none is implemented here.
//! The core moves bounded opaque capabilities without parsing cipher payloads.
//! An [`IpPlugin`] sees routed IP packets and a logical [`PacketLink`] per peer;
//! it never learns reachability or the network secret. The agent configures one
//! such plugin. Built-in agents use the same internal WireGuard cipher for every
//! peer, regardless of which external transports carry the encrypted bytes.
//!
//! Two rules shape this module:
//!
//! 1. **The core never parses plugin payloads.** A [`PluginCapability`] carries
//! a protocol id, a version, an enabled flag and a bounded opaque blob. The
//! core transports the blob and hands it to the matching plugin. It does not
//! know what a WireGuard configuration looks like.
//! 2. **Plugin keys and lifecycle are separate from iroh identity and from the
//! network secret.** A plugin owns its own keys and its own system objects.
//!
//! An iroh address is *not* automatically a WireGuard address. A future plugin
//! is expected to gather its own reachability information and ship it through
//! the control plane as its announcement payload.
//!
//! A data plane failure never stops the daemon: errors returned here are
//! recorded and surfaced, the control plane keeps running.
//! [`transport::DataCarrier`] owns external capability negotiation and lifecycle.
//! It sees reachability but never plaintext overlay packets. A relay forwards
//! the encrypted inner bytes without entering an IP plugin or the TUN.
//! Data-plane failure never stops control sessions or discovery.
pub mod relay;
pub mod routing;
pub mod transport;
pub mod tunnel;
use std::sync::Arc;
use std::sync::{Arc, Weak};
use iroh::EndpointId;
use tokio::sync::mpsc;
@@ -35,11 +26,37 @@ use crate::identity::NetworkId;
pub use transport::{
MultiPacketTransport, PacketLink, PacketTransport, SharedLink, TransportError,
};
pub use tunnel::{GenericTunnelPlugin, TunnelCodec};
/// Maximum length of a plugin protocol identifier.
pub const MAX_PROTOCOL_ID_LEN: usize = 32;
/// Validates bounded local protocol preferences before storing or applying them.
pub(crate) fn validate_protocols(protocols: &[String], max: usize) -> crate::error::Result<()> {
if protocols.len() > max {
return Err(crate::Error::InvalidProtocols(format!(
"at most {max} protocols are allowed"
)));
}
for (index, name) in protocols.iter().enumerate() {
if name.is_empty()
|| name.len() > MAX_PROTOCOL_ID_LEN
|| !name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
{
return Err(crate::Error::InvalidProtocols(
"names must be 1–32 ASCII letters, digits, hyphens or underscores".into(),
));
}
if protocols[..index].contains(name) {
return Err(crate::Error::InvalidProtocols(format!(
"`{name}` is listed more than once"
)));
}
}
Ok(())
}
/// An announcement of one IP plugin's capability.
///
/// `data` is opaque to the core. Nothing in it may be interpreted as a shell
@@ -159,6 +176,7 @@ pub struct PluginContext {
/// Where decrypted packets go. Absent when nothing is carrying traffic,
/// in which case a protocol still runs and its packets are discarded.
sink: Option<Arc<dyn PacketSink>>,
routes: Weak<crate::overlay::RoutingTable>,
}
impl PluginContext {
@@ -166,14 +184,23 @@ impl PluginContext {
sender: mpsc::Sender<PluginRequest>,
local: EndpointId,
sink: Option<Arc<dyn PacketSink>>,
routes: &Arc<crate::overlay::RoutingTable>,
) -> Self {
Self {
sender: Some(sender),
local: Some(local),
sink,
routes: Arc::downgrade(routes),
}
}
/// The peer whose tunnel should stay ready for traffic even while idle.
/// Only the locally selected internet exit in its own network qualifies.
pub fn warm_peer(&self, network: NetworkId) -> Option<EndpointId> {
let (selected, peer) = self.routes.upgrade()?.exit_via()?;
(selected == network).then_some(peer)
}
/// Where to hand a decrypted packet.
///
/// Always answers: with no interface to write to, the packets are
@@ -191,15 +218,15 @@ impl PluginContext {
sender: None,
local: None,
sink: None,
routes: Weak::new(),
}
}
/// A context configured with a custom packet sink.
pub fn with_sink(sink: Arc<dyn PacketSink>) -> Self {
Self {
sender: None,
local: None,
sink: Some(sink),
..Self::detached()
}
}
@@ -214,6 +241,7 @@ impl PluginContext {
sender: Some(sender),
local: Some(local),
sink,
..Self::detached()
}
}
@@ -411,7 +439,9 @@ pub trait IpPlugin: Send + Sync + std::fmt::Debug + 'static {
/// Always preceded by [`IpPlugin::on_network_deactivated`], so this is
/// only about what outlives a session. Defaulted to nothing, for a
/// plugin that stores nothing.
fn on_network_forgotten(&self, _network: NetworkId) {}
fn on_network_forgotten(&self, _network: NetworkId) -> BoxFuture<'_, ()> {
Box::pin(async {})
}
/// Called once when the agent shuts down.
///
+41 -3
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) {
@@ -492,11 +521,13 @@ impl RelayHub {
}
}
/// Revokes all links and topology involving a departed authenticated peer.
pub fn remove_peer(&self, peer: EndpointId) {
/// 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();
raw.reader.abort();
}
}
@@ -511,6 +542,13 @@ impl RelayHub {
link.close();
}
}
state.publish();
}
/// Revokes all links and topology involving a departed authenticated peer.
pub fn remove_peer(&self, peer: EndpointId) {
self.clear_peer_links(peer);
let mut state = self.state();
state.members.remove(peer.as_bytes());
state.graph.remove(peer.as_bytes());
for neighbors in state.graph.values_mut() {
@@ -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,
@@ -0,0 +1,44 @@
//! External link negotiation, deliberately separate from the IP encryption plugin.
use crate::dataplane::{PluginCapability, PluginError, ProtocolOption};
use crate::{BoxFuture, NetworkId};
use iroh::EndpointId;
use std::sync::Arc;
/// Capability and lifecycle of one external data carrier.
/// Only this layer sees reachability. It never receives plaintext overlay IP packets.
pub trait DataCarrier: Send + Sync + std::fmt::Debug + 'static {
/// External protocol identifier used in local policy and peer negotiation.
fn protocol_id(&self) -> &str;
/// Wire version, independent of software releases and the internal tunnel.
fn protocol_version(&self) -> u16;
/// Supported carrier settings.
fn options(&self) -> &'static [ProtocolOption] {
&[]
}
/// Bounded opaque reachability/negotiation capability for one network.
fn local_capability(&self, network: NetworkId)
-> Result<Option<PluginCapability>, PluginError>;
/// Installs a capability received through an authenticated membership session.
fn on_peer_capability(
&self,
network: NetworkId,
peer: EndpointId,
capability: &PluginCapability,
) -> Result<(), PluginError>;
/// Supplies the actual owned interface name, including kernel-assigned names.
fn on_interface_ready(&self, _name: &str) {}
/// Activates this carrier for one local network.
fn on_network_activated(&self, _network: NetworkId) {}
/// Retires all negotiation and links for this member.
fn on_peer_gone(&self, network: NetworkId, peer: EndpointId);
/// Retires this network's sockets and negotiations.
fn on_network_deactivated(&self, network: NetworkId);
/// Forgets durable carrier settings, if any.
fn on_network_forgotten(&self, _network: NetworkId) {}
/// Stops carrier tasks, with the agent enforcing a shutdown deadline.
fn shutdown(&self) -> BoxFuture<'_, ()> {
Box::pin(async {})
}
}
/// One shared carrier adapter.
pub type SharedCarrier = Arc<dyn DataCarrier>;
@@ -0,0 +1,386 @@
//! 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::{LinkQuality, PacketLink, SharedLink, TransportError};
use crate::{BoxFuture, NetworkId};
use bytes::Bytes;
use hmac::{Hmac, KeyInit, Mac};
use iroh::EndpointId;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::{mpsc, watch};
#[derive(Clone, Serialize, Deserialize, zeroize::ZeroizeOnDrop)]
pub(crate) struct Settings {
marker: [u8; 16],
key: [u8; 32],
}
impl Settings {
pub(crate) fn fresh() -> Self {
Self {
marker: rand::random(),
key: rand::random(),
}
}
}
impl std::fmt::Debug for Settings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("HealthSettings([REDACTED])")
}
}
struct Samples {
pending: VecDeque<(u64, Instant, usize)>,
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, size: usize) {
self.pending.push_back((seq, now, size));
}
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, size: usize) -> bool {
if let Some(i) = self
.pending
.iter()
.position(|(n, _, expected)| *n == seq && *expected == size)
&& 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);
}
return success;
}
false
}
fn expire(&mut self, now: Instant) {
while self
.pending
.front()
.is_some_and(|(_, at, _)| now.duration_since(*at) >= PROBE_TIMEOUT)
{
self.pending.pop_front();
self.record(None);
}
}
fn degraded(&self) -> bool {
self.recent.len() >= 15
&& 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.
pub(crate) struct HealthLink {
raw: SharedLink,
settings: Mutex<Option<Settings>>,
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 {
f.debug_struct("HealthLink")
.field("raw", &self.raw)
.finish_non_exhaustive()
}
}
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
match m.lock() {
Ok(g) => g,
Err(p) => p.into_inner(),
}
}
impl HealthLink {
pub(crate) fn new(raw: SharedLink, local: EndpointId, settings: Option<Settings>) -> Arc<Self> {
let (tx, rx) = mpsc::channel(64);
let (stop, _) = watch::channel(false);
let link = Arc::new(Self {
raw: raw.clone(),
settings: Mutex::new(settings),
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();
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(1));
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut samples = Samples::new();
let mut sequence = rand::random::<u64>();
let mut since: Option<Instant> = None;
let mut marker = None;
loop {
tokio::select! {
biased;
_=stopped.changed()=>break,
_=interval.tick()=>{
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;
}
sequence=sequence.wrapping_add(1);
let size=raw.max_datagram_size();
let packet=probe(&settings,local,1,sequence,size.min(1000));
samples.sent(sequence,now,packet.len());
let _=raw.send(packet);
}
packet=raw.recv()=>{
let Some(packet)=packet else{break;};let Some(link)=weak.upgrade()else{break;};
let settings=lock(&link.settings).clone();
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 && marker == Some(settings.marker) {
if samples.acknowledge(seq, Instant::now(), packet.len()) {
raw.confirm_delivery();
}
*lock(&link.quality) = samples.quality().map(|q| (settings.marker, q));
}
}
} else {let _=tx.try_send(packet);}
}
}
}
raw.close();
if let Some(link) = weak.upgrade() {
link.stop.send_replace(true);
}
});
link
}
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)];
bytes[..16].copy_from_slice(&settings.marker);
bytes[16] = kind;
bytes[17..25].copy_from_slice(&seq.to_be_bytes());
rand::fill(&mut bytes[25..size.max(57) - 32]);
let tail = bytes.len() - 32;
if let Ok(mut mac) = <Hmac<Sha256> as KeyInit>::new_from_slice(&settings.key) {
mac.update(sender.as_bytes());
mac.update(&bytes[..tail]);
bytes[tail..].copy_from_slice(&mac.finalize().into_bytes());
}
Bytes::from(bytes)
}
fn verify(settings: &Settings, sender: EndpointId, bytes: &[u8]) -> Option<(u8, u64)> {
if bytes.len() < 57 || !bytes.starts_with(&settings.marker) {
return None;
}
let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(&settings.key).ok()?;
let tail = bytes.len() - 32;
mac.update(sender.as_bytes());
mac.update(&bytes[..tail]);
mac.verify_slice(&bytes[tail..]).ok()?;
Some((
bytes[16],
u64::from_be_bytes(bytes.get(17..25)?.try_into().ok()?),
))
}
impl PacketLink for HealthLink {
fn network(&self) -> NetworkId {
self.raw.network()
}
fn peer(&self) -> EndpointId {
self.raw.peer()
}
fn max_datagram_size(&self) -> usize {
self.raw.max_datagram_size()
}
fn send(&self, payload: Bytes) -> Result<(), TransportError> {
if self.is_closed() {
Err(TransportError::Closed)
} else {
self.raw.send(payload)
}
}
fn send_flow(
&self,
payload: Bytes,
flow: super::super::routing::FlowId,
) -> Result<(), TransportError> {
if self.is_closed() {
Err(TransportError::Closed)
} else {
self.raw.send_flow(payload, flow)
}
}
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
Box::pin(async move {
let mut stop = self.stop.subscribe();
if *stop.borrow() {
return None;
}
let mut rx = self.rx.lock().await;
tokio::select! {biased;_=stop.changed()=>None,packet=rx.recv()=>packet}
})
}
fn closed(&self) -> BoxFuture<'_, ()> {
Box::pin(async move {
let mut stop = self.stop.subscribe();
if !*stop.borrow() {
let _ = stop.changed().await;
}
})
}
fn is_closed(&self) -> bool {
*self.stop.borrow() || self.raw.is_closed()
}
fn close(&self) {
self.stop.send_replace(true);
self.raw.close();
}
fn failure_reason(&self) -> Option<String> {
lock(&self.reason)
.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()
}
}
impl Drop for HealthLink {
fn drop(&mut self) {
self.stop.send_replace(true);
self.raw.close();
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn an_authenticated_short_reply_does_not_prove_full_size_delivery() {
let start = Instant::now();
let mut samples = Samples::new();
samples.sent(7, start, 1000);
assert!(!samples.acknowledge(7, start, 57));
assert!(samples.quality().is_none());
assert!(samples.acknowledge(7, start, 1000));
}
#[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, 1000);
samples.acknowledge(seq, start + Duration::from_millis(delay), 1000);
}
assert!(!samples.acknowledge(1, start + Duration::from_secs(1), 1000));
samples.sent(4, start, 1000);
samples.expire(start + Duration::from_secs(3));
assert!(!samples.acknowledge(4, start + Duration::from_secs(4), 1000));
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, 1000);
samples.acknowledge(seq, sent + Duration::from_millis(80), 1000);
}
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();
let now = Instant::now();
for seq in 0..20 {
samples.sent(seq, now, 1000);
if seq % 5 == 0 {
samples.acknowledge(seq, now, 1000);
}
}
assert!(!samples.degraded());
samples.expire(now + Duration::from_secs(4));
assert!(samples.degraded());
for seq in 20..40 {
samples.sent(seq, now, 1000);
samples.acknowledge(seq, now, 1000);
}
samples.expire(now + Duration::from_secs(4));
assert!(!samples.degraded());
}
#[test]
fn a_forged_or_reflected_probe_cannot_claim_delivery() {
let a = crate::identity::DeviceIdentity::generate().endpoint_id();
let b = crate::identity::DeviceIdentity::generate().endpoint_id();
let settings = Settings::fresh();
let packet = probe(&settings, a, 1, 42, 1100);
assert_eq!(verify(&settings, a, &packet), Some((1, 42)));
assert!(verify(&settings, b, &packet).is_none());
let mut forged = packet.to_vec();
forged[16] = 2;
assert!(verify(&settings, a, &forged).is_none());
}
}
@@ -40,6 +40,49 @@ use crate::proto::{read_frame, write_frame};
use super::fragments::{self, Reassembler};
use super::{InboundLink, PacketLink, PacketTransport, SharedLink, TransportError};
/// QUIC carrier capability. Encryption of end-to-end IP packets is independent.
#[derive(Debug, Default)]
pub struct IrohCarrier;
impl super::DataCarrier for IrohCarrier {
fn protocol_id(&self) -> &str {
"wg-quic"
}
fn protocol_version(&self) -> u16 {
1
}
fn local_capability(
&self,
_: NetworkId,
) -> Result<Option<crate::dataplane::PluginCapability>, crate::dataplane::PluginError> {
Ok(Some(crate::dataplane::PluginCapability {
protocol: self.protocol_id().into(),
version: self.protocol_version(),
enabled: true,
data: Vec::new(),
}))
}
fn on_peer_capability(
&self,
_: NetworkId,
_: EndpointId,
capability: &crate::dataplane::PluginCapability,
) -> Result<(), crate::dataplane::PluginError> {
if capability.protocol != self.protocol_id()
|| capability.version != self.protocol_version()
|| !capability.enabled
|| !capability.data.is_empty()
{
return Err(crate::dataplane::PluginError::Rejected(
"unsupported QUIC carrier capability".into(),
));
}
Ok(())
}
fn on_peer_gone(&self, _: NetworkId, _: EndpointId) {}
fn on_network_deactivated(&self, _: NetworkId) {}
}
/// What the iroh transport needs from the agent.
///
/// Implemented by the agent, which is the only thing that knows which networks
@@ -97,6 +140,9 @@ impl IrohLink {
}
impl PacketLink for IrohLink {
fn close(&self) {
self.conn.close(0u32.into(), b"data link retired");
}
fn network(&self) -> NetworkId {
self.network
}
@@ -187,6 +233,10 @@ impl PacketLink for IrohLink {
self.conn.close_reason().is_some()
}
fn failure_reason(&self) -> Option<String> {
self.conn.close_reason().map(|reason| reason.to_string())
}
fn path_description(&self) -> String {
// Report what iroh actually knows, never a guess.
let snapshot = crate::net::snapshot_connection(&self.conn);
@@ -261,7 +311,8 @@ impl IrohTransport {
));
}
let serves = self.lookup.serves(outcome.network_id, &open.protocol).await;
let serves = open.protocol == "wg-quic"
&& self.lookup.serves(outcome.network_id, &open.protocol).await;
if open.max_datagram == 0 || conn.max_datagram_size().is_none() {
return Err(TransportError::Other(
"data channel has no datagram support".into(),
@@ -322,6 +373,12 @@ impl PacketTransport for IrohTransport {
"data channel protocol id is out of bounds".into(),
));
}
// This default must never impersonate a missing native carrier.
if protocol != "wg-quic" {
return Err(TransportError::Declined(format!(
"no native `{protocol}` data transport registered"
)));
}
let keys = self
.lookup
.snapshot()
@@ -30,12 +30,18 @@
//! one plugin protocol.
mod fragments;
pub(crate) mod health;
pub mod iroh_link;
pub mod carrier;
pub use carrier::{DataCarrier, SharedCarrier};
use std::sync::Arc;
use std::time::{Duration, Instant};
use bytes::Bytes;
use iroh::EndpointId;
use serde::{Deserialize, Serialize};
use crate::BoxFuture;
use crate::identity::NetworkId;
@@ -68,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.
@@ -112,6 +137,23 @@ pub trait PacketLink: Send + Sync + std::fmt::Debug + 'static {
/// keeping a task parked on [`PacketLink::closed`].
fn is_closed(&self) -> bool;
/// Explicitly retires a physical link. Implementations should wake readers.
fn close(&self) {}
/// Observed reason for retiring this link, if available.
fn failure_reason(&self) -> Option<String> {
None
}
/// Fresh measurements from this physical link's own authenticated probes.
fn quality(&self) -> Option<LinkQuality> {
None
}
/// The link monitor received a timely, authenticated answer to a data probe
/// on this very link. A carrier can use it in place of its own idle probe.
fn confirm_delivery(&self) {}
/// A short description of the path in use, for diagnostics.
///
/// Reports what the transport actually knows. It must not invent a value.
@@ -121,6 +163,76 @@ pub trait PacketLink: Send + Sync + std::fmt::Debug + 'static {
/// A shared handle to a link.
pub type SharedLink = std::sync::Arc<dyn PacketLink>;
/// Maximum opaque pair-negotiation payload.
pub const MAX_TRANSPORT_PAYLOAD: usize = 4096;
/// Private transport bytes, never included in Debug output.
#[derive(Clone, PartialEq, Eq, Serialize, zeroize::ZeroizeOnDrop)]
pub struct TransportPayload(Vec<u8>);
impl<'de> Deserialize<'de> for TransportPayload {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = TransportPayload;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "at most {MAX_TRANSPORT_PAYLOAD} private transport bytes")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(
self,
mut sequence: A,
) -> std::result::Result<Self::Value, A::Error> {
if sequence
.size_hint()
.is_some_and(|size| size > MAX_TRANSPORT_PAYLOAD)
{
return Err(serde::de::Error::custom("transport payload too large"));
}
let mut payload = TransportPayload(Vec::with_capacity(
sequence.size_hint().unwrap_or(0).min(MAX_TRANSPORT_PAYLOAD),
));
while let Some(byte) = sequence.next_element::<u8>()? {
if payload.0.len() == MAX_TRANSPORT_PAYLOAD {
return Err(serde::de::Error::custom("transport payload too large"));
}
payload.0.push(byte);
}
Ok(payload)
}
}
deserializer.deserialize_seq(Visitor)
}
}
impl TransportPayload {
/// Wraps bytes for one authenticated control session.
pub fn new(bytes: Vec<u8>) -> Self {
Self(bytes)
}
/// Borrows private bytes; callers must not log them.
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
}
impl std::fmt::Debug for TransportPayload {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("TransportPayload([REDACTED])")
}
}
/// Private control-plane sender for transports. Contains no network secret.
pub trait ControlSender: Send + Sync + std::fmt::Debug + 'static {
/// Queues a bounded message to one authenticated member of one network.
fn send<'a>(
&'a self,
network: NetworkId,
peer: EndpointId,
protocol: &'a str,
payload: TransportPayload,
) -> BoxFuture<'a, Result<(), TransportError>>;
}
/// An inbound link a peer opened towards us.
#[derive(Debug)]
pub struct InboundLink {
@@ -139,6 +251,18 @@ pub struct InboundLink {
/// The agent owns one of these and hands links to plugins; plugins never call
/// it directly.
pub trait PacketTransport: Send + Sync + std::fmt::Debug + 'static {
/// Supplies a private sender before network activation.
fn attach_control(&self, _control: Arc<dyn ControlSender>) {}
/// Validates and queues private negotiation received from an authenticated member.
fn on_control(
&self,
_network: NetworkId,
_peer: EndpointId,
_protocol: &str,
_payload: &[u8],
) -> Result<(), TransportError> {
Err(TransportError::Declined(self.name().into()))
}
/// A short name used in diagnostics.
fn name(&self) -> &str;
@@ -184,6 +308,24 @@ impl MultiPacketTransport {
}
impl PacketTransport for MultiPacketTransport {
fn attach_control(&self, control: Arc<dyn ControlSender>) {
self.default.attach_control(control.clone());
for transport in self.by_protocol.values() {
transport.attach_control(control.clone());
}
}
fn on_control(
&self,
network: NetworkId,
peer: EndpointId,
protocol: &str,
payload: &[u8],
) -> Result<(), TransportError> {
match self.by_protocol.get(protocol) {
Some(transport) => transport.on_control(network, peer, protocol, payload),
None => Err(TransportError::Declined(protocol.into())),
}
}
fn name(&self) -> &str {
"multi"
}
-380
View File
@@ -1,380 +0,0 @@
//! Generic harness for IP tunnel plugins.
//!
//! Implementing [`super::IpPlugin`] directly requires managing per-peer background
//! tasks, synchronization, packet queues, and graceful shutdown.
//!
//! [`TunnelCodec`] provides a simplified interface where a plugin author only
//! defines cryptographic transformation and handshake payloads.
//! [`GenericTunnelPlugin`] adapts any [`TunnelCodec`] into a full [`super::IpPlugin`].
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use bytes::Bytes;
use iroh::EndpointId;
use tokio::task::JoinHandle;
use super::{IpPlugin, PluginCapability, PluginContext, PluginError, ProtocolOption, SharedLink};
use crate::BoxFuture;
use crate::identity::NetworkId;
/// The simplified contract for an IP tunnel protocol implementation.
///
/// Implementors only handle key announcements, link lifecycle events,
/// and packet encrypt/decrypt. Concurrency and task management are handled
/// by [`GenericTunnelPlugin`].
pub trait TunnelCodec: Send + Sync + 'static {
/// Protocol identifier, e.g. `tcp-tls`.
fn protocol_id(&self) -> &str;
/// Protocol wire version.
fn protocol_version(&self) -> u16;
/// Options accepted by the protocol.
fn options(&self) -> &'static [ProtocolOption] {
&[]
}
/// Generates local capability announcement data for a network.
fn local_capability_data(&self, network: NetworkId) -> Result<Vec<u8>, PluginError>;
/// Handles a peer's announced capability payload.
fn on_peer_capability_data(
&self,
network: NetworkId,
peer: EndpointId,
data: &[u8],
) -> Result<(), PluginError>;
/// Called when an authenticated link to a peer is established.
fn on_peer_link_up(&self, network: NetworkId, peer: EndpointId, link: &SharedLink) {
let _ = (network, peer, link);
}
/// Called when a peer goes away.
fn on_peer_down(&self, network: NetworkId, peer: EndpointId) {
let _ = (network, peer);
}
/// Encrypts an outbound IP packet into a payload to send over the link.
fn encrypt(
&self,
network: NetworkId,
peer: EndpointId,
packet: &[u8],
) -> Result<Bytes, PluginError>;
/// Decrypts an inbound payload from the link into an IP packet.
fn decrypt(
&self,
network: NetworkId,
peer: EndpointId,
payload: &[u8],
) -> Result<Bytes, PluginError>;
/// Called during shutdown.
fn shutdown<'a>(&'a self) -> BoxFuture<'a, ()> {
Box::pin(async {})
}
}
struct TunnelPeerState {
link: SharedLink,
tx_packets: AtomicU64,
rx_packets: AtomicU64,
tx_bytes: AtomicU64,
rx_bytes: AtomicU64,
dropped: AtomicU64,
established_at: std::time::Instant,
}
/// Statistics and status for one active peer in [`GenericTunnelPlugin`].
#[derive(Debug, Clone)]
pub struct TunnelPeerReport {
/// Peer endpoint identity.
pub peer: EndpointId,
/// Protocol identifier.
pub protocol: String,
/// Human-readable path description.
pub path: String,
/// Packets successfully encrypted and sent.
pub tx_packets: u64,
/// Packets successfully received and decrypted.
pub rx_packets: u64,
/// Plaintext bytes successfully encrypted and sent.
pub tx_bytes: u64,
/// Plaintext bytes successfully received and decrypted.
pub rx_bytes: u64,
/// Packets dropped due to encryption/decryption/send failures.
pub dropped: u64,
/// Uptime in seconds since the data link was established.
pub uptime_secs: u64,
}
/// Generic wrapper that turns a [`TunnelCodec`] into a full [`IpPlugin`].
pub struct GenericTunnelPlugin<C: TunnelCodec> {
codec: Arc<C>,
context: Mutex<Option<PluginContext>>,
links: RwLock<HashMap<(NetworkId, EndpointId), Arc<TunnelPeerState>>>,
tasks: Mutex<HashMap<(NetworkId, EndpointId), JoinHandle<()>>>,
}
impl<C: TunnelCodec> GenericTunnelPlugin<C> {
/// Wraps `codec` into an [`IpPlugin`].
pub fn new(codec: C) -> Self {
Self {
codec: Arc::new(codec),
context: Mutex::new(None),
links: RwLock::new(HashMap::new()),
tasks: Mutex::new(HashMap::new()),
}
}
/// Returns a reference to the underlying codec.
pub fn codec(&self) -> &C {
&self.codec
}
/// Returns the active peers with established data links for a network.
pub fn active_peers(&self, network: NetworkId) -> Vec<TunnelPeerReport> {
let guard = match self.links.read() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
guard
.iter()
.filter(|((net, _), _)| *net == network)
.map(|((_, peer), state)| TunnelPeerReport {
peer: *peer,
protocol: self.codec.protocol_id().to_string(),
path: state.link.path_description(),
tx_packets: state.tx_packets.load(Ordering::Relaxed),
rx_packets: state.rx_packets.load(Ordering::Relaxed),
tx_bytes: state.tx_bytes.load(Ordering::Relaxed),
rx_bytes: state.rx_bytes.load(Ordering::Relaxed),
dropped: state.dropped.load(Ordering::Relaxed),
uptime_secs: state.established_at.elapsed().as_secs(),
})
.collect()
}
}
impl<C: TunnelCodec> std::fmt::Debug for GenericTunnelPlugin<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GenericTunnelPlugin")
.field("protocol_id", &self.codec.protocol_id())
.field("protocol_version", &self.codec.protocol_version())
.finish()
}
}
impl<C: TunnelCodec> IpPlugin for GenericTunnelPlugin<C> {
fn protocol_id(&self) -> &str {
self.codec.protocol_id()
}
fn protocol_version(&self) -> u16 {
self.codec.protocol_version()
}
fn options(&self) -> &'static [ProtocolOption] {
self.codec.options()
}
fn attach(&self, context: PluginContext) {
if let Ok(mut guard) = self.context.lock() {
*guard = Some(context);
}
}
fn local_capability(
&self,
network: NetworkId,
) -> Result<Option<PluginCapability>, PluginError> {
let data = self.codec.local_capability_data(network)?;
Ok(Some(PluginCapability {
protocol: self.codec.protocol_id().to_string(),
version: self.codec.protocol_version(),
enabled: true,
data,
}))
}
fn on_peer_capability(
&self,
network: NetworkId,
peer: EndpointId,
capability: &PluginCapability,
) -> Result<(), PluginError> {
if capability.protocol != self.codec.protocol_id() {
return Ok(());
}
self.codec
.on_peer_capability_data(network, peer, &capability.data)
}
fn carry(&self, network: NetworkId, peer: EndpointId, packet: bytes::Bytes) -> bool {
let state = {
let guard = match self.links.read() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
guard.get(&(network, peer)).cloned()
};
let Some(state) = state else {
return false;
};
match self.codec.encrypt(network, peer, &packet) {
Ok(ciphertext) => {
if state.link.send(ciphertext).is_ok() {
state.tx_packets.fetch_add(1, Ordering::Relaxed);
state
.tx_bytes
.fetch_add(packet.len() as u64, Ordering::Relaxed);
true
} else {
state.dropped.fetch_add(1, Ordering::Relaxed);
false
}
}
Err(err) => {
state.dropped.fetch_add(1, Ordering::Relaxed);
tracing::debug!(%peer, %err, "tunnel encrypt failed");
false
}
}
}
fn on_peer_link(&self, network: NetworkId, peer: EndpointId, link: SharedLink) {
let state = Arc::new(TunnelPeerState {
link: Arc::clone(&link),
tx_packets: AtomicU64::new(0),
rx_packets: AtomicU64::new(0),
tx_bytes: AtomicU64::new(0),
rx_bytes: AtomicU64::new(0),
dropped: AtomicU64::new(0),
established_at: std::time::Instant::now(),
});
{
let mut guard = match self.links.write() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
guard.insert((network, peer), Arc::clone(&state));
}
self.codec.on_peer_link_up(network, peer, &link);
let codec = Arc::clone(&self.codec);
let sink = match self.context.lock() {
Ok(g) => g.as_ref().map(|ctx| ctx.packet_sink()),
Err(p) => p.into_inner().as_ref().map(|ctx| ctx.packet_sink()),
};
let rx_link = Arc::clone(&link);
let rx_state = Arc::clone(&state);
let handle = tokio::spawn(async move {
while let Some(payload) = rx_link.recv().await {
match codec.decrypt(network, peer, &payload) {
Ok(packet) => {
rx_state.rx_packets.fetch_add(1, Ordering::Relaxed);
rx_state
.rx_bytes
.fetch_add(packet.len() as u64, Ordering::Relaxed);
if let Some(ref sink) = sink {
sink.deliver(network, peer, packet).await;
}
}
Err(err) => {
rx_state.dropped.fetch_add(1, Ordering::Relaxed);
tracing::debug!(%peer, %err, "tunnel decrypt failed");
}
}
}
});
let mut guard = match self.tasks.lock() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
if let Some(old) = guard.insert((network, peer), handle) {
old.abort();
}
}
fn on_peer_gone(&self, network: NetworkId, peer: EndpointId) {
{
let mut guard = match self.tasks.lock() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
if let Some(task) = guard.remove(&(network, peer)) {
task.abort();
}
}
{
let mut guard = match self.links.write() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
guard.remove(&(network, peer));
}
self.codec.on_peer_down(network, peer);
}
fn on_network_deactivated(&self, network: NetworkId) {
let keys_to_remove: Vec<(NetworkId, EndpointId)> = {
let guard = match self.tasks.lock() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
guard
.keys()
.filter(|(net, _)| *net == network)
.copied()
.collect()
};
{
let mut guard = match self.tasks.lock() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
for key in &keys_to_remove {
if let Some(task) = guard.remove(key) {
task.abort();
}
}
}
{
let mut guard = match self.links.write() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
guard.retain(|(net, _), _| *net != network);
}
}
fn shutdown<'a>(&'a self) -> BoxFuture<'a, ()> {
Box::pin(async move {
let mut tasks = Vec::new();
{
let mut guard = match self.tasks.lock() {
Ok(g) => g,
Err(p) => p.into_inner(),
};
for (_, task) in guard.drain() {
tasks.push(task);
}
}
for task in tasks {
task.abort();
}
self.codec.shutdown().await;
})
}
}
+50
View File
@@ -59,6 +59,56 @@ pub fn listen_plan(port: u16) -> ListenPlan {
pub use server::{DnsServer, SharedZone};
pub use zone::{Answer, Query, Zone, ZoneError, ZoneName, Zones};
/// Authoritative zones and the publication diagnostics for one agent snapshot.
pub struct RosterZones {
/// Member and service records indexed by zone.
pub zones: Zones,
/// Zone names in configured-network order.
pub labels: Vec<String>,
/// Unusable or potentially conflicting zone names.
pub warnings: Vec<String>,
}
impl RosterZones {
/// Build the desktop and mobile DNS view from the same signed state.
pub fn from_networks(networks: &[crate::NetworkStatus]) -> Self {
let mut zones = Vec::new();
let mut labels = Vec::new();
let mut warnings = Vec::new();
for network in networks {
let zone = match ZoneName::new(network.name.as_str()) {
Ok(zone) => zone,
Err(err) => {
warnings.push(format!(
"`{}` cannot be a zone, so its members have no names: {err}",
network.name
));
continue;
}
};
if let Some(warning) = zone.collision() {
warnings.push(warning);
}
labels.push(zone.as_str().to_string());
let members = network
.members
.iter()
.filter_map(|member| Some((member.hostname.clone()?, member.overlay_address_v4?)));
let services = network
.vips
.iter()
.filter(|vip| vip.error.is_none())
.filter_map(|vip| Some((vip.config.name.clone(), vip.address?)));
zones.push(Zone::new(zone, members.chain(services)).with_reverse_range(network.range));
}
Self {
zones: Zones::new(zones),
labels,
warnings,
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+50 -19
View File
@@ -81,7 +81,22 @@ impl SharedZone {
/// server should reply to, and replying anyway would make this a useful
/// amplifier for somebody spoofing a source address.
pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
let packet = simple_dns::Packet::parse(query).ok()?;
match resolve(zones, query)? {
Resolution::Local(reply) | Resolution::Outside(reply) => Some(reply),
}
}
/// An authoritative decision for a host resolver that also handles external domains.
pub enum Resolution {
/// Answer locally, including authoritative denials and protocol errors.
Local(Vec<u8>),
/// A well-formed question outside all mesh zones, with the authoritative server's REFUSED reply.
Outside(Vec<u8>),
}
/// Distinguish an external question from an unknown name inside a mesh zone.
pub fn resolve(zones: &Zones, query: &[u8]) -> Option<Resolution> {
let packet = parse_message(query)?;
if packet.has_flags(PacketFlag::RESPONSE) {
return None;
}
@@ -95,18 +110,18 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
if packet.opcode() != simple_dns::OPCODE::StandardQuery {
*reply.rcode_mut() = RCODE::NotImplemented;
return reply.build_bytes_vec().ok();
return reply.build_bytes_vec().ok().map(Resolution::Local);
}
// Exactly one question. Zero is nothing to answer; more than one has no
// agreed meaning and every real server rejects it.
let [question] = packet.questions.as_slice() else {
*reply.rcode_mut() = RCODE::FormatError;
return reply.build_bytes_vec().ok();
return reply.build_bytes_vec().ok().map(Resolution::Local);
};
if !matches!(question.qclass, QCLASS::CLASS(simple_dns::CLASS::IN)) {
*reply.rcode_mut() = RCODE::Refused;
return reply.build_bytes_vec().ok();
return reply.build_bytes_vec().ok().map(Resolution::Local);
}
let qname = question.qname.to_string();
@@ -117,7 +132,10 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
None => {
reply.questions.push(question.clone());
*reply.rcode_mut() = RCODE::Refused;
return reply.build_bytes_vec_compressed().ok();
return reply
.build_bytes_vec_compressed()
.ok()
.map(Resolution::Outside);
}
};
reply.questions.push(question.clone());
@@ -163,7 +181,22 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
}
}
reply.build_bytes_vec_compressed().ok()
reply
.build_bytes_vec_compressed()
.ok()
.map(Resolution::Local)
}
/// Parse a DNS message only after bounding its section allocations against the bytes received.
pub fn parse_message(wire: &[u8]) -> Option<simple_dns::Packet<'_>> {
let header = wire.get(..12)?;
let counts = |at: usize| usize::from(u16::from_be_bytes([header[at], header[at + 1]]));
// Even a root question needs five bytes. An empty root resource record needs eleven.
let minimum = 12 + counts(4) * 5 + (counts(6) + counts(8) + counts(10)) * 11;
if wire.len() < minimum || wire.len() > usize::from(u16::MAX) {
return None;
}
simple_dns::Packet::parse(wire).ok()
}
/// The zone's start of authority.
@@ -202,8 +235,7 @@ fn query_kind(qtype: QTYPE) -> Query {
/// Whether the client offered EDNS, and so how large an answer it will take.
fn udp_limit(query: &[u8]) -> usize {
simple_dns::Packet::parse(query)
.ok()
parse_message(query)
.and_then(|packet| packet.opt().map(|opt| opt.udp_packet_size as usize))
.unwrap_or(CLASSIC_UDP_LIMIT as u16 as usize)
.clamp(CLASSIC_UDP_LIMIT, MAX_MESSAGE_LEN)
@@ -214,20 +246,19 @@ fn udp_limit(query: &[u8]) -> usize {
/// The records are dropped and the truncated bit set, which tells a resolver
/// to ask again over TCP. Sending a reply it cannot reassemble would just
/// look like packet loss.
fn truncate_for_udp(query: &[u8], reply: Vec<u8>) -> Vec<u8> {
let limit = udp_limit(query);
pub fn truncate_for_udp(query: &[u8], reply: Vec<u8>, payload_limit: usize) -> Vec<u8> {
let limit = udp_limit(query).min(payload_limit);
if reply.len() <= limit {
return reply;
}
let Ok(parsed) = simple_dns::Packet::parse(&reply) else {
let Some(mut short) = parse_message(&reply) else {
return reply;
};
let mut short = simple_dns::Packet::new_reply(parsed.id());
short.set_flags(PacketFlag::TRUNCATION | PacketFlag::AUTHORITATIVE_ANSWER);
*short.rcode_mut() = parsed.rcode();
for question in &parsed.questions {
short.questions.push(question.clone());
}
short.set_flags(PacketFlag::TRUNCATION);
short.answers.clear();
short.name_servers.clear();
short.additional_records.clear();
*short.opt_mut() = None;
short.build_bytes_vec().unwrap_or(reply)
}
@@ -264,7 +295,7 @@ impl DnsServer {
let Some(reply) = respond(&udp_zone.get(), query) else {
continue;
};
let reply = truncate_for_udp(query, reply);
let reply = truncate_for_udp(query, reply, MAX_MESSAGE_LEN);
if let Err(err) = udp.send_to(&reply, from).await {
tracing::debug!(%err, "dns udp reply failed");
}
@@ -494,7 +525,7 @@ mod tests {
"the test needs a big answer"
);
let short = truncate_for_udp(&query, full);
let short = truncate_for_udp(&query, full, MAX_MESSAGE_LEN);
assert!(short.len() <= CLASSIC_UDP_LIMIT);
let parsed = simple_dns::Packet::parse(&short).unwrap();
assert!(parsed.has_flags(PacketFlag::TRUNCATION));
+18
View File
@@ -208,6 +208,7 @@ pub enum Answer {
#[derive(Debug, Clone)]
pub struct Zone {
origin: ZoneName,
reverse_range: Option<crate::state::Ipv4Range>,
/// Name relative to the origin, to the addresses it answers to.
hosts: BTreeMap<String, Vec<Ipv4Addr>>,
/// Address to the name that holds it.
@@ -246,12 +247,23 @@ impl Zone {
let serial = content_serial(&hosts);
Self {
origin,
// Standalone authoritative zones retain their original broad PTR view.
// Agent snapshots scope the authority to each network's actual range.
reverse_range: Some(crate::state::Ipv4Range {
base: Ipv4Addr::UNSPECIFIED,
prefix_len: 0,
}),
hosts,
names,
serial,
}
}
pub(super) fn with_reverse_range(mut self, range: Option<crate::state::Ipv4Range>) -> Self {
self.reverse_range = range;
self
}
/// The zone's origin.
pub fn origin(&self) -> &ZoneName {
&self.origin
@@ -300,6 +312,12 @@ impl Zone {
/// Answers one question.
pub fn lookup(&self, qname: &str, query: Query) -> Answer {
if let Some(address) = reverse_address(qname) {
if !self
.reverse_range
.is_some_and(|range| range.contains(address))
{
return Answer::NotOurs;
}
return match self.names.get(&address) {
Some(name) if query == Query::Ptr => {
Answer::Name(format!("{name}.{}", self.origin.as_str()))
+19
View File
@@ -15,6 +15,12 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// A node-history cleanup is unsafe, stale or cannot be performed.
#[error("cannot forget node: {0}")]
ForgetNode(String),
/// An ordered local data-plane protocol selection is invalid.
#[error("invalid protocol selection: {0}")]
InvalidProtocols(String),
/// The supplied network name does not satisfy the documented rules.
#[error("invalid network name: {0}")]
InvalidNetworkName(&'static str),
@@ -97,6 +103,19 @@ pub enum Error {
#[error("network {0} is not configured")]
NetworkUnknown(NetworkId),
/// An overlay range overlaps networks already active on this agent.
#[error(
"network {network} cannot start: {range} overlaps active networks {conflicts:?}; switch to it to suspend those networks"
)]
NetworkRangeConflict {
/// Network that could not start.
network: NetworkId,
/// Its agreed or proposed range.
range: crate::state::Ipv4Range,
/// Active networks that must be suspended first.
conflicts: Vec<NetworkId>,
},
/// No session with that peer exists in the given network.
#[error("no authenticated session with peer {peer} in network {network}")]
NoSuchPeer {
+373 -7
View File
@@ -171,6 +171,33 @@ pub fn default_control_socket_path() -> PathBuf {
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Request {
/// Save a complete version-checked service draft or its deletion.
SaveVip {
/// Exact network id.
network_id: String,
/// Entire desired configuration.
config: crate::vip::VipConfig,
/// Revision originally displayed; absent for creation.
expected: Option<String>,
/// Remove the service permanently.
delete: bool,
},
/// Retire the selected offline member's observed claim.
ForgetNode {
/// Exact public network id.
network_id: String,
/// Exact device identity selected by the client.
peer: String,
/// Claim version displayed when the user selected the node.
expected_version: u64,
},
/// Replace one network's ordered local data-plane selection.
SetProtocols {
/// Public network identifier.
network_id: String,
/// Protocol names, best first; empty selects control only.
protocols: Vec<String>,
},
/// Report what the agent is doing.
Status,
/// Set local broadcast participation in one configured network.
@@ -255,6 +282,24 @@ pub enum Request {
impl std::fmt::Debug for Request {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Request::SaveVip {
network_id, config, ..
} => write!(f, "SaveVip {{ {network_id}, {} }}", config.id),
Request::ForgetNode {
network_id,
peer,
expected_version,
} => write!(
f,
"ForgetNode {{ {network_id}, peer: {peer}, version: {expected_version} }}"
),
Request::SetProtocols {
network_id,
protocols,
} => write!(
f,
"SetProtocols {{ {network_id}, protocols: {protocols:?} }}"
),
Request::Status => f.write_str("Status"),
Request::SetBroadcast {
network_id,
@@ -286,6 +331,12 @@ impl std::fmt::Debug for Request {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Response {
/// Accepted configuration with fresh local routing observations.
Vips(Vec<crate::vip::VipStatus>),
/// An observed offline claim was durably retired.
NodeForgotten(ForgottenNodeReport),
/// Accepted ordered protocol selection.
Protocols(Vec<String>),
/// A status report.
Status(Box<StatusReport>),
/// Accepted local broadcast participation.
@@ -312,6 +363,192 @@ pub enum Response {
Error(String),
}
/// The durable result of an offline-node cleanup.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ForgottenNodeReport {
/// Selected device identity.
pub peer: String,
/// The retired claim version, not a future-version ban.
pub record_version: u64,
/// Peers to which cleanup was immediately queued.
pub peers_told: u32,
}
/// Saves a whole VIP draft through the running agent.
pub async fn save_vip(
socket: &Path,
network_id: &str,
config: crate::vip::VipConfig,
expected: Option<String>,
delete: bool,
) -> Result<Vec<crate::vip::VipStatus>> {
match exchange(
socket,
&Request::SaveVip {
network_id: network_id.into(),
config,
expected,
delete,
},
EXCHANGE_TIMEOUT,
)
.await?
{
Response::Vips(vips) => Ok(vips),
Response::Error(reason) => Err(Error::Rejected { reason }),
_ => Err(Error::Rejected {
reason: "unexpected VIP response".into(),
}),
}
}
/// Resolves a service by exact name, full id or unique id prefix.
pub fn resolve_vip<'a>(
network: &'a NetworkReport,
selector: &str,
) -> std::result::Result<&'a crate::vip::VipStatus, String> {
let matches: Vec<_> = network
.vips
.iter()
.filter(|v| v.config.name == selector || v.config.id.starts_with(selector))
.collect();
match matches.as_slice() {
[vip] => Ok(vip),
[] => Err(format!("no VIP matches `{selector}`")),
_ => Err(format!(
"ambiguous VIP `{selector}`: {}",
matches
.iter()
.map(|v| format!("{} ({})", v.config.name, v.config.id))
.collect::<Vec<_>>()
.join(", ")
)),
}
}
/// Resolves a node by exact hostname, full id, unique id prefix or overlay IPv4.
/// Ambiguity is reported with names and full ids and never guessed.
pub fn resolve_node<'a>(
network: &'a NetworkReport,
selector: &str,
) -> std::result::Result<&'a MemberReport, String> {
let selector = selector.trim();
if selector.is_empty() {
return Err("select a node by name, id or IPv4 address".into());
}
if let Some(member) = network.members.iter().find(|m| m.endpoint_id == selector) {
return Ok(member);
}
let prefix = selector.trim_end_matches('…');
let matches: Vec<_> = network
.members
.iter()
.filter(|m| {
m.hostname.as_deref() == Some(selector)
|| m.overlay_address_v4.as_deref() == Some(selector)
|| (!prefix.is_empty() && m.endpoint_id.starts_with(prefix))
})
.collect();
match matches.as_slice() {
[one] => Ok(one),
[] => Err(format!(
"no signed node matches `{selector}` in `{}`",
network.name
)),
many => Err(format!(
"`{selector}` is ambiguous; use a full id or unique id prefix:\n{}",
many.iter()
.map(|m| format!(
" {} {} {}",
m.hostname.as_deref().unwrap_or("unnamed"),
m.endpoint_id,
m.overlay_address_v4.as_deref().unwrap_or("no IPv4")
))
.collect::<Vec<_>>()
.join("\n")
)),
}
}
/// Retires an exact selected claim; an online or changed target is rejected.
pub async fn forget_node(
socket: &Path,
network: &str,
peer: &str,
expected_version: u64,
) -> Result<ForgottenNodeReport> {
let request = Request::ForgetNode {
network_id: network.into(),
peer: peer.into(),
expected_version,
};
match exchange(socket, &request, EXCHANGE_TIMEOUT).await? {
Response::NodeForgotten(report) => Ok(report),
Response::Error(reason) => Err(Error::ForgetNode(reason)),
other => Err(Error::Storage(format!("unexpected response: {other:?}"))),
}
}
#[cfg(test)]
mod node_selector_tests {
use super::*;
#[test]
fn exact_names_addresses_and_unique_prefixes_select_the_same_signed_node() {
let node = MemberReport {
endpoint_id: "abcdef01".into(),
hostname: Some("laptop".into()),
overlay_address_v4: Some("10.2.0.3".into()),
record_version: 42,
..Default::default()
};
let network = NetworkReport {
name: "home".into(),
members: vec![node.clone()],
..Default::default()
};
for selector in ["laptop", "10.2.0.3", "abcdef01", "abc…"] {
assert_eq!(resolve_node(&network, selector), Ok(&node));
}
for selector in ["", "LAPTOP", "missing"] {
assert!(resolve_node(&network, selector).is_err());
}
}
#[test]
fn collisions_between_names_addresses_and_prefixes_require_an_explicit_identity() {
let first = MemberReport {
endpoint_id: "abcdef01".into(),
hostname: Some("duplicate".into()),
overlay_address_v4: Some("10.2.0.3".into()),
..Default::default()
};
let second = MemberReport {
endpoint_id: "abcdef02".into(),
hostname: Some("duplicate".into()),
overlay_address_v4: Some("10.2.0.3".into()),
..Default::default()
};
let third = MemberReport {
endpoint_id: "12345678".into(),
hostname: Some("abc".into()),
..Default::default()
};
let network = NetworkReport {
name: "home".into(),
members: vec![first.clone(), second, third],
..Default::default()
};
for selector in ["duplicate", "10.2.0.3", "abc"] {
let result = resolve_node(&network, selector);
assert!(result.is_err_and(|error| error.contains("ambiguous")
&& error.contains("abcdef01")
&& error.contains("abcdef02")
&& error.contains("duplicate")));
}
assert_eq!(resolve_node(&network, "abcdef01"), Ok(&first));
}
}
/// What happened when a network was stopped or started.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActiveReport {
@@ -324,6 +561,9 @@ pub struct ActiveReport {
/// Stopping something already stopped is not an error — it is the state
/// asked for — but it is worth saying which happened.
pub changed: bool,
/// Networks suspended by switching to this network.
#[serde(default)]
pub suspended: Vec<RangeConflictReport>,
}
/// What happened when a network was joined.
@@ -345,6 +585,13 @@ pub struct JoinedReport {
/// Almost always a mistyped secret, and the one thing that makes two
/// sections of a report look like one network.
pub name_shared_with: Option<String>,
/// Whether it started; false means it is configured but blocked by overlap.
#[serde(default = "joined_active_default")]
pub active: bool,
}
fn joined_active_default() -> bool {
true
}
/// What happened when a network was left.
@@ -367,6 +614,10 @@ 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.
pub endpoint_id: String,
/// Hostname announced to peers.
@@ -437,9 +688,37 @@ pub struct DnsReport {
pub names: u32,
}
/// An active network with an overlapping overlay range.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RangeConflictReport {
/// Public network id, for unambiguous selection.
pub network_id: String,
/// Configured network name.
pub name: String,
/// The overlapping range.
pub range: String,
}
/// A data-plane protocol available in the running agent.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProtocolReport {
/// Stable protocol name used by the CLI and network negotiation.
pub name: String,
/// A short description of encryption and transport.
pub summary: String,
}
/// One network.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetworkReport {
/// Shared VIPs and this client's routing observations.
#[serde(default)]
pub vips: Vec<crate::vip::VipStatus>,
/// Enabled local data-plane protocols, in preference order.
pub protocols: Vec<String>,
/// Whether the network starts or resumes automatically when its range is free.
#[serde(default)]
pub auto_start: bool,
/// Whether this agent participates in LAN broadcasts in this network.
#[serde(default)]
pub broadcast: bool,
@@ -482,6 +761,9 @@ pub struct NetworkReport {
/// The range it could not have, because another network on this agent
/// already holds it.
pub range_conflict: Option<String>,
/// Networks that switching to this network would suspend.
#[serde(default)]
pub range_conflicts: Vec<RangeConflictReport>,
/// The overlay, when a protocol is running one.
pub overlay: Option<OverlayReport>,
/// This agent's own name, when another member claimed it first.
@@ -524,6 +806,8 @@ pub struct HostnameConflictReport {
/// One member of the network, from signed state.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemberReport {
/// Signed claim version used to reject stale cleanup requests.
pub record_version: u64,
/// The member's device identity.
pub endpoint_id: String,
/// The IPv4 overlay address it claimed and signed for.
@@ -546,6 +830,10 @@ pub struct MemberReport {
/// One control plane peer.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerReport {
/// The software version reported by this authenticated peer, when available.
pub agent_version: Option<String>,
/// Actionable carrier failure or policy mismatch; absent for a usable route.
pub data_error: Option<String>,
/// The peer's endpoint id.
pub endpoint_id: String,
/// Hostname it announced, if any.
@@ -553,8 +841,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.
@@ -603,6 +895,8 @@ pub struct RuleSetReport {
/// One network's exit-node settings and what they are doing.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExitReport {
/// IP bytes carried through this exit since selection, when locally observed.
pub traffic: Option<crate::overlay::exit::ExitTraffic>,
/// This agent offers itself as an exit node in this network.
pub offering: bool,
/// Masquerading and forwarding rules for members' traffic, when offering.
@@ -635,19 +929,23 @@ pub struct HostRulesReport {
/// One overlay peer.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct OverlayPeerReport {
/// Opaque counter lifetime. A new tunnel or agent restart starts a new epoch.
pub counter_epoch: u64,
/// The peer's control plane identity, so a tunnel can be matched to the
/// session and the member it belongs to.
pub endpoint_id: String,
/// Protocol carrying overlay traffic for this peer (e.g. "tcp-tls", "wg-quic").
/// Reserved legacy field; the internal encryption protocol is not user selectable.
pub protocol: String,
/// The peer's WireGuard public key (if applicable).
pub public_key: String,
/// The overlay address the network agreed it holds.
pub address: Option<String>,
/// Seconds since the last WireGuard handshake.
///
/// `None` means the tunnel has never handshaken and cannot carry traffic.
/// Seconds since the last WireGuard handshake while its session key is usable.
pub handshake_secs_ago: Option<u64>,
/// An established tunnel has no recent or pending IP traffic. An expired
/// key on a tunnel required to stay warm is reported as waiting instead.
#[serde(default)]
pub idle: bool,
/// Packets encrypted and sent to this peer.
pub tx_packets: u64,
/// Packets decrypted from this peer.
@@ -693,6 +991,33 @@ impl OverlayPeerReport {
/// running and what they can report or change. That is what keeps this module
/// free of any knowledge of them.
pub trait ReportSource: Send + Sync + 'static {
/// Atomically saves a complete VIP draft using its original revision.
fn save_vip(
&self,
_network: String,
_config: crate::vip::VipConfig,
_expected: Option<String>,
_delete: bool,
) -> BoxFuture<'_, std::result::Result<Vec<crate::vip::VipStatus>, String>> {
Box::pin(async { Err("this agent cannot manage VIPs".into()) })
}
/// Persists and announces a version-scoped node cleanup.
fn forget_node(
&self,
_network: String,
_peer: String,
_expected_version: u64,
) -> BoxFuture<'_, std::result::Result<ForgottenNodeReport, String>> {
Box::pin(async { Err("this agent cannot forget node history".into()) })
}
/// Saves and applies a local ordered protocol set for one network.
fn set_protocols(
&self,
_network_id: String,
_protocols: Vec<String>,
) -> BoxFuture<'_, std::result::Result<Vec<String>, String>> {
Box::pin(async { Err("this agent cannot change protocols".into()) })
}
/// Produces a fresh report.
fn report(&self) -> BoxFuture<'_, StatusReport>;
@@ -822,7 +1147,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', 18]);
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 26]);
/// Reads one request off an accepted stream, answers it, writes the response.
///
@@ -846,6 +1171,30 @@ where
}
};
let response = match request {
Request::SaveVip {
network_id,
config,
expected,
delete,
} => match source.save_vip(network_id, config, expected, delete).await {
Ok(vips) => Response::Vips(vips),
Err(reason) => Response::Error(reason),
},
Request::ForgetNode {
network_id,
peer,
expected_version,
} => match source.forget_node(network_id, peer, expected_version).await {
Ok(report) => Response::NodeForgotten(report),
Err(reason) => Response::Error(reason),
},
Request::SetProtocols {
network_id,
protocols,
} => match source.set_protocols(network_id, protocols).await {
Ok(protocols) => Response::Protocols(protocols),
Err(reason) => Response::Error(reason),
},
Request::Status => Response::Status(Box::new(source.report().await)),
Request::SetBroadcast {
network_id,
@@ -1001,7 +1350,24 @@ pub async fn join_network_with_broadcast(
}
}
/// Changes one network's broadcast participation while the agent runs.
/// Replaces the enabled data-plane protocols of one configured network.
pub async fn set_protocols(
socket: &Path,
network_id: &str,
protocols: Vec<String>,
) -> Result<Vec<String>> {
let request = Request::SetProtocols {
network_id: network_id.to_owned(),
protocols,
};
match exchange(socket, &request, EXCHANGE_TIMEOUT).await? {
Response::Protocols(protocols) => Ok(protocols),
Response::Error(reason) => Err(Error::Storage(reason)),
other => Err(Error::Storage(format!("unexpected response: {other:?}"))),
}
}
/// Changes local broadcast participation in a network.
pub async fn set_broadcast(
path: impl AsRef<Path>,
network_id: &str,
+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:?}"
+1
View File
@@ -51,6 +51,7 @@ pub mod storage;
pub mod task;
#[cfg(feature = "testing")]
pub mod testing;
pub mod vip;
pub use agent::{Agent, AgentStatus, Event, NetworkStatus, PeerStatus};
pub use config::{AgentConfig, Limits, ReconnectPolicy, StoragePaths, TransportPolicy};
+135 -8
View File
@@ -22,6 +22,7 @@
//! own reachability data.
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use iroh::endpoint::{
@@ -221,9 +222,15 @@ fn local_addr_string(addr: &iroh::endpoint::LocalTransportAddr) -> Option<String
#[derive(Debug, Clone)]
pub struct EndpointAdapter {
endpoint: Endpoint,
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) {
let _ = self.owned_interface.set(name.to_owned());
}
/// Binds an endpoint according to `config`, reusing the persistent device key.
pub async fn bind(config: &AgentConfig, identity: &DeviceIdentity) -> Result<Self> {
let mut builder = Endpoint::builder(presets::Minimal)
@@ -240,12 +247,44 @@ impl EndpointAdapter {
TransportPolicy::N0Defaults => builder.preset(presets::N0),
};
if matches!(
config.transport,
TransportPolicy::N0Defaults | TransportPolicy::DirectOnly
) {
let filter = iroh::address_lookup::AddrFilter::new(|addrs| {
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.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());
}
for iface in netdev::get_interfaces() {
let name = iface.name.to_lowercase();
let friendly = iface
@@ -258,7 +297,9 @@ impl EndpointAdapter {
.as_deref()
.map(str::to_lowercase)
.unwrap_or_default();
if name.starts_with("tsun")
if name == owned_interface
|| friendly == owned_interface
|| name.starts_with("tsun")
|| name.contains("tsunagi")
|| name.contains("wintun")
|| friendly.starts_with("tsun")
@@ -288,7 +329,9 @@ impl EndpointAdapter {
.collect();
std::borrow::Cow::Owned(filtered)
});
builder = builder.addr_filter(filter);
builder = builder
.direct_addr_filter(filter.clone())
.addr_filter(filter);
}
#[cfg(feature = "testing")]
@@ -395,7 +438,10 @@ impl EndpointAdapter {
}
});
Ok(Self { endpoint })
Ok(Self {
endpoint,
owned_interface,
})
}
/// The underlying iroh endpoint.
@@ -468,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"));
}
}
+9
View File
@@ -5,6 +5,15 @@
//! system sees. It is kept apart from the broadcast rules, which have a
//! different lifetime and different tags.
/// Plaintext IP bytes carried through the client's currently selected internet exit.
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ExitTraffic {
/// Bytes accepted by the carrier for off-mesh destinations.
pub tx_bytes: u64,
/// Internet reply bytes delivered to the local interface.
pub rx_bytes: u64,
}
/// How one set of host rules went.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuleSetReport {
@@ -35,6 +35,8 @@ pub struct ExitHostPlan {
pub offer: Vec<Ipv4Range>,
/// Whether this device sends its internet traffic through a member.
pub client: bool,
/// Local address in the selected exit network, for hosts that choose a primary address.
pub client_source: Option<std::net::Ipv4Addr>,
/// The range of every network on the interface. Only the using side
/// reads it, to keep this agent's own traffic *to* the overlay inside it
/// where the host has no per-user routing (macOS).
@@ -84,6 +86,11 @@ pub trait ExitHostRules: Send + Sync + std::fmt::Debug + 'static {
/// startup to take away what a crashed run left.
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()>;
/// Refreshes volatile local socket protection without replacing exit routes.
fn refresh<'a>(&'a self, _plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
Box::pin(async { None })
}
/// Whether using an exit node on this host needs the underlay addresses
/// the agent talks to, because the host cannot exempt the agent's own
/// traffic from the default route by user id (Windows). The default is no.
@@ -33,12 +33,13 @@ const CHAIN: &str = "INPUT";
/// Fixed places `iptables` is installed. Never `PATH`: the agent is
/// privileged and a directory a user controls must not decide what it runs.
const IPTABLES_DIRECTORIES: [&str; 5] = [
const IPTABLES_DIRECTORIES: [&str; 6] = [
"/usr/sbin/iptables",
"/sbin/iptables",
"/usr/bin/iptables",
"/bin/iptables",
"/usr/local/sbin/iptables",
"/run/current-system/sw/bin/iptables",
];
/// The first candidate that exists.
@@ -328,7 +329,23 @@ fn clear_firewall(run: Run<'_>, interface: &str) {
/// Runs the real `iptables`.
pub(super) fn run_iptables(args: &[String]) -> Ran {
let Some(program) = pick_iptables(|path| std::path::Path::new(path).is_file()) else {
run_firewall(false, args)
}
pub(super) fn run_firewall(ipv6: bool, args: &[String]) -> Ran {
let v6_paths: Vec<_> = IPTABLES_DIRECTORIES
.iter()
.map(|p| p.replace("iptables", "ip6tables"))
.collect();
let v6_program = v6_paths
.iter()
.find(|path| std::path::Path::new(path).is_file());
let program = if ipv6 {
v6_program.map(String::as_str)
} else {
pick_iptables(|path| std::path::Path::new(path).is_file())
};
let Some(program) = program else {
return Ran::Missing;
};
match std::process::Command::new(program).args(args).output() {
@@ -350,11 +367,17 @@ pub(super) fn run_iptables(args: &[String]) -> Ran {
#[derive(Debug)]
pub struct LinuxHostRules {
pub(super) route: RouteHandle,
/// Interface, sorted socket snapshot and whether exit routes committed.
pub(super) underlay_sockets:
std::sync::Mutex<Option<(String, Vec<super::linux_exit_mark::Listener>, bool)>>,
}
impl LinuxHostRules {
pub(crate) fn new(route: RouteHandle) -> Self {
Self { route }
Self {
route,
underlay_sockets: std::sync::Mutex::new(None),
}
}
async fn set_route(&self, interface: String, source: Ipv4Addr) -> RuleOutcome {
@@ -24,19 +24,20 @@
//! Policy routing, with no `/1` routes and nothing in the main table:
//!
//! ```text
//! table 0x7473: default dev <if>
//! 5280: from all uidrange <euid>-<euid> lookup main
//! 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
//! 5300: from all lookup 0x7473
//! ```
//!
//! The first keeps the agent's *own* sockets off the tunnel: its QUIC, relay,
//! The first two keep the agent's *own* sockets and marked replies off the tunnel: its QUIC, relay,
//! DHT and DNS traffic would otherwise be routed into the interface it is
//! carrying, a loop. The second lets every specific route — the LAN, another
//! carrying, a loop. The specific-route rule lets the LAN, another
//! VPN, a tunnel to somewhere else — keep working, because only the default
//! route is suppressed. The priorities sit after Tailscale's 5270.
//! route is suppressed. Mark/UID bypass precedes Tailscale; application rules follow it.
//!
//! The first rule exempts a *user id*, so it is only right when the agent has
//! The UID rule exempts a *user id*, so it is only right when the agent has
//! one of its own, as the packaged service does. An agent started from a login
//! session would take that user's own applications out of the tunnel with it,
//! and the exit node would silently do nothing for them. That is refused, not
@@ -44,13 +45,15 @@
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};
use super::linux::{
LinuxHostRules, Ran, Run, comment_supported, failure, locked, run_iptables, same_rule,
split_rule_line,
LinuxHostRules, Ran, Run, comment_supported, failure, locked, run_firewall, run_iptables,
same_rule, split_rule_line,
};
use super::linux_exit_mark;
/// The chains the offering rules live in: `(table, chain)`.
const CHAINS: [(&str, &str); 2] = [("nat", "POSTROUTING"), ("filter", "FORWARD")];
@@ -377,6 +380,32 @@ fn read_sysctl(path: &str) -> Option<String> {
std::fs::read_to_string(path).ok()
}
fn check_kernel_rpf(overlay: &str) -> Result<(), String> {
let directory = "/proc/sys/net/ipv4/conf";
let value = |name: &str, setting: &str| -> Result<u32, String> {
read_sysctl(&format!("{directory}/{name}/{setting}"))
.and_then(|s| s.trim().parse().ok())
.ok_or_else(|| format!("cannot check {name}/{setting} before installing exit routes"))
};
let mut interfaces = Vec::new();
for entry in std::fs::read_dir(directory).map_err(|err| err.to_string())? {
let entry = entry.map_err(|err| err.to_string())?;
let name = entry.file_name().to_string_lossy().into_owned();
if name != "all" && name != "default" && name != "lo" && name != overlay {
interfaces.push((
name.clone(),
value(&name, "rp_filter")?,
value(&name, "src_valid_mark")?,
));
}
}
linux_exit_mark::check_kernel_rpf(
value("all", "rp_filter")?,
value("all", "src_valid_mark")?,
&interfaces,
)
}
/// The effective user id from the text of `/proc/self/status`.
fn parse_euid(status: &str) -> Option<u32> {
status
@@ -413,11 +442,11 @@ 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.
self.clear_client().await;
let _ = self.clear_client(interface).await;
return RuleOutcome::Failed(reason);
}
let Some(euid) = std::fs::read_to_string("/proc/self/status")
@@ -426,24 +455,156 @@ impl LinuxHostRules {
else {
return RuleOutcome::Failed("cannot tell which user this agent runs as".to_string());
};
let installed = self
.underlay_sockets
.lock()
.unwrap_or_else(|p| p.into_inner())
.as_ref()
.is_some_and(|(name, _, routed)| name == interface && *routed);
if installed {
// 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
.unwrap_or(RuleOutcome::Applied);
}
if let Err(reason) = self.clear_client(interface).await {
return RuleOutcome::Failed(reason);
}
let name = interface.to_string();
let prepared = Self::blocking(move || {
check_kernel_rpf(&name)?;
linux_exit_mark::install(
&run_firewall,
&name,
euid,
std::path::Path::new("/proc/sys/net/ipv6").is_dir(),
)
})
.await;
match prepared {
Ok(Ok(sockets)) => {
*self
.underlay_sockets
.lock()
.unwrap_or_else(|p| p.into_inner()) = Some((interface.into(), sockets, false));
}
Ok(Err(reason)) | Err(reason) => return RuleOutcome::Failed(reason),
}
let route = self.route.clone();
let interface = interface.to_string();
match Self::blocking(move || route.set_exit_client(&interface, euid)).await {
let name = interface.to_string();
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),
};
if let RuleOutcome::Failed(reason) = outcome {
let reason = match self.clear_client(interface).await {
Ok(()) => reason,
Err(cleanup) => format!("{reason}; cannot roll back exit rules: {cleanup}"),
};
RuleOutcome::Failed(reason)
} else {
if let Some((_, _, routed)) = self
.underlay_sockets
.lock()
.unwrap_or_else(|p| p.into_inner())
.as_mut()
{
*routed = true;
}
outcome
}
}
async fn clear_client(&self) {
async fn clear_client(&self, interface: &str) -> Result<(), String> {
let route = self.route.clone();
if let Ok(Err(err)) = Self::blocking(move || route.clear_exit_client()).await {
tracing::warn!(%err, "cannot remove the exit node routing rules");
Self::blocking(move || route.clear_exit_client())
.await?
.map_err(|err| err.to_string())?;
// Route removal must precede removing reply protection.
let name = interface.to_string();
Self::blocking(move || {
linux_exit_mark::clear(
&run_firewall,
&name,
std::path::Path::new("/proc/sys/net/ipv6").is_dir(),
)
})
.await??;
*self
.underlay_sockets
.lock()
.unwrap_or_else(|p| p.into_inner()) = None;
Ok(())
}
async fn refresh_sockets(&self, interface: &str) -> Option<RuleOutcome> {
let previous = self
.underlay_sockets
.lock()
.unwrap_or_else(|p| p.into_inner())
.clone();
if previous
.as_ref()
.is_none_or(|(name, _, routed)| name != interface || !routed)
{
return None;
}
let name = interface.to_string();
let work_name = name.clone();
let result = Self::blocking(move || {
let uid = std::fs::read_to_string("/proc/self/status")
.ok()
.and_then(|s| parse_euid(&s))
.ok_or("cannot read agent UID")?;
check_kernel_rpf(&work_name)?;
let v6 = std::path::Path::new("/proc/sys/net/ipv6").is_dir();
let sockets = linux_exit_mark::local_sockets(uid, v6)?;
if previous
.as_ref()
.is_some_and(|(name, old, _)| name == &work_name && old == &sockets)
{
return Ok(None);
}
linux_exit_mark::refresh(&run_firewall, &work_name, v6, &sockets)?;
Ok(Some(sockets))
})
.await;
match result {
Ok(Ok(None)) => None,
Ok(Ok(Some(sockets))) => {
*self
.underlay_sockets
.lock()
.unwrap_or_else(|p| p.into_inner()) = Some((name, sockets, true));
Some(RuleOutcome::Applied)
}
Ok(Err(reason)) | Err(reason) => Some(RuleOutcome::Failed(reason)),
}
}
}
impl ExitHostRules for LinuxHostRules {
fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
Box::pin(async move {
if plan.client {
self.refresh_sockets(&plan.interface).await
} else {
None
}
})
}
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
Box::pin(async move {
let interface = plan.interface.clone();
@@ -465,9 +626,11 @@ 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 {
self.clear_client().await;
if let Err(reason) = self.clear_client(&interface).await {
tracing::warn!(%reason, "cannot remove exit-client rules");
}
None
};
ExitHostReport {
@@ -482,7 +645,9 @@ impl ExitHostRules for LinuxHostRules {
Box::pin(async move {
let name = interface.to_string();
let _ = Self::blocking(move || clear_offer(&run_iptables, &name)).await;
self.clear_client().await;
if let Err(reason) = self.clear_client(interface).await {
tracing::warn!(%reason, "cannot remove exit-client rules");
}
})
}
}
@@ -0,0 +1,469 @@
//! Privileged routing regression, isolated from the host in named namespaces.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream, UdpSocket};
use std::os::unix::process::CommandExt;
use std::process::{Child, Command};
use std::time::Duration;
use super::linux::run_firewall;
use super::linux_exit_mark::{clear, install, local_sockets, refresh};
use crate::overlay::NetlinkProvisioner;
const TEST: &str = "overlay::hostrules::linux_exit_kernel::strict_firewall_preserves_underlay_and_application_exit_routing";
const ROLE: &str = "TSUNAGI_EXIT_KERNEL_TEST_ROLE";
fn ip(arguments: &[&str]) -> String {
let result = Command::new("ip").args(arguments).output().unwrap();
assert!(
result.status.success(),
"ip {arguments:?}: {}",
String::from_utf8_lossy(&result.stderr)
);
String::from_utf8_lossy(&result.stdout).into_owned()
}
struct Namespace(String);
impl Drop for Namespace {
fn drop(&mut self) {
let _ = Command::new("ip").args(["netns", "del", &self.0]).status();
}
}
struct Echo(Child);
impl Drop for Echo {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
fn probes() {
let should_pass = std::env::var("TSUNAGI_EXIT_KERNEL_EXPECT").unwrap() == "pass";
for address in ["198.51.100.2:42000", "[2001:db8:2::2]:42000"] {
let address: SocketAddr = address.parse().unwrap();
let socket = UdpSocket::bind(if address.is_ipv4() {
"0.0.0.0:0"
} else {
"[::]:0"
})
.unwrap();
socket
.set_read_timeout(Some(Duration::from_secs(1)))
.unwrap();
socket.send_to(b"rpf", address).unwrap();
let mut packet = [0u8; 3];
assert_eq!(
socket.recv(&mut packet).is_ok(),
should_pass,
"UDP {address}"
);
if should_pass {
assert_eq!(&packet, b"rpf");
}
let connected = TcpStream::connect_timeout(&address, Duration::from_secs(1));
assert_eq!(connected.is_ok(), should_pass, "TCP {address}");
if let Ok(mut stream) = connected {
stream
.set_read_timeout(Some(Duration::from_secs(1)))
.unwrap();
stream.write_all(b"rpf").unwrap();
stream.read_exact(&mut packet).unwrap();
assert_eq!(&packet, b"rpf");
}
}
}
fn run_probes(expect: &str) {
let result = Command::new(std::env::current_exe().unwrap())
.args(["--ignored", "--exact", TEST, "--nocapture"])
.env(ROLE, "probe")
.env("TSUNAGI_EXIT_KERNEL_EXPECT", expect)
.uid(990)
.gid(990)
.output()
.unwrap();
assert!(
result.status.success(),
"{}\n{}",
String::from_utf8_lossy(&result.stdout),
String::from_utf8_lossy(&result.stderr)
);
}
fn passive_listener() {
let listeners: Vec<_> = ["192.0.2.1:42010", "[2001:db8:1::1]:42010"]
.into_iter()
.map(|address| TcpListener::bind(address).unwrap())
.collect();
println!("PASSIVE_READY");
let tasks: Vec<_> = listeners
.into_iter()
.map(|listener| {
std::thread::spawn(move || {
let (mut socket, _) = listener.accept().unwrap();
socket
.set_read_timeout(Some(Duration::from_secs(2)))
.unwrap();
let mut bytes = [0; 3];
socket.read_exact(&mut bytes).unwrap();
socket.write_all(&bytes).unwrap();
})
})
.collect();
for task in tasks {
task.join().unwrap();
}
}
fn udp_listener() {
let sockets: Vec<_> = ["192.0.2.1:42011", "[2001:db8:1::1]:42011"]
.into_iter()
.map(|a| UdpSocket::bind(a).unwrap())
.collect();
println!("PASSIVE_READY");
let tasks: Vec<_> = sockets
.into_iter()
.map(|socket| {
std::thread::spawn(move || {
socket
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
let mut bytes = [0; 3];
let (len, peer) = socket.recv_from(&mut bytes).unwrap();
socket.send_to(&bytes[..len], peer).unwrap();
})
})
.collect();
for task in tasks {
task.join().unwrap();
}
}
fn spawn_listener(role: &str) -> Echo {
let process = Command::new(std::env::current_exe().unwrap())
.args(["--ignored", "--exact", TEST, "--nocapture"])
.env(ROLE, role)
.uid(990)
.gid(990)
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap();
let mut child = Echo(process);
let mut output = BufReader::new(child.0.stdout.take().unwrap());
loop {
let mut line = String::new();
assert_ne!(
output.read_line(&mut line).unwrap(),
0,
"listener exited before readiness"
);
if line.contains("PASSIVE_READY") {
// Keep the reader open for libtest's final status after the socket
// worker finishes; closing it here makes success a broken pipe.
child.0.stdout = Some(output.into_inner());
return child;
}
}
}
fn client() {
for setting in ["rp_filter", "src_valid_mark"] {
std::fs::write(format!("/proc/sys/net/ipv4/conf/all/{setting}"), b"1").unwrap();
}
std::fs::write("/proc/sys/net/ipv4/conf/rpf-c/rp_filter", b"1").unwrap();
for family in [false, true] {
let args: Vec<_> = [
"-t",
"mangle",
"-A",
"PREROUTING",
"-m",
"rpfilter",
"--invert",
"--validmark",
"-j",
"DROP",
]
.into_iter()
.map(str::to_string)
.collect();
let result = run_firewall(family, &args);
assert!(
matches!(result, super::linux::Ran::Exited { success: true, .. }),
"{result:?}"
);
}
let provisioner = NetlinkProvisioner::new().unwrap();
let route = provisioner.host_rules().route;
// Model Tailscale's earlier lookup, without running another VPN daemon.
ip(&["-4", "rule", "add", "priority", "5270", "table", "52"]);
ip(&[
"-4", "route", "add", "default", "dev", "tsun0", "table", "52",
]);
ip(&["-6", "rule", "add", "priority", "5270", "table", "52"]);
ip(&[
"-6",
"route",
"add",
"unreachable",
"default",
"table",
"52",
]);
// A foreign VPN must leave neighbour discovery and connected LAN paths
// usable; otherwise the fixture itself cannot resolve its uplink neighbour.
for prefix in ["fe80::/64", "2001:db8:1::/64"] {
ip(&["-6", "route", "add", "throw", prefix, "table", "52"]);
}
let mut passive = spawn_listener("listener");
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();
run_probes("pass");
// Pair transports may bind fresh UDP ports after exit activation.
let mut dynamic_udp = spawn_listener("udp-listener");
refresh(
&run_firewall,
"tsun0",
true,
&local_sockets(990, true).unwrap(),
)
.unwrap();
let server = std::env::var("TSUNAGI_EXIT_KERNEL_SERVER").unwrap();
let incoming = Command::new("ip").args(["netns", "exec", &server, "python3", "-c", r#"import socket
for family,source,target in [(socket.AF_INET,'198.51.100.2','192.0.2.1'),(socket.AF_INET6,'2001:db8:2::2','2001:db8:1::1')]:
for kind,port in [(socket.SOCK_STREAM,42010),(socket.SOCK_DGRAM,42011)]:
s=socket.socket(family,kind); s.settimeout(2); s.bind((source,0)); s.connect((target,port)); s.sendall(b'rpf'); assert s.recv(3)==b'rpf'; s.close()
"#]).output().unwrap();
assert!(
incoming.status.success(),
"first inbound TCP/UDP must be protected: {}",
String::from_utf8_lossy(&incoming.stderr)
);
assert!(passive.0.wait().unwrap().success());
assert!(dynamic_udp.0.wait().unwrap().success());
// Repeated apply remains usable, and does not redirect application sockets.
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()
.unwrap();
assert!(
!blocked.status.success(),
"application IPv6 must stay blocked"
);
route.clear_exit_client().unwrap();
clear(&run_firewall, "tsun0", true).unwrap();
for family in ["-4", "-6"] {
assert!(
ip(&[family, "rule", "show"]).contains("5270:"),
"foreign routing rules survive cleanup"
);
ip(&[family, "rule", "del", "priority", "5270"]);
}
assert!(ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]).contains("dev rpf-c"));
assert!(ip(&["-6", "route", "get", "2001:db8:2::2", "uid", "991"]).contains("dev rpf-c"));
for family in [false, true] {
let result = run_firewall(family, &["-t".into(), "mangle".into(), "-S".into()]);
if let super::linux::Ran::Exited { stdout, .. } = result {
assert!(!stdout.contains("tsunagi-exit-underlay:"));
assert!(!stdout.contains("tsunagi-exit-sockets:"));
assert!(
stdout.contains("rpfilter"),
"strict host filtering is retained"
);
}
}
}
#[test]
#[ignore = "needs root, iproute2, iptables/ip6tables and Python; changes only temporary namespaces"]
fn strict_firewall_preserves_underlay_and_application_exit_routing() {
match std::env::var(ROLE).as_deref() {
Ok("probe") => {
probes();
return;
}
Ok("client") => {
client();
return;
}
Ok("listener") => {
passive_listener();
return;
}
Ok("udp-listener") => {
udp_listener();
return;
}
_ => {}
}
let suffix = std::process::id();
let client_name = format!("tsng-rpf-c-{suffix}");
let server_name = format!("tsng-rpf-s-{suffix}");
ip(&["netns", "add", &client_name]);
let _client = Namespace(client_name.clone());
ip(&["netns", "add", &server_name]);
let _server = Namespace(server_name.clone());
ip(&[
"link",
"add",
"rpf-c",
"netns",
&client_name,
"type",
"veth",
"peer",
"name",
"rpf-s",
"netns",
&server_name,
]);
for (namespace, interface, v4, v6) in [
(&client_name, "rpf-c", "192.0.2.1/24", "2001:db8:1::1/64"),
(&server_name, "rpf-s", "192.0.2.2/24", "2001:db8:1::2/64"),
] {
ip(&["-n", namespace, "link", "set", "lo", "up"]);
ip(&["-n", namespace, "addr", "add", v4, "dev", interface]);
ip(&[
"-n", namespace, "-6", "addr", "add", v6, "dev", interface, "nodad",
]);
ip(&["-n", namespace, "link", "set", interface, "up"]);
}
ip(&[
"-n",
&server_name,
"addr",
"add",
"198.51.100.2/32",
"dev",
"lo",
]);
ip(&[
"-n",
&server_name,
"-6",
"addr",
"add",
"2001:db8:2::2/128",
"dev",
"lo",
"nodad",
]);
ip(&[
"-n",
&client_name,
"route",
"add",
"default",
"via",
"192.0.2.2",
]);
ip(&[
"-n",
&client_name,
"-6",
"route",
"add",
"default",
"via",
"2001:db8:1::2",
]);
ip(&["-n", &client_name, "link", "add", "tsun0", "type", "dummy"]);
ip(&[
"-n",
&client_name,
"addr",
"add",
"10.13.37.1/24",
"dev",
"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]:
for kind in [socket.SOCK_DGRAM,socket.SOCK_STREAM]:
sock=socket.socket(family,kind)
if family==socket.AF_INET6: sock.setsockopt(socket.IPPROTO_IPV6,socket.IPV6_V6ONLY,1)
sock.bind(('198.51.100.2' if family==socket.AF_INET else '2001:db8:2::2',42000))
if kind==socket.SOCK_STREAM: sock.listen()
selector.register(sock,selectors.EVENT_READ,kind)
print('ready',flush=True)
while True:
for key,_ in selector.select():
if key.data==socket.SOCK_DGRAM:
data,address=key.fileobj.recvfrom(128); key.fileobj.sendto(data,address)
else:
conn,_=key.fileobj.accept(); conn.settimeout(2)
try: conn.sendall(conn.recv(128))
finally: conn.close()
"#;
let child = Command::new("ip")
.args([
"netns",
"exec",
&server_name,
"python3",
"-u",
"-c",
echo_code,
])
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap();
let mut echo = Echo(child);
let mut ready = String::new();
BufReader::new(echo.0.stdout.take().unwrap())
.read_line(&mut ready)
.unwrap();
assert_eq!(ready.trim(), "ready");
let result = Command::new("ip")
.args(["netns", "exec", &client_name])
.arg(std::env::current_exe().unwrap())
.args(["--ignored", "--exact", TEST, "--nocapture"])
.env(ROLE, "client")
.env("TSUNAGI_EXIT_KERNEL_SERVER", &server_name)
.output()
.unwrap();
assert!(
result.status.success(),
"{}\n{}",
String::from_utf8_lossy(&result.stdout),
String::from_utf8_lossy(&result.stderr)
);
}
@@ -0,0 +1,535 @@
//! Own-bit connection marks for exit-client underlay traffic.
//! Reply marks are restored before host reverse-path filtering, never accepted
//! around it. No peer address becomes a host route or firewall argument.
use super::linux::{Ran, failure, locked, split_rule_line};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
/// Outside Tailscale's 0xff0000 mask and ordinary low-bit WireGuard marks.
pub(crate) const UNDERLAY_MARK: u32 = 0x4000_0000;
pub(crate) const UNDERLAY_MASK: u32 = UNDERLAY_MARK;
const MARK: &str = "0x40000000/0x40000000";
const MASK: &str = "0x40000000";
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(super) struct Listener {
address: IpAddr,
port: u16,
tcp: bool,
}
fn parse_listeners(listing: &str, uid: u32, v6: bool, tcp: bool) -> Result<Vec<Listener>, String> {
let mut result = Vec::new();
for line in listing.lines().skip(1) {
let fields: Vec<_> = line.split_whitespace().collect();
if (tcp && fields.get(3) != Some(&"0A"))
|| fields.get(7).and_then(|s| s.parse::<u32>().ok()) != Some(uid)
{
continue;
}
let (address, port) = fields
.get(1)
.and_then(|s| s.split_once(':'))
.ok_or("malformed local socket")?;
let port = u16::from_str_radix(port, 16).map_err(|e| e.to_string())?;
let address = if v6 {
let mut bytes = [0; 16];
for (word, chunk) in bytes.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let hex = address
.get(word * 8..word * 8 + 8)
.ok_or("malformed local IPv6 listener")?;
chunk.copy_from_slice(
&u32::from_str_radix(hex, 16)
.map_err(|e| e.to_string())?
.to_ne_bytes(),
);
}
IpAddr::V6(Ipv6Addr::from(bytes))
} else {
IpAddr::V4(Ipv4Addr::from(
u32::from_str_radix(address, 16)
.map_err(|e| e.to_string())?
.to_ne_bytes(),
))
};
if result.len() == 128 {
return Err("too many local sockets for exit protection".into());
}
if port != 0 {
result.push(Listener { address, port, tcp });
}
}
Ok(result)
}
pub(super) fn local_sockets(uid: u32, v6: bool) -> Result<Vec<Listener>, String> {
let mut listeners = Vec::new();
for (protocol, tcp) in [("tcp", true), ("udp", false)] {
for family in [false, true].into_iter().filter(|f| !f || v6) {
let path = format!("/proc/net/{protocol}{}", if family { "6" } else { "" });
listeners.extend(parse_listeners(
&std::fs::read_to_string(path).map_err(|e| e.to_string())?,
uid,
family,
tcp,
)?);
}
}
listeners.sort();
listeners.dedup();
Ok(listeners)
}
fn listener_rules(interface: &str, listener: &Listener) -> Vec<Vec<String>> {
let mut base = words(&[
"!",
"-i",
interface,
"-p",
if listener.tcp { "tcp" } else { "udp" },
"--dport",
&listener.port.to_string(),
]);
if !listener.address.is_unspecified() {
base.extend(words(&["-d", &listener.address.to_string()]));
}
// Match an actual local socket, not just a destination port. Listening
// sockets need protection on the first packet, before any outbound connmark.
base.extend(words(&[
"-m",
"socket",
"--nowildcard",
"-m",
"comment",
"--comment",
&listener_tag(interface),
]));
let save = base
.iter()
.cloned()
.chain(words(&[
"-m",
"mark",
"--mark",
MARK,
"-j",
"CONNMARK",
"--save-mark",
"--nfmask",
MASK,
"--ctmask",
MASK,
]))
.collect();
let mark = base
.into_iter()
.chain(words(&["-j", "MARK", "--set-xmark", MARK]))
.collect();
vec![save, mark]
}
pub(super) type RunFamily<'a> = &'a dyn Fn(bool, &[String]) -> Ran;
fn tag(interface: &str) -> String {
format!("tsunagi-exit-underlay:{interface}")
}
fn listener_tag(interface: &str) -> String {
format!("tsunagi-exit-sockets:{interface}")
}
fn words(values: &[&str]) -> Vec<String> {
values.iter().map(|s| (*s).into()).collect()
}
fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
let tag = tag(interface);
let uid = uid.to_string();
// Insert at position one in this order: final OUTPUT order is MARK, SAVE.
vec![
(
"PREROUTING",
words(&[
"!",
"-i",
interface,
"-m",
"connmark",
"--mark",
MARK,
"-m",
"comment",
"--comment",
&tag,
"-j",
"CONNMARK",
"--restore-mark",
"--nfmask",
MASK,
"--ctmask",
MASK,
]),
),
(
"OUTPUT",
words(&[
"-m",
"owner",
"--uid-owner",
&uid,
"-m",
"mark",
"--mark",
MARK,
"-m",
"comment",
"--comment",
&tag,
"-j",
"CONNMARK",
"--save-mark",
"--nfmask",
MASK,
"--ctmask",
MASK,
]),
),
(
"OUTPUT",
words(&[
"-m",
"owner",
"--uid-owner",
&uid,
"-m",
"comment",
"--comment",
&tag,
"-j",
"MARK",
"--set-xmark",
MARK,
]),
),
]
}
fn execute(run: RunFamily<'_>, v6: bool, args: Vec<String>) -> Result<String, String> {
match run(v6, &locked(args)) {
Ran::Exited {
success: true,
stdout,
..
} => Ok(stdout),
Ran::Exited { stderr, .. } => Err(failure(&stderr)),
Ran::Missing => Err(format!(
"{} is required for exit-node connection marks",
if v6 { "ip6tables" } else { "iptables" }
)),
}
}
/// Removes only exact interface tags, retaining other agents and host rules.
pub(super) fn clear(run: RunFamily<'_>, interface: &str, v6: bool) -> Result<(), String> {
clear_tags(run, interface, v6, false)
}
fn clear_tags(
run: RunFamily<'_>,
interface: &str,
v6: bool,
sockets_only: bool,
) -> Result<(), String> {
let wanted = tag(interface);
let sockets = listener_tag(interface);
for family in [false, true].into_iter().filter(|family| !family || v6) {
let chains: &[&str] = if sockets_only {
&["PREROUTING"]
} else {
&["OUTPUT", "PREROUTING"]
};
for chain in chains {
let listing = execute(run, family, words(&["-t", "mangle", "-S", chain]))?;
for line in listing.lines() {
let tokens = split_rule_line(line);
let [append, listed_chain, rest @ ..] = tokens.as_slice() else {
continue;
};
if append == "-A"
&& listed_chain == *chain
&& rest.windows(2).any(|pair| {
pair[0] == "--comment"
&& (pair[1] == sockets || (!sockets_only && pair[1] == wanted))
})
{
let args = words(&["-t", "mangle", "-D", chain])
.into_iter()
.chain(rest.iter().cloned())
.collect();
execute(run, family, args)?;
}
}
}
}
Ok(())
}
/// Establishes protection before routing may redirect application traffic.
pub(super) fn install(
run: RunFamily<'_>,
interface: &str,
uid: u32,
v6: bool,
) -> Result<Vec<Listener>, String> {
let listeners = local_sockets(uid, v6)?;
install_with_listeners(run, interface, uid, v6, &listeners)?;
Ok(listeners)
}
fn install_with_listeners(
run: RunFamily<'_>,
interface: &str,
uid: u32,
v6: bool,
listeners: &[Listener],
) -> Result<(), String> {
clear(run, interface, v6)?;
let result = (|| {
for family in [false, true].into_iter().filter(|family| !family || v6) {
for (chain, spec) in rules(interface, uid) {
let args = words(&["-t", "mangle", "-I", chain, "1"])
.into_iter()
.chain(spec)
.collect();
execute(run, family, args)?;
}
for listener in listeners.iter().filter(|s| s.address.is_ipv6() == family) {
for spec in listener_rules(interface, listener) {
execute(
run,
family,
words(&["-t", "mangle", "-I", "PREROUTING", "1"])
.into_iter()
.chain(spec)
.collect(),
)?;
}
}
}
Ok(())
})();
if result.is_err()
&& let Err(cleanup) = clear(run, interface, v6)
{
return Err(format!(
"{}; cannot roll back connection marks: {cleanup}",
result.err().unwrap_or_default()
));
}
result
}
/// Updates passive protection without interrupting established connmark rules.
pub(super) fn refresh(
run: RunFamily<'_>,
interface: &str,
v6: bool,
listeners: &[Listener],
) -> Result<(), String> {
clear_tags(run, interface, v6, true)?;
for family in [false, true].into_iter().filter(|f| !f || v6) {
for listener in listeners.iter().filter(|s| s.address.is_ipv6() == family) {
for spec in listener_rules(interface, listener) {
execute(
run,
family,
words(&["-t", "mangle", "-I", "PREROUTING", "1"])
.into_iter()
.chain(spec)
.collect(),
)?;
}
}
}
Ok(())
}
/// Kernel strict RPF must include the restored mark, independently of iptables.
pub(super) fn check_kernel_rpf(
all_rpf: u32,
all_valid: u32,
interfaces: &[(String, u32, u32)],
) -> Result<(), String> {
for (interface, rpf, valid) in interfaces {
if all_rpf.max(*rpf) == 1 && all_valid.max(*valid) == 0 {
return Err(format!(
"strict rp_filter on `{interface}` ignores connection marks; enable net.ipv4.conf.all.src_valid_mark=1 before using an exit node (rp_filter stays enabled)"
));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use std::cell::RefCell;
#[test]
fn both_families_restore_before_firewall_and_preserve_foreign_mark_bits() {
let calls = RefCell::new(Vec::new());
let run = |v6, args: &[String]| {
calls.borrow_mut().push((v6, args.to_vec()));
Ran::Exited {
success: true,
stdout: String::new(),
stderr: String::new(),
}
};
install_with_listeners(&run, "tsun0", 990, true, &[]).unwrap();
let calls = calls.borrow();
for family in [false, true] {
let inserts: Vec<_> = calls
.iter()
.filter(|(v6, a)| *v6 == family && a.iter().any(|s| s == "-I"))
.map(|(_, a)| a.join(" "))
.collect();
assert_eq!(inserts.len(), 3);
assert!(inserts[0].contains("-I PREROUTING 1 ! -i tsun0 -m connmark"));
assert!(inserts[0].contains("--restore-mark --nfmask 0x40000000 --ctmask 0x40000000"));
assert!(inserts[1].contains("--uid-owner 990"));
assert!(inserts[1].contains("--save-mark"));
assert!(inserts[2].contains("--set-xmark 0x40000000/0x40000000"));
assert!(
!inserts
.iter()
.any(|s| s.contains("-j ACCEPT") || s.contains("-j RETURN"))
);
}
assert_eq!(UNDERLAY_MASK & 0x00ff_0000, 0);
}
#[test]
fn cleanup_retains_other_interfaces_and_rolls_back_partial_ipv6_installation() {
let calls = RefCell::new(Vec::new());
let run = |v6, args: &[String]| {
calls.borrow_mut().push((v6, args.to_vec()));
let listing = "-A OUTPUT -m comment --comment tsunagi-exit-underlay:tsun0 -j MARK --set-xmark 0x40000000/0x40000000\n-A OUTPUT -m comment --comment tsunagi-exit-underlay:tsun1 -j MARK --set-xmark 0x40000000/0x40000000\n-A OUTPUT -m comment --comment unrelated -j RETURN\n";
Ran::Exited {
success: !(v6 && args.iter().any(|s| s == "-I")),
stdout: if args.iter().any(|s| s == "-S") {
listing.into()
} else {
String::new()
},
stderr: "injected IPv6 failure".into(),
}
};
assert!(install_with_listeners(&run, "tsun0", 990, true, &[]).is_err());
let calls = calls.borrow();
let deletions: Vec<_> = calls
.iter()
.filter(|(_, a)| a.iter().any(|s| s == "-D"))
.collect();
assert!(
deletions.len() >= 4,
"both initial and rollback cleanup run"
);
assert!(
deletions
.iter()
.all(|(_, a)| a.iter().any(|s| s == "tsunagi-exit-underlay:tsun0"))
);
}
#[test]
fn kernel_strict_validation_requires_mark_awareness_without_weakening_rpf() {
let interfaces = vec![("eth0".into(), 1, 0)];
assert!(check_kernel_rpf(0, 0, &interfaces).is_err());
assert!(check_kernel_rpf(0, 1, &interfaces).is_ok());
assert!(check_kernel_rpf(2, 0, &interfaces).is_ok());
assert!(check_kernel_rpf(0, 0, &[("eth0".into(), 1, 1)]).is_ok());
}
#[test]
fn passive_tcp_protection_uses_only_locally_owned_listeners() {
let listing = "header\n0: 00000000:01BB 00000000:0000 0A 0:0 0:0 0 990 0 1\n1: 0100007F:1111 00000000:0000 0A 0:0 0:0 0 1000 0 2\n2: 0100007F:2222 00000000:0000 01 0:0 0:0 0 990 0 3\n";
let listeners = parse_listeners(listing, 990, false, true).unwrap();
assert_eq!(
listeners,
vec![Listener {
address: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
port: 443,
tcp: true
}]
);
let rules = listener_rules("tsun0", &listeners[0]);
assert!(
rules[0]
.join(" ")
.contains("-p tcp --dport 443 -m socket --nowildcard")
);
assert!(rules[0].join(" ").contains("--save-mark"));
assert!(rules[1].join(" ").contains("--set-xmark"));
}
#[test]
fn listener_parser_checks_family_encoding_and_bounds() {
let loopback = Ipv6Addr::LOCALHOST.octets();
let hex: String = loopback
.as_chunks::<4>()
.0
.iter()
.map(|bytes| format!("{:08X}", u32::from_ne_bytes(*bytes)))
.collect();
let listing = format!("header\n0: {hex}:01BB 0:0 0A 0:0 0:0 0 990 0 1\n");
assert_eq!(
parse_listeners(&listing, 990, true, true).unwrap(),
vec![Listener {
address: IpAddr::V6(Ipv6Addr::LOCALHOST),
port: 443,
tcp: true
}]
);
assert!(
parse_listeners(
"header\n0: BAD:01BB 0:0 0A 0:0 0:0 0 990 0 1",
990,
true,
true
)
.is_err()
);
let huge = format!(
"header\n{}",
"0: 00000000:01BB 0:0 0A 0:0 0:0 0 990 0 1\n".repeat(129)
);
assert!(parse_listeners(&huge, 990, false, true).is_err());
}
#[test]
fn udp_refresh_preserves_general_connmark_protection_and_other_interfaces() {
let listing = "header\n0: 00000000:ABA0 0:0 07 0:0 0:0 0 990 0 1\n1: 00000000:0000 0:0 07 0:0 0:0 0 990 0 2\n";
let sockets = parse_listeners(listing, 990, false, false).unwrap();
assert_eq!(sockets.len(), 1);
assert!(!sockets[0].tcp);
let calls = RefCell::new(Vec::new());
let run = |v6, args: &[String]| {
calls.borrow_mut().push((v6, args.join(" ")));
Ran::Exited { success: true, stdout: "-A PREROUTING -m comment --comment tsunagi-exit-underlay:tsun0 -j CONNMARK --restore-mark\n-A PREROUTING -m comment --comment tsunagi-exit-sockets:tsun0 -j MARK\n-A PREROUTING -m comment --comment tsunagi-exit-sockets:tsun1 -j MARK\n".into(), stderr: String::new() }
};
refresh(&run, "tsun0", false, &sockets).unwrap();
let calls = calls.borrow();
assert!(
calls
.iter()
.any(|(_, a)| a.contains("-I PREROUTING 1") && a.contains("-p udp"))
);
assert!(
calls
.iter()
.filter(|(_, a)| a.contains("-D"))
.all(|(_, a)| a.contains("tsunagi-exit-sockets:tsun0"))
);
}
}
@@ -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(())
}
}
@@ -55,6 +55,10 @@ pub use exit::{
mod linux;
#[cfg(all(feature = "tun-device", target_os = "linux"))]
mod linux_exit;
#[cfg(all(test, feature = "tun-device", target_os = "linux"))]
mod linux_exit_kernel;
#[cfg(all(feature = "tun-device", target_os = "linux"))]
pub(in crate::overlay) mod linux_exit_mark;
#[cfg(all(feature = "tun-device", target_os = "linux"))]
pub use linux::LinuxHostRules;
@@ -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(),
@@ -407,6 +501,7 @@ mod tests {
overlay: vec![range()],
bypass: vec![Ipv4Addr::new(138, 201, 61, 182)],
bypass_hosts: vec!["relay.example".into()],
..Default::default()
}
}
@@ -436,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')"));
}
@@ -445,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'"));
@@ -472,6 +573,7 @@ mod tests {
Ipv4Addr::UNSPECIFIED,
],
&["relay.example".into(), "gone.example".into()],
&[],
);
assert_eq!(
all,
@@ -504,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}");
+365 -49
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};
@@ -145,18 +145,17 @@ impl Tally {
}
/// The overlay interface.
#[derive(Debug)]
pub struct Interface {
device: Arc<dyn TunDevice>,
factory: Arc<dyn TunFactory>,
name: String,
mtu: u32,
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<()>>,
/// The host rules for this interface, when the factory manages the host.
host_rules: Option<Arc<dyn BroadcastHostRules>>,
@@ -170,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 {
@@ -200,6 +206,14 @@ impl ExitState {
}
}
impl std::fmt::Debug for Interface {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Interface")
.field("name", &self.name)
.finish_non_exhaustive()
}
}
impl Interface {
/// Creates the interface and starts moving packets.
pub async fn start(
@@ -221,7 +235,33 @@ impl Interface {
let name = device.name().to_string();
let tally = Arc::new(Tally::default());
let vip_task = {
let factory = Arc::clone(&factory);
let routes = Arc::clone(&routes);
let carrier = Arc::clone(&carrier);
tokio::spawn(async move {
let mut interval = tokio::time::interval(std::time::Duration::from_millis(250));
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut checks = tokio::task::JoinSet::new();
loop {
tokio::select! {
_=interval.tick()=>{
let (probes,jobs)=routes.vips.tick(routes.vips.check_capacity().saturating_sub(checks.len()));
for (route,packet) in probes {carrier.carry(route,packet);}
for job in jobs {
let factory = Arc::clone(&factory);
checks.spawn(job.run(move |socket, source| factory.bind_overlay_socket(socket, source)));
}
},
Some(result)=checks.join_next(),if !checks.is_empty()=>{
if let Ok((job,ok))=result {routes.vips.checked(job,ok);}
}
}
}
})
};
let task = {
let carrier = Arc::clone(&carrier);
let device = Arc::clone(&device);
let routes = Arc::clone(&routes);
let tally = Arc::clone(&tally);
@@ -231,6 +271,26 @@ impl Interface {
tally.malformed.fetch_add(1, Ordering::Relaxed);
continue;
};
match routes.vips.outgoing(packet.clone()) {
crate::vip::router::Decision::Send(route, packet) => {
for part in crate::vip::packet::fragments(packet, mtu) {
if carrier.carry(route, part) {
tally.sent.fetch_add(1, Ordering::Relaxed);
} else {
tally.undeliverable.fetch_add(1, Ordering::Relaxed);
}
}
continue;
}
crate::vip::router::Decision::Local(packet) => {
for part in crate::vip::packet::fragments(packet, mtu) {
let _ = device.send(part).await;
}
continue;
}
crate::vip::router::Decision::Drop => continue,
crate::vip::router::Decision::Pass => {}
}
let destination = header.destination();
if let (IpAddr::V4(source), IpAddr::V4(destination)) =
(header.source(), destination)
@@ -260,11 +320,19 @@ impl Interface {
tally.multicast.fetch_add(1, Ordering::Relaxed);
continue;
}
let Some(route) = routes.route_v4(destination) else {
let selected = match destination {
IpAddr::V4(address) => routes.packet_route(address),
IpAddr::V6(_) => None,
};
let Some((route, exit)) = selected else {
tally.note_unroutable(destination);
continue;
};
let len = packet.len() as u64;
if carrier.carry(route, packet) {
if let Some(exit) = exit {
exit.tx_bytes.fetch_add(len, Ordering::Relaxed);
}
tally.sent.fetch_add(1, Ordering::Relaxed);
} else {
tally.undeliverable.fetch_add(1, Ordering::Relaxed);
@@ -279,9 +347,14 @@ impl Interface {
name,
mtu,
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(())),
host_rules,
rules_report: std::sync::Mutex::new(None),
@@ -362,7 +435,10 @@ impl Interface {
.collect();
ranges.sort_by_key(|range| (range.base, range.prefix_len));
ranges.dedup();
let client = self.routes.exit_via().is_some();
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)
@@ -373,6 +449,7 @@ impl Interface {
interface: self.name.clone(),
offer: ranges,
client,
client_source,
overlay,
bypass,
bypass_hosts,
@@ -397,6 +474,14 @@ impl Interface {
return;
}
if planned.as_ref() == Some(&wanted) && ok {
if let Some(outcome) = exit.refresh(&wanted).await {
if let RuleOutcome::Failed(reason) = &outcome {
tracing::warn!(interface = %self.name, %reason, "cannot refresh exit-client socket protection");
}
if let Some(report) = self.exit_state().report.as_mut() {
report.client = Some(outcome);
}
}
return;
}
let report = exit.apply(&wanted).await;
@@ -447,6 +532,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.
@@ -471,13 +564,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;
}
@@ -634,13 +721,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
@@ -651,12 +738,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.
@@ -708,6 +808,15 @@ impl Interface {
task.abort();
let _ = task.await;
}
let vip_task = self
.vip_task
.lock()
.unwrap_or_else(|e| e.into_inner())
.take();
if let Some(task) = vip_task {
task.abort();
let _ = task.await;
}
self.factory.destroy(self.device.name()).await;
}
@@ -735,35 +844,64 @@ 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, exit) = match (origin, header.destination()) {
(
PacketSource::ExitReply {
local: Some(local),
exit,
},
IpAddr::V4(destination),
) if destination == local => (false, Some(exit)),
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_broadcast(destination) =>
{
if !super::broadcast::valid_udp(&packet)
|| !self.routes.accepts_broadcast(network, peer, destination)
{
self.tally.broadcast_dropped.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::BroadcastDenied);
}
true
(true, None)
}
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) => {
false
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_local_destination(network, destination)
|| self.routes.accepts_exit_traffic(network, destination) =>
{
(false, None)
}
_ => {
self.tally.wrong_destination.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::WrongDestination);
}
};
// Source ownership was checked before any VIP reverse translation.
let packet = match self.routes.vips.incoming(network, peer, packet.clone()) {
crate::vip::router::Decision::Send(route, packet) => {
// Probe replies use the ordinary peer carrier, never the TUN.
self.carrier.carry(route, packet);
return Ok(());
}
crate::vip::router::Decision::Local(packet) => {
for part in crate::vip::packet::fragments(packet, self.mtu) {
if self.device.send(part).await.is_ok() {
self.tally.received.fetch_add(1, Ordering::Relaxed);
}
}
return Ok(());
}
crate::vip::router::Decision::Drop => return Ok(()),
crate::vip::router::Decision::Pass => packet,
};
// Remote broadcasts terminate here. Only local TUN ingress can fan out.
let len = packet.len() as u64;
if self.device.send(packet).await.is_ok() {
if let Some(exit) = exit {
exit.rx_bytes.fetch_add(len, Ordering::Relaxed);
}
if broadcast {
self.tally
.broadcast_received
@@ -786,6 +924,14 @@ impl Interface {
impl Drop for Interface {
fn drop(&mut self) {
if let Some(task) = self
.vip_task
.lock()
.unwrap_or_else(|e| e.into_inner())
.take()
{
task.abort();
}
if let Ok(mut guard) = self.task.lock()
&& let Some(task) = guard.take()
{
@@ -794,18 +940,6 @@ impl Drop for Interface {
}
}
impl RoutingTable {
/// The route for a destination, when it is one the overlay carries.
fn route_v4(&self, destination: IpAddr) -> Option<Route> {
match destination {
IpAddr::V4(address) => self.route(address),
// The overlay is IPv4. An IPv6 packet has no owner here, and
// counting it as unroutable is the truth rather than a fault.
IpAddr::V6(_) => None,
}
}
}
/// Whether an address is one the overlay has nowhere to send.
fn is_multicast_or_broadcast(address: IpAddr) -> bool {
match address {
@@ -1143,6 +1277,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;
@@ -1321,6 +1532,57 @@ mod tests {
}
}
#[tokio::test]
async fn exit_totals_count_only_accepted_internet_packets_for_the_current_choice() {
let (interface, device, routes, _, id) = interface(false).await;
let totals = |p| {
routes
.exit_traffic(id, peer(p))
.map(|t| (t.tx_bytes, t.rx_bytes))
};
assert_eq!(totals(2), None);
routes.set_exit(id, using(peer(2)));
let outgoing = ipv4(addr(1), INTERNET, b"request");
device.push_from_os(outgoing.clone());
device.push_from_os(ipv4(addr(1), addr(2), b"ordinary mesh traffic"));
wait_for(&interface, |c| c.sent.saturating_sub(1)).await;
let incoming = ipv4(INTERNET, addr(1), b"reply");
interface
.deliver(id, peer(2), incoming.clone())
.await
.unwrap();
interface
.deliver(id, peer(2), ipv4(addr(2), addr(1), b"mesh"))
.await
.unwrap();
assert!(
interface
.deliver(id, peer(3), incoming.clone())
.await
.is_err()
);
assert!(
interface
.deliver(id, peer(2), ipv4(INTERNET, addr(3), b"wrong host"))
.await
.is_err()
);
routes.set_exit(id, using(peer(2)));
assert_eq!(
totals(2),
Some((outgoing.len() as u64, incoming.len() as u64))
);
routes.set_exit(id, using(peer(3)));
assert_eq!(totals(2), None);
assert_eq!(totals(3), Some((0, 0)));
routes.set_exit(id, ExitPolicy::default());
assert_eq!(totals(3), None);
routes.set_exit(id, using(peer(2)));
assert_eq!(totals(2), Some((0, 0)));
interface.remove().await;
}
#[tokio::test]
async fn internet_traffic_goes_to_the_exit_node_and_only_once_one_is_chosen() {
let (interface, device, routes, carrier, id) = interface(false).await;
@@ -1376,6 +1638,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;
@@ -1476,6 +1779,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 {
@@ -55,6 +55,7 @@ use crate::BoxFuture;
use crate::overlay::OverlayError;
use super::super::config::Cidr;
use super::super::hostrules::linux_exit_mark::{UNDERLAY_MARK, UNDERLAY_MASK};
use super::super::tun::{TunDevice, TunRequest};
use super::privilege::{NetAdmin, Privilege, probe_net_admin};
use super::{
@@ -75,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.
@@ -212,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)
})
}
@@ -345,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) => {
@@ -397,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
});
@@ -641,8 +670,10 @@ async fn del_broadcast_route(name: &str) -> Result<(), OverlayError> {
const EXIT_TABLE: u32 = 0x7473;
/// The main table.
const MAIN_TABLE: u32 = 254;
/// Where the exit rules sit, after Tailscale's 5270.
const EXIT_BYPASS_PRIORITY: u32 = 5280;
/// Protect marked underlay and initial socket routing before Tailscale's rules.
const EXIT_MARK_PRIORITY: u32 = 5205;
const EXIT_BYPASS_PRIORITY: u32 = 5206;
const LEGACY_EXIT_BYPASS_PRIORITY: u32 = 5280;
const EXIT_SPECIFIC_PRIORITY: u32 = 5290;
const EXIT_DEFAULT_PRIORITY: u32 = 5300;
@@ -666,14 +697,23 @@ fn rule_priority(rule: &RuleMessage) -> Option<u32> {
})
}
/// Whether a rule is one of the three this agent adds for an exit node.
/// Whether a rule is one this agent adds for an exit node, including old UID priority.
///
/// Recognised by shape as well as priority: those numbers are not reserved,
/// and a rule somebody else put at one of them must not be removed.
fn is_exit_rule(rule: &RuleMessage) -> bool {
let table = rule_table(rule);
match rule_priority(rule) {
Some(EXIT_BYPASS_PRIORITY) => {
Some(EXIT_MARK_PRIORITY) => {
table == MAIN_TABLE
&& rule
.attributes
.contains(&RuleAttribute::FwMark(UNDERLAY_MARK))
&& rule
.attributes
.contains(&RuleAttribute::FwMask(UNDERLAY_MASK))
}
Some(EXIT_BYPASS_PRIORITY | LEGACY_EXIT_BYPASS_PRIORITY) => {
table == MAIN_TABLE
&& rule
.attributes
@@ -692,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()
}
@@ -760,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") => {}
@@ -785,11 +836,34 @@ 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 rule add priority 5280 uidrange <uid>-<uid> lookup main
/// 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
/// ip rule add priority 5300 lookup 0x7473
/// ```
@@ -800,24 +874,19 @@ 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?;
let mut bypass = handle
.rule()
@@ -891,6 +960,7 @@ async fn set_exit_block_v6(handle: &rtnetlink::Handle, uid: u32) -> Result<(), O
};
}
add_mark_bypass(handle, true).await?;
let mut bypass = handle
.rule()
.add()
@@ -938,6 +1008,27 @@ async fn set_exit_block_v6(handle: &rtnetlink::Handle, uid: u32) -> Result<(), O
.map_err(|err| fail("rule for the default route", err))
}
async fn add_mark_bypass(handle: &rtnetlink::Handle, v6: bool) -> Result<(), OverlayError> {
let mut rule = handle
.rule()
.add()
.table_id(MAIN_TABLE)
.action(RuleAction::ToTable)
.priority(EXIT_MARK_PRIORITY)
.fw_mark(UNDERLAY_MARK);
rule.message_mut().header.family = if v6 {
rtnetlink::packet_route::AddressFamily::Inet6
} else {
rtnetlink::packet_route::AddressFamily::Inet
};
rule.message_mut()
.attributes
.push(RuleAttribute::FwMask(UNDERLAY_MASK));
rule.execute().await.map_err(|err| {
OverlayError::Unavailable(format!("cannot protect marked underlay traffic: {err}"))
})
}
async fn configure_link(configure: &Configure) -> Result<(), OverlayError> {
let name = configure.name.as_str();
with_netlink(|handle| async move {
@@ -1110,6 +1201,28 @@ mod tests {
assert!(!is_exit_rule(&rule(5280, 100, vec![uid])));
}
#[test]
fn underlay_bypass_recognises_only_our_exact_bit_and_mask() {
let rule = |table, mark, mask| {
let mut message = RuleMessage::default();
message.attributes.extend([
RuleAttribute::Table(table),
RuleAttribute::Priority(EXIT_MARK_PRIORITY),
RuleAttribute::FwMark(mark),
RuleAttribute::FwMask(mask),
]);
message
};
assert!(is_exit_rule(&rule(
MAIN_TABLE,
UNDERLAY_MARK,
UNDERLAY_MASK
)));
assert!(!is_exit_rule(&rule(MAIN_TABLE, 0x80000, 0xff0000)));
assert!(!is_exit_rule(&rule(MAIN_TABLE, UNDERLAY_MARK, u32::MAX)));
assert!(!is_exit_rule(&rule(52, UNDERLAY_MARK, UNDERLAY_MASK)));
}
#[test]
fn the_ipv6_default_of_the_exit_table_refuses_instead_of_routing() {
let route = exit_blocking_route_v6();
@@ -1131,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]
+239 -27
View File
@@ -21,9 +21,11 @@
//! one is in use.
use super::broadcast::{BroadcastPolicy, BroadcastTable};
use arc_swap::ArcSwap;
use super::exit::ExitTraffic;
use arc_swap::{ArcSwap, ArcSwapOption};
use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use iroh::EndpointId;
@@ -40,6 +42,24 @@ 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>,
exit: Arc<SelectedExit>,
},
}
/// A packet holds its selection until delivery finishes, even if the operator
/// switches to another exit in the meantime.
#[derive(Debug)]
pub(super) struct SelectedExit {
route: Route,
pub(super) tx_bytes: AtomicU64,
pub(super) rx_bytes: AtomicU64,
}
/// A network's exit-node settings, as far as packets are concerned.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ExitPolicy {
@@ -72,7 +92,7 @@ pub enum RouteError {
#[error(
"network {network} uses {range}, which overlaps {other_range} already in use by \
{other}. One agent has one interface, so an address can belong to only one of \
them: give one network a different range."
them: stop the other network before starting this one."
)]
Overlap {
/// The network being added.
@@ -89,7 +109,9 @@ pub enum RouteError {
/// Address ownership across every network this agent is in.
#[derive(Debug, Default)]
pub struct RoutingTable {
pub(crate) vips: Arc<crate::vip::VipRouter>,
broadcast: ArcSwap<BroadcastTable>,
selected_exit: ArcSwapOption<SelectedExit>,
networks: RwLock<HashMap<NetworkId, NetworkRoutes>>,
}
@@ -119,7 +141,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 {
@@ -138,16 +182,22 @@ impl RoutingTable {
}
}
}
if routes.exit.via.is_some() {
clear_other_exits(networks, network);
}
networks.insert(network, routes);
self.refresh_exit(networks);
self.broadcast
.store(Arc::new(BroadcastTable::build(&networks)));
.store(Arc::new(BroadcastTable::build(networks)));
Ok(())
}
/// Forgets a network.
pub fn remove_network(&self, network: NetworkId) {
self.vips.remove_network(network);
let mut networks = self.write();
networks.remove(&network);
self.refresh_exit(&networks);
self.broadcast
.store(Arc::new(BroadcastTable::build(&networks)));
}
@@ -170,11 +220,45 @@ 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);
}
self.refresh_exit(&networks);
}
}
/// Publish the current choice under the same write lock as the route edits.
fn refresh_exit(&self, networks: &HashMap<NetworkId, NetworkRoutes>) {
let route = exit_via(networks).map(|(network, peer)| Route { network, peer });
if self.selected_exit.load().as_ref().map(|exit| exit.route) != route {
self.selected_exit.store(route.map(|route| {
Arc::new(SelectedExit {
route,
tx_bytes: AtomicU64::default(),
rx_bytes: AtomicU64::default(),
})
}));
}
}
pub(crate) fn exit_traffic(&self, network: NetworkId, peer: EndpointId) -> Option<ExitTraffic> {
let current = self.selected_exit.load();
let exit = current
.as_ref()
.filter(|e| e.route == Route { network, peer })?;
Some(ExitTraffic {
tx_bytes: exit.tx_bytes.load(Ordering::Relaxed),
rx_bytes: exit.rx_bytes.load(Ordering::Relaxed),
})
}
/// Recognizes limited and configured subnet broadcasts before unicast lookup.
pub fn is_broadcast(&self, destination: Ipv4Addr) -> bool {
self.broadcast.load().is_destination(destination)
@@ -208,6 +292,13 @@ impl RoutingTable {
/// unicast destination, goes to this device's exit node when it has one:
/// that is what sending *all* traffic through a member means.
pub fn route(&self, destination: Ipv4Addr) -> Option<Route> {
self.packet_route(destination).map(|(route, _)| route)
}
pub(super) fn packet_route(
&self,
destination: Ipv4Addr,
) -> Option<(Route, Option<Arc<SelectedExit>>)> {
let networks = self.read();
for (network, routes) in networks.iter() {
if routes.local == Some(destination) {
@@ -218,10 +309,13 @@ impl RoutingTable {
.iter()
.find(|(address, _)| *address == destination)
{
return Some(Route {
network: *network,
peer: *peer,
});
return Some((
Route {
network: *network,
peer: *peer,
},
None,
));
}
}
// Inside an overlay range, an unowned address is nobody's, not the
@@ -229,7 +323,8 @@ impl RoutingTable {
if !is_internet_destination(destination) || in_any_range(&networks, destination) {
return None;
}
exit_via(&networks).map(|(network, peer)| Route { network, peer })
let exit = self.selected_exit.load_full()?;
Some((exit.route, Some(exit)))
}
/// Whether a peer may send from a source address.
@@ -239,20 +334,33 @@ 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)
let current = self.selected_exit.load();
let exit = current.as_ref()?;
(exit.route == Route { network, peer }
&& is_internet_destination(source)
&& !in_any_range(&networks, source)
&& !in_any_range(&networks, source))
.then(|| PacketSource::ExitReply {
local: routes.local,
exit: Arc::clone(exit),
})
}
/// Whether this agent, as an exit node of `network`, takes a member's
@@ -273,10 +381,21 @@ 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())
self.selected_exit
.load()
.as_ref()
.map(|exit| (exit.route.network, exit.route.peer))
}
/// Whether a default route is selected and the local source valid in that network.
pub(crate) fn exit_client(&self) -> (bool, Option<Ipv4Addr>) {
let networks = self.read();
match exit_via(&networks) {
Some((id, _)) => (true, networks.get(&id).and_then(|routes| routes.local)),
None => (false, None),
}
}
/// Networks that offer this agent as an exit node, with the range each
@@ -365,6 +484,25 @@ impl RoutingTable {
})
}
/// All active networks whose reserved ranges intersect this range.
pub fn overlapping_networks(
&self,
network: NetworkId,
range: Ipv4Range,
) -> Vec<(NetworkId, Ipv4Range)> {
let mut conflicts: Vec<_> = self
.read()
.iter()
.filter_map(|(other, routes)| {
let other_range = routes.range?;
(*other != network && ranges_overlap(range, other_range))
.then_some((*other, other_range))
})
.collect();
conflicts.sort_by_key(|(id, _)| *id);
conflicts
}
/// How many networks the table covers.
pub fn len(&self) -> usize {
self.read().len()
@@ -393,12 +531,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.
@@ -510,7 +655,7 @@ mod tests {
let err = table.set_network(second, routes()).unwrap_err();
let RouteError::Overlap { other, .. } = err;
assert_eq!(other, first);
assert!(err.to_string().contains("different range"), "{err}");
assert!(err.to_string().contains("stop the other network"), "{err}");
assert_eq!(table.len(), 1, "the overlapping network is not added");
// A range of its own is fine.
@@ -715,6 +860,72 @@ mod tests {
const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34);
#[test]
fn tunnel_warming_follows_the_selected_membership_on_restore_switch_and_off() {
let table = Arc::new(RoutingTable::new());
let (tx, _rx) = tokio::sync::mpsc::channel(1);
let context = crate::dataplane::PluginContext::new(tx, peer(1), None, &table);
let (a, b) = (network("left"), network("right"));
let exit = peer(2);
table.set_network(a, with_exit(false, Some(exit))).unwrap();
table.set_network(b, NetworkRoutes::default()).unwrap();
assert_eq!(context.warm_peer(a), Some(exit));
assert_eq!(context.warm_peer(b), None);
let select = |via| ExitPolicy { offer: true, via };
table.set_exit(b, select(Some(exit)));
assert_eq!(context.warm_peer(a), None);
assert_eq!(context.warm_peer(b), Some(exit));
table.set_exit(b, select(None));
assert_eq!(
context.warm_peer(b),
None,
"offering an exit does not select one"
);
table.set_exit(a, select(Some(exit)));
table.remove_network(a);
assert_eq!(context.warm_peer(a), None);
}
#[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();
@@ -789,7 +1000,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
@@ -808,9 +1019,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]);
}
}
Loaded 100 of 296 files, more files were not shown because too many files have changed in this diff. Show more