diff --git a/.github/workflows/packages.yaml b/.github/workflows/packages.yaml
index 9e28109..beb52a3 100644
--- a/.github/workflows/packages.yaml
+++ b/.github/workflows/packages.yaml
@@ -59,10 +59,12 @@ jobs:
contents: read
outputs:
tag: ${{ steps.plan.outputs.tag }}
+ commit: ${{ steps.plan.outputs.commit }}
fedora: ${{ steps.plan.outputs.fedora }}
build: ${{ steps.plan.outputs.build }}
publish: ${{ steps.plan.outputs.publish }}
steps:
+ # All history: plan.sh checks that the tag is on origin/main.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
@@ -89,8 +91,9 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: read
+ # Its output is signed as built, so it runs in publish's image.
container:
- image: registry.fedoraproject.org/fedora:44
+ image: quay.io/fedora/fedora:44@sha256:6ad1739ac6fb30f72ecc7b62a7ca94871d1cab215e4f5174113941047e0b4ed4
steps:
- name: Install tools
run: dnf -y install git-core rpm-build
@@ -102,9 +105,12 @@ jobs:
- name: Build source RPMs
env:
TAG: ${{ needs.plan.outputs.tag }}
+ COMMIT: ${{ needs.plan.outputs.commit }}
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
- packaging/make-srpm.sh out ${TAG:+"$TAG"}
+ # The plan job checked that COMMIT is on main; make-srpm.sh
+ # refuses a tag moved since then.
+ packaging/make-srpm.sh out ${TAG:+"$TAG" "$COMMIT"}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: srpm-nm-sshuttle
@@ -166,8 +172,9 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: read
+ # Its output is signed as built, so it runs in publish's image.
container:
- image: registry.fedoraproject.org/fedora:44
+ image: quay.io/fedora/fedora:44@sha256:6ad1739ac6fb30f72ecc7b62a7ca94871d1cab215e4f5174113941047e0b4ed4
steps:
- run: dnf -y install rpm-build
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -197,8 +204,10 @@ jobs:
environment: rpm-signing
permissions:
contents: read
+ # This job holds the signing key, so its image is pinned by digest.
+ # Refresh it as "Container images" in packaging/README.md says.
container:
- image: registry.fedoraproject.org/fedora:44
+ image: quay.io/fedora/fedora:44@sha256:6ad1739ac6fb30f72ecc7b62a7ca94871d1cab215e4f5174113941047e0b4ed4
steps:
- run: dnf -y install createrepo_c findutils gnupg2 jq python3-rpm rpm-sign
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -255,8 +264,9 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: read
+ # publish's image, so that a pull request with a new digest tries it.
container:
- image: registry.fedoraproject.org/fedora:44
+ image: quay.io/fedora/fedora:44@sha256:6ad1739ac6fb30f72ecc7b62a7ca94871d1cab215e4f5174113941047e0b4ed4
steps:
- run: dnf -y install createrepo_c findutils gnupg2 jq python3-rpm rpm-build rpm-sign
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml
index dbb11cd..d2a9fdc 100644
--- a/.github/workflows/release.yaml
+++ b/.github/workflows/release.yaml
@@ -3,7 +3,9 @@ name: release
# Puts a tagged release into the package repository. The repository is
# published from main, the only branch that may use the signing key, so this
# workflow starts the packages workflow there instead of publishing itself.
-# Pre-releases (a tag with a hyphen, such as v1.0.0-rc.1) are not packaged.
+# That workflow packages the tag only if it names a commit on main
+# (packaging/plan.sh). Pre-releases (a tag with a hyphen, such as
+# v1.0.0-rc.1) are not packaged.
on:
push:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index efa411b..070268f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,100 @@ All notable changes to nm-sshuttle are listed here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project
uses [semantic versioning](https://semver.org/).
+## [Unreleased]
+
+### Security
+
+- The packages workflow packages and signs a release tag only if it names
+ a commit on `main`, and the source RPM job refuses a tag moved after that
+ check. Before, any `vX.Y.Z` tag, pushed or given to a hand-started run,
+ was built from whatever commit it named and signed with the project's
+ key. `scripts/signing-key.sh` now restricts the `github-pages`
+ environment to `main` too, and `--restrict` restricts both environments
+ again (packaging/README.md).
+- The install steps download the signing key file and show its keys with
+ `gpg --show-keys`, to compare with the fingerprints in the README on
+ GitHub before `rpm --import`, and install the repository package with
+ `localpkg_gpgcheck=1`, so that dnf checks its signature against that key.
+ The key, the repository package and the fingerprint on the site all come
+ from the same site, so the site alone proved nothing, and dnf did not
+ check the repository package at all. The README and the site show
+ fingerprints as gpg prints them.
+- The packages workflow's `publish` job, which holds the signing key, runs
+ in a Fedora image pinned by digest instead of the `fedora:44` tag, and so
+ do the `srpm` and `release-rpm` jobs, whose output it signs as built.
+- A profile address or network with an IPv6 scope id (`fe80::%eth0/64`) is
+ refused. The scope is free text that `ipaddress` keeps, and a crafted one in
+ `subnets`, `exclude` or `gateway` reached the root `nft` script, where an
+ `include` made root read a file in `/etc` and log its first lines. The guard's set
+ elements are now written from each network's number, and a failed guard
+ logs only nft's error line.
+- The `remote` destination is checked as sshuttle splits it, in the plugin and
+ in the GNOME editor: an empty user or host (`@`, `@corp`), a host that starts
+ with `-` (`@-gD1080`), a password (`user:password@host`, which ended up in
+ sshuttle's command line and the journal) and a bad port are refused.
+- The sweep and the health check count only root's listeners on `127.0.0.1`
+ or `::1` (or the wildcard address). Any user's listener on the port of a
+ table that a killed sshuttle left behind kept the table, and with it the
+ redirect of the tunnelled traffic and DNS to that user's socket, past the
+ guard; such a table is now removed at the next sweep, with a warning
+ that names the user. A user's listener still counts while sshuttle's
+ root firewall helper runs below it, as for an sshuttle the user runs in
+ the foreground; one run with `--daemon`, or a root one listening on a
+ LAN address, now loses its tables at the plugin's sweeps. The health
+ check no longer falls back to every listener when it cannot find the
+ tunnel unit's cgroup; it now also finds it on hybrid and legacy cgroup
+ hosts, and gives up once, instead of reconnecting every 10 s, where
+ there is none. `check` warns about that.
+- sshuttle listens on an IPv4 port from 225 to 240, which only root may
+ bind: its slot's own two first, then a free one of the others. Any user
+ could hold sshuttle's ports from 12300 down and stop every tunnel from
+ starting. The IPv6 and DNS ports are still sshuttle's choice, so a user
+ can still block those, or bind them in the moment between sshuttle's
+ exit and the sweep: this is only partly fixed for profiles with DNS or
+ IPv6. The plugin now says when sshuttle found no free DNS or IPv6 port.
+ `check` warns when `ip_unprivileged_port_start` lets users bind the new
+ ports.
+- The plugin answers `VPN.Plugin` calls only from NetworkManager.
+- A profile with `dns split` or `all` is refused unless NetworkManager uses
+ systemd-resolved and `/etc/resolv.conf` sends every lookup to its stub;
+ otherwise lookups fell back to the local network's resolver during
+ reconnects. `check` reports it.
+- A guard removed during a reconnect is put back within 10 s, and before
+ each attempt; before, only the health check while up did.
+- A claim counts only for the process with the start time it recorded,
+ not any process that has the PID and `nm-sshuttle-service` in its command
+ line. A claim from the previous version needs that process to run with
+ every user ID 0.
+- The first hop's addresses from a lookup on the local network no longer
+ decide alone what bypasses the tunnel and the guard. One that lies in the
+ profile's networks or DNS servers is ignored, with a warning, unless
+ `exclude` covers it, and at most 8 are used; with none left the
+ activation fails. A forged DNS answer could take any internal address
+ out of the tunnel while the VPN showed connected. A jump host reached by
+ name inside the tunnelled networks now needs `gateway` or `exclude`; this
+ includes every profile that tunnels `0.0.0.0/0` or `::/0`, where a jump
+ host with a changing address, such as a dynamic DNS name, no longer
+ works. A `HostName` or remote that is an address is not looked up and
+ works as before. While addresses are ignored, ssh is pinned to a kept
+ one, and a failed start names the ignored ones. `check` reports it.
+- sshuttle gets `127.0.0.1` as its remote, and the ssh bridge gives ssh
+ the profile's remote. sshuttle 2.0.0 looked the remote up itself, as
+ root and on the local network, also with `gateway` set, and excluded
+ every address it got.
+- The tunnel unit has `/etc` read-only, so sshuttle's root firewall helper
+ cannot write `/etc/hosts`; nm-sshuttle never passes `--auto-hosts`.
+ `cleanup` removes the lines a stopped sshuttle left in `/etc/hosts`.
+- The systemd units have a sandbox (design §4.7). All three keep the kernel
+ tunables and cgroups read-only, lock the personality, and refuse realtime
+ scheduling and new setuid files. The tunnel unit adds a read-only
+ `/usr` and `/etc` and a capability bounding set; the plugin unit and the
+ dispatcher a read-only `/usr`, and the dispatcher also a read-only
+ `/home`, a private `/tmp` and fewer socket families and namespaces.
+- The user's `ssh -G` for the first hop, and anything their ssh config runs
+ from it, no longer inherit the plugin unit's `OOMScoreAdjust=-500`: the
+ bridge sets 0, which also resets the floor, before it drops to the user.
+
## [0.1.0] - 2026-10-11
The first release.
@@ -45,4 +139,5 @@ The first release.
- There is no Debian or Ubuntu package repository; take the `.deb` files
from a CI run.
+[Unreleased]: https://github.com/dennisklein/nm-sshuttle/compare/v0.1.0...HEAD
[0.1.0]: https://github.com/dennisklein/nm-sshuttle/releases/tag/v0.1.0
diff --git a/README.md b/README.md
index 11b6d9c..c35150f 100644
--- a/README.md
+++ b/README.md
@@ -30,20 +30,28 @@ hosts where WireGuard is not an option.
## Install
Fedora 43 and 44 can install from the signed package repository, which also
-brings updates:
+brings updates. Packages and repository metadata are signed with a key from
+[`RPM-GPG-KEY-nm-sshuttle`](packaging/nm-sshuttle-release/RPM-GPG-KEY-nm-sshuttle),
+which holds the keys with these fingerprints:
-```console
-$ sudo rpm --import https://dennisklein.github.io/nm-sshuttle/RPM-GPG-KEY-nm-sshuttle
-$ sudo dnf install https://dennisklein.github.io/nm-sshuttle/nm-sshuttle-release.noarch.rpm
-$ sudo dnf install nm-sshuttle nm-sshuttle-gnome
+```
+62D450232396EDB49BFF8E71109A2C1BD34D4A1C
```
-Packages and repository metadata are signed with this key
-([`RPM-GPG-KEY-nm-sshuttle`](packaging/nm-sshuttle-release/RPM-GPG-KEY-nm-sshuttle)),
-fingerprint:
+Download the key file, and import it only if `gpg --show-keys` shows each
+fingerprint listed here and no other key, and reports no error (install
+`gnupg2` if `gpg` is missing). The site serves the key file and the
+repository package together, so compare with this page on GitHub, not with
+the site. Then install the repository package with its
+signature checked, which dnf skips for a package named on the command line
+unless told otherwise:
-```
-62D4 5023 2396 EDB4 9BFF 8E71 109A 2C1B D34D 4A1C
+```console
+$ curl -fsSLO https://dennisklein.github.io/nm-sshuttle/RPM-GPG-KEY-nm-sshuttle
+$ gpg --show-keys RPM-GPG-KEY-nm-sshuttle
+$ sudo rpm --import RPM-GPG-KEY-nm-sshuttle
+$ sudo dnf install --setopt=localpkg_gpgcheck=1 https://dennisklein.github.io/nm-sshuttle/nm-sshuttle-release.noarch.rpm
+$ sudo dnf install nm-sshuttle nm-sshuttle-gnome
```
`nm-sshuttle-gnome` adds sshuttle to GNOME Settings' VPN list; leave it out
@@ -129,6 +137,14 @@ $ nm-sshuttle add lab --remote lab --subnets 10.50.0.0/16
connects to first, so name it, and the tunnel will not swallow it:
`--gateway 203.0.113.7`.
+**A jump host inside the tunnelled networks.** The plugin ignores an
+address of the jump host that it looked up and that lies in `--subnets`,
+since a forged DNS answer could otherwise take internal addresses out of
+the tunnel. Name it: `--gateway 10.0.0.5`, `--exclude 10.0.0.5`, or
+`HostName 10.0.0.5` in `~/.ssh/config`. A jump host with a changing
+address, such as a dynamic DNS name, therefore does not work with a
+profile that tunnels `0.0.0.0/0` or `::/0`.
+
**Notice a stuck tunnel.** `--probe 10.1.0.10:22` makes the plugin connect
to a server on the far side that speaks first, such as an ssh server, every
10 seconds, and restart the tunnel after two failures.
diff --git a/data/nm-sshuttle-dispatcher.service.in b/data/nm-sshuttle-dispatcher.service.in
index a0a71c8..d5be0bd 100644
--- a/data/nm-sshuttle-dispatcher.service.in
+++ b/data/nm-sshuttle-dispatcher.service.in
@@ -9,3 +9,16 @@ Type=dbus
BusName=org.freedesktop.NetworkManager.sshuttle.Dispatcher
ExecStart=@LIBEXECDIR@/nm-sshuttle-dispatcher
Restart=no
+# Sandbox (design §4.7). It runs nothing as the user. /etc stays writable for
+# the cleanup after a single-tunnel version; no capability bounding set, as
+# it starts units through systemd's D-Bus API.
+ProtectSystem=true
+ProtectHome=read-only
+PrivateTmp=yes
+ProtectKernelTunables=yes
+ProtectControlGroups=yes
+RestrictAddressFamilies=AF_UNIX AF_NETLINK AF_INET AF_INET6
+RestrictNamespaces=yes
+LockPersonality=yes
+RestrictRealtime=yes
+RestrictSUIDSGID=yes
diff --git a/data/nm-sshuttle-tunnel@.service.in b/data/nm-sshuttle-tunnel@.service.in
index d4c9b0e..8fb0475 100644
--- a/data/nm-sshuttle-tunnel@.service.in
+++ b/data/nm-sshuttle-tunnel@.service.in
@@ -18,3 +18,20 @@ Restart=no
# retry after an unlock waits up to 110 s for the agent's prompt (design §4.3).
TimeoutStartSec=120
TimeoutStopSec=15
+# Sandbox (design §4.7). The user's ssh runs here too, with whatever the
+# user's ssh config runs: it must still read ~/.ssh, write known_hosts, reach
+# the agent in /run/user and run setuid helpers such as ssh-keysign. So no
+# NoNewPrivileges, ProtectHome, PrivateTmp, PrivateDevices,
+# RestrictAddressFamilies or the others that design §4.7 lists.
+# /usr and /etc read-only, so that sshuttle's root firewall helper cannot
+# write /etc/hosts (design §4.8).
+ProtectSystem=full
+ProtectKernelTunables=yes
+ProtectControlGroups=yes
+LockPersonality=yes
+RestrictRealtime=yes
+RestrictSUIDSGID=yes
+# nft, iptables and tproxy; the redirect ports below 1024; setpriv; signals
+# to the user's ssh; the sweep, which reads other users' /proc/PID/fd; and
+# modprobe, which iptables-legacy runs itself (design §4.7).
+CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SETUID CAP_SETGID CAP_KILL CAP_DAC_READ_SEARCH CAP_SYS_PTRACE CAP_SYS_MODULE
diff --git a/data/nm-sshuttle@.service.in b/data/nm-sshuttle@.service.in
index 626a5ac..9814709 100644
--- a/data/nm-sshuttle@.service.in
+++ b/data/nm-sshuttle@.service.in
@@ -10,8 +10,8 @@ Type=notify
NotifyAccess=main
ExecStart=@LIBEXECDIR@/nm-sshuttle-service --slot %i
# After a stop, a kill or a crash: stop this slot's tunnel unit, remove its
-# link, guard and stale sshuttle tables. NetworkManager never removes the link
-# itself (design §4.4, §4.7).
+# link, guard and stale sshuttle tables, and sshuttle's lines in /etc/hosts.
+# NetworkManager never removes the link itself (design §4.4, §4.7, §4.8).
ExecStopPost=@LIBEXECDIR@/nm-sshuttle cleanup --slot %i
# The plugin owns the restart policy; a restart under an active VPN would
# leave NetworkManager's DNS entry behind.
@@ -20,3 +20,15 @@ OOMScoreAdjust=-500
# On SIGTERM the plugin gives up first and waits up to 1 s for
# NetworkManager's Disconnect; it exits within 5 s whatever happens.
TimeoutStopSec=20
+# Sandbox (design §4.7). The first hop's ssh -G runs here as the user, and
+# with it the user's Match exec, so no NoNewPrivileges, ProtectHome or
+# PrivateTmp. /etc stays writable: cleanup removes what sshuttle left in
+# /etc/hosts. No capability bounding set: starting units through systemd's
+# D-Bus API takes CAP_SYS_ADMIN unless polkit is asked, and ssh-as-user needs
+# CAP_SYS_RESOURCE to take the user's processes off OOMScoreAdjust's floor.
+ProtectSystem=true
+ProtectKernelTunables=yes
+ProtectControlGroups=yes
+LockPersonality=yes
+RestrictRealtime=yes
+RestrictSUIDSGID=yes
diff --git a/debian/control b/debian/control
index 365ba97..2a7c999 100644
--- a/debian/control
+++ b/debian/control
@@ -41,8 +41,8 @@ Description: NetworkManager VPN plugin that tunnels with sshuttle
brought up, supervised and torn down by a small root service. ssh runs as the
logged-in user, so the user's keys, agent and ~/.ssh/config apply.
.
- The design needs systemd-resolved for per-link DNS; without it the DNS
- settings of a profile degrade to "every lookup goes to the VPN's servers".
+ The design needs systemd-resolved for per-link DNS; without it a profile
+ that sets DNS (dns=split or dns=all) is refused at connect.
Package: nm-sshuttle-gnome
Architecture: any
diff --git a/docs/design.md b/docs/design.md
index c54cfa9..8c889b3 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -505,7 +505,13 @@ dns-rc`). Each item is marked:
Cleanup therefore cannot assume a port. A table is stale exactly when
nothing listens on its port, and the lab's sweeper uses that test
- **[lab T7c]**.
+ **[lab T7c]**. The plugin now passes a privileged IPv4 port and counts
+ only root's listeners (§4.8).
+- **[src] `--listen` with a port for each family fails.** Given
+ `127.0.0.1:P,[::1]:P`, sshuttle 1.3.1 and 2.0.0 stop with an
+ `UnboundLocalError` (`used_ports` is only set while searching). With
+ `[::1]:0` it searches the IPv6 port as before. The DNS port is always
+ searched, from 12300 down, and has no option.
- **[src] `--dns` already covers systemd-resolved, but only once.** Since
1.0.5 it reads `/etc/resolv.conf` and `/run/systemd/resolve/resolv.conf`,
only at start. After a network change the capture points at the old
@@ -518,6 +524,11 @@ dns-rc`). Each item is marked:
for the user's aliases.
- nm-sshuttle must therefore work out the first hop as the user and pass
`-x` itself.
+ - **[src]** It also looks the name up as root, on whatever network the
+ host is on, and excludes every address it gets: a spoofed answer
+ takes internal addresses out of the tunnel, outside the plugin's
+ checks (§4.8). The plugin therefore gives sshuttle an address as its
+ remote, which needs no lookup (§4.3).
- **[lab T9] A bad remote nameserver kills the tunnel.** If the remote
host's resolver list contains an unreachable server, one forwarded DNS
query kills the whole tunnel. In `server.py` `try_send()`, `connect()` sits
@@ -626,9 +637,9 @@ DNS behaviour.
│ StartUnit / StopUnit
┌─ nm-sshuttle-tunnel.service ──── root, Type=notify, Restart=no ─────────┐
│ ExecStartPre / ExecStopPost: nm-sshuttle sweep │
- │ ExecStart: sshuttle --method nft -r REMOTE -x FIRST_HOP │
+ │ ExecStart: sshuttle --method nft -r 127.0.0.1 -x FIRST_HOP │
│ --ns-hosts DNS --to-ns DNS SUBNETS │
- │ -e "nm-sshuttle ssh-as-user USER" │
+ │ -e "nm-sshuttle ssh-as-user USER --remote REMOTE" │
│ ├─ sshuttle --firewall (root; nft table sshuttle-ipv4-PORT) │
│ └─ ssh, as USER via setpriv (~/.ssh/config, ProxyJump, agent) │
└─────────────────────────────────────────────────────────────────────────┘
@@ -861,7 +872,7 @@ keys:
| `dns-servers` | `10.1.0.53` | Required for `split` and `all`. IPv4 only. |
| `dns-domains` | `corp.example,lab.example` | Routing domains for `split`. |
| `method` | `nft` | `nft` (default), `nat`, or `tproxy`, which also carries UDP ([tproxy](later/tproxy.md)). |
-| `gateway` | `203.0.113.7` | Override the first hop, IPv4 or IPv6. Needed with `ProxyCommand`. |
+| `gateway` | `203.0.113.7` | Override the first hop, IPv4 or IPv6. Needed with `ProxyCommand`. Never looked up, so it may lie in `subnets`. |
| `probe` | `10.1.0.10:22` | Optional reachability check through the tunnel, `ADDRESS:PORT` or `[IPV6]:PORT`. The service must send first, as an ssh server does (§4.4, "Health"). |
| `fail-closed` | `yes` | Install the guard table (default `yes`). |
@@ -876,9 +887,20 @@ $ nm-sshuttle check corp # as the user: ssh -G, host key, test login
**The profile is untrusted input to a root process.** The plugin enforces:
-- `remote` must match `^[A-Za-z0-9._@:%\[\]-]+$` and must not start with
- `-`;
-- every address and network must parse with `ipaddress`;
+- `remote` must match `^[A-Za-z0-9._@:%\[\]-]+$`, must not start with
+ `-`, and must split as sshuttle's `parse_hostport` splits it,
+ `[USER@]HOST[:PORT]`. The user part is not empty and has no `:`, which
+ sshuttle reads as the start of a password. The host is not empty, since
+ sshuttle then runs its server locally, as root, without ssh; it does not
+ start with `-`, since sshuttle passes it to ssh with no `--` before it. An
+ IPv6 host is in brackets when a port follows, and a port is 1 to 65535.
+ ssh itself has no `:PORT` in a destination, so the first-hop lookup
+ (`ssh -G`) and `nm-sshuttle check` work only without one; a port belongs
+ in `~/.ssh/config`;
+- every address and network must parse with `ipaddress` and have no IPv6
+ scope id (`fe80::1%eth0`): `ipaddress` keeps any text after the `%`,
+ spaces, quotes and braces included, and that text would reach the guard's
+ nft script and sshuttle's arguments;
- `local-user` must exist and be a regular user;
- `connection.permissions` must be exactly `user:
sudo rpm --import https://dennisklein.github.io/nm-sshuttle/RPM-GPG-KEY-nm-sshuttle
-sudo dnf install https://dennisklein.github.io/nm-sshuttle/nm-sshuttle-release.noarch.rpm
+Download the signing key file, and import it only if
+gpg --show-keys shows each fingerprint listed in the
+README on GitHub
+and no other key, and reports no error (install gnupg2 if
+gpg is missing).
+The fingerprint below comes from this site, like the key, so it proves nothing
+on its own. Then install the repository package with
+localpkg_gpgcheck=1, so that dnf checks its signature against the
+key; it does not check a package named on the command line otherwise.
+curl -fsSLO https://dennisklein.github.io/nm-sshuttle/RPM-GPG-KEY-nm-sshuttle
+gpg --show-keys RPM-GPG-KEY-nm-sshuttle
+sudo rpm --import RPM-GPG-KEY-nm-sshuttle
+sudo dnf install --setopt=localpkg_gpgcheck=1 https://dennisklein.github.io/nm-sshuttle/nm-sshuttle-release.noarch.rpm
sudo dnf install nm-sshuttle
To create and edit profiles in GNOME Settings as well, install
nm-sshuttle-gnome.
diff --git a/packaging/smoke-test.sh b/packaging/smoke-test.sh
index c82f428..bd35afd 100755
--- a/packaging/smoke-test.sh
+++ b/packaging/smoke-test.sh
@@ -13,7 +13,7 @@ base=${base%/}
curl -fsSL --retry 5 --retry-all-errors "$base/RPM-GPG-KEY-nm-sshuttle" -o /tmp/RPM-GPG-KEY-nm-sshuttle
rpm --import /tmp/RPM-GPG-KEY-nm-sshuttle
-dnf -y install "$base/nm-sshuttle-release.noarch.rpm"
+dnf -y install --setopt=localpkg_gpgcheck=1 "$base/nm-sshuttle-release.noarch.rpm"
# nm-sshuttle.repo points at the public site; follow the site under test
# instead. --allowerasing: the container has systemd-standalone-tmpfiles,
# which conflicts with the systemd that systemd-resolved needs; a real system
diff --git a/scripts/signing-key.sh b/scripts/signing-key.sh
index f897b8d..1d78541 100755
--- a/scripts/signing-key.sh
+++ b/scripts/signing-key.sh
@@ -9,15 +9,18 @@
# signing-key.sh --next add a new key beside the current one
# signing-key.sh --switch FILE sign with the secret key in FILE
# signing-key.sh --retire FPR stop trusting key FPR
+# signing-key.sh --restrict restrict the environments to main again
#
# Without options, it
# - generates an RSA-4096 signing key without passphrase or expiry in a
# throwaway GnuPG home
-# - creates the GitHub environment rpm-signing if needed and restricts it to
-# the main branch, so that only workflow runs on main can read its secrets;
-# it removes any other deployment branch or tag policy of that environment
-# - stores the secret key as secret RPM_SIGNING_KEY of that environment via
-# the gh CLI
+# - creates the GitHub environments rpm-signing and github-pages if needed
+# and restricts them to the main branch, so that only workflow runs on
+# main can read the key or deploy the site; it removes any other
+# deployment branch or tag policy of those environments and keeps their
+# other protection rules (--restrict does only this)
+# - stores the secret key as secret RPM_SIGNING_KEY of the rpm-signing
+# environment via the gh CLI
# - writes the public key to packaging/nm-sshuttle-release/RPM-GPG-KEY-nm-sshuttle, to be
# committed
# - keeps a backup of the secret key and its revocation certificate in
@@ -30,10 +33,13 @@
# with a new nm-sshuttle-release Version, so that clients get the new key from a
# package signed by one they trust:
# 1. --next generates a key, adds it to RPM-GPG-KEY-nm-sshuttle and backs it up as
-# above, without signing with it yet.
+# above, without signing with it yet. Add its fingerprint to README.md.
# 2. Once clients have updated nm-sshuttle-release, --switch with that backup makes
# the next publish sign everything with the new key.
-# 3. After that publish, --retire removes the old key.
+# 3. After that publish, --retire removes the old key. Remove its fingerprint
+# from README.md.
+# README.md lists the fingerprint of every key in RPM-GPG-KEY-nm-sshuttle, for
+# new users to check the key file against (tests/test_packaging.py).
#
# Env: NM_SSHUTTLE_SIGNING_UID key user ID (default: nm-sshuttle package signing )
# NM_SSHUTTLE_REPO GitHub repository (default: dennisklein/nm-sshuttle)
@@ -43,25 +49,29 @@ uid=${NM_SSHUTTLE_SIGNING_UID:-nm-sshuttle package signing }
repo=${NM_SSHUTTLE_REPO:-dennisklein/nm-sshuttle}
environment=rpm-signing
secret=RPM_SIGNING_KEY
+pages_environment=github-pages
mode=${1:-create}
case $mode in
create) [ $# -eq 0 ] ;;
+ --restrict) [ $# -eq 1 ] ;;
--next) [ $# -eq 1 ] ;;
--switch | --retire) [ $# -eq 2 ] ;;
*) false ;;
-esac || { echo "usage: $0 [--next | --switch SECRET-KEY-FILE | --retire FINGERPRINT]" >&2; exit 2; }
+esac || { echo "usage: $0 [--next | --switch SECRET-KEY-FILE | --retire FINGERPRINT | --restrict]" >&2; exit 2; }
-for cmd in gpg gh git; do
+for cmd in gpg gh git jq; do
command -v "$cmd" > /dev/null || { echo "$cmd is required" >&2; exit 1; }
done
root=$(git rev-parse --show-toplevel)
pubkey=$root/packaging/nm-sshuttle-release/RPM-GPG-KEY-nm-sshuttle
backup=${XDG_DATA_HOME:-$HOME/.local/share}/nm-sshuttle/signing-key
-GNUPGHOME=$(mktemp -d)
+tmp=$(mktemp -d)
+trap 'rm -rf "$tmp"' EXIT
+GNUPGHOME=$tmp/gnupg
+mkdir -m 700 "$GNUPGHOME"
export GNUPGHOME
-trap 'rm -rf "$GNUPGHOME"' EXIT
# fingerprints prints the fingerprints of the primary keys in file $1.
fingerprints() {
@@ -84,6 +94,53 @@ generate() {
)
}
+# restrict lets only workflow runs on main use environment $1, creating it
+# if needed. It replaces the environment's deployment branch policy with
+# one for main and removes every other branch or tag policy. The PUT
+# repeats the environment's reviewers and wait timer, so that they stay.
+restrict() {
+ local env=$1 out body policies list id type name have_main= err=$tmp/gh-error
+ if out=$(gh api "repos/$repo/environments/$env" 2> "$err"); then
+ body=$(jq '{
+ wait_timer: ([.protection_rules[]? | select(.type == "wait_timer") | .wait_timer] | first // 0),
+ prevent_self_review: ([.protection_rules[]? | select(.type == "required_reviewers") | .prevent_self_review] | first // false),
+ reviewers: [.protection_rules[]? | select(.type == "required_reviewers") | .reviewers[] | {type, id: .reviewer.id}]
+ }' <<< "$out")
+ elif grep -q 'HTTP 404' "$err"; then
+ body='{}'
+ else
+ echo "cannot read the $env environment: $(cat "$err")" >&2
+ exit 1
+ fi
+ jq '. + {deployment_branch_policy: {protected_branches: false, custom_branch_policies: true}}' <<< "$body" |
+ gh api --silent --method PUT "repos/$repo/environments/$env" --input -
+ policies="repos/$repo/environments/$env/deployment-branch-policies"
+ # Read the listing into a variable first: a failed listing then aborts the
+ # script, where one read through process substitution would pass as "no
+ # policies".
+ list=$(gh api --paginate "$policies" --jq '.branch_policies[] | [.id, .type, .name] | @tsv')
+ while IFS=$'\t' read -r id type name; do
+ [ -n "$id" ] || continue
+ if [ "$type" = branch ] && [ "$name" = main ]; then
+ have_main=1
+ else
+ echo "removing $type policy $name from the $env environment" >&2
+ gh api --silent --method DELETE "$policies/$id"
+ fi
+ done <<< "$list"
+ if [ -z "$have_main" ]; then
+ gh api --silent --method POST "$policies" -f name=main -f type=branch
+ fi
+}
+
+if [ "$mode" = --restrict ]; then
+ gh auth status > /dev/null
+ restrict "$environment"
+ restrict "$pages_environment"
+ echo "Only workflow runs on main can use the $environment and $pages_environment environments of $repo."
+ exit 0
+fi
+
if [ "$mode" != create ] && [ ! -e "$pubkey" ]; then
echo "$pubkey does not exist; create the first key without options" >&2
exit 1
@@ -101,7 +158,8 @@ case $mode in
Added key $fpr ($uid) to ${pubkey#"$root"/}; packages are still signed
with the current key.
-- Bump nm-sshuttle-release's Version, then commit and push.
+- Add its fingerprint to the list in README.md, bump nm-sshuttle-release's
+ Version, then commit and push.
- Once clients have updated nm-sshuttle-release, run
$0 --switch $backup/$fpr.secret.asc
- Backups of the secret key and revocation certificate are in $backup.
@@ -140,9 +198,10 @@ MSG
mv "$pubkey.new" "$pubkey"
cat <&2
- gh api --silent --method DELETE "$policies/$id"
- fi
-done <<< "$list"
-if [ -z "$have_main" ]; then
- gh api --silent --method POST "$policies" -f name=main -f type=branch
-fi
+# Restrict the environments before any key exists, so that main is the only
+# ref that can read the key or deploy the site.
+restrict "$environment"
+restrict "$pages_environment"
generate
gh secret set "$secret" --repo "$repo" --env "$environment" < "$backup/$fpr.secret.asc"
@@ -201,7 +239,9 @@ Created signing key $fpr ($uid).
- Secret key stored as $secret in the $environment environment of $repo,
which only workflow runs on main can use.
-- Public key written to ${pubkey#"$root"/}; commit and push it.
+- The $pages_environment environment is restricted to main as well.
+- Public key written to ${pubkey#"$root"/}; put its fingerprint in
+ README.md, then commit and push both.
- Backups of the secret key and revocation certificate are in $backup.
Move them to offline storage and delete them from this machine.
MSG
diff --git a/test-vm/README.md b/test-vm/README.md
index 3ecbfb2..98ea421 100644
--- a/test-vm/README.md
+++ b/test-vm/README.md
@@ -21,8 +21,8 @@ slot.
| id | scenario |
|---|---|
-| M2-01 | install: files, SELinux labels, `90-nm-sshuttle.conf` takes effect after `nmcli general reload conf` |
-| M2-02 | connect: address, resolved per link, split and outside lookups, guard, units, firewalld zone, the link unmanaged, a bus name of its own from NM |
+| M2-01 | install: files, SELinux labels, `/etc/resolv.conf` is resolved's stub, `90-nm-sshuttle.conf` takes effect after `nmcli general reload conf` |
+| M2-02 | connect: address, resolved per link, split and outside lookups, guard, units, firewalld zone, the link unmanaged, a bus name of its own from NM, sshuttle on the slot's own redirect port, sshuttle's remote 127.0.0.1 and ssh's the profile's, /etc read-only in the tunnel unit |
| M2-03 | reconnect (nbns) three times with firewalld: same ifindex, DNS, one VPN entry in NM, fail closed in the gap |
| M2-04 | the same without firewalld |
| M2-05 | a gap longer than 10 s |
@@ -31,10 +31,10 @@ slot.
| M2-08 | `systemctl stop` and `restart` in a gap |
| M2-09 | `kill -9` in a gap: `ExecStopPost` cleans up and no new instance starts |
| M2-10 | switching off while a reconnect is pending; the instance then exits |
-| M2-11 | Connect right after Disconnect: a new instance serves it |
+| M2-11 | Connect right after Disconnect: a new instance serves it; three more activations within a minute, each stopped with a connection open, take another redirect port while TIME_WAIT holds the old ones |
| M2-12 | a user override of the unmanaged setting: the plugin logs it |
| M2-13 | NetworkManager restart under an active VPN |
-| M2-14 | `ExecStopPost` removes leftovers |
+| M2-14 | `ExecStopPost` removes leftovers; the sweep removes a stale table whose port another user listens on |
| M2-15 | no SELinux denials during the run |
| M2-16 | `kill -9` of sshuttle while up: a reconnect without a block |
| M2-17 | `nft flush ruleset` while up: the health check restores the guard and restarts the tunnel |
@@ -50,6 +50,7 @@ slot.
| M2-27 | the probe: the sshuttle server on the jump host is stopped, the probe fails twice and the plugin reconnects |
| M2-28 | suspend and resume (only with `--suspend`) |
| M2-29 | a ProxyJump host named inside `~corp.test`: resolved from the local network at connect, pinned to that address on the reconnect |
+| M2-30 | `/etc/resolv.conf` linked to `/run/systemd/resolve/resolv.conf`: a `dns=split` profile is refused; the link is restored after |
| V6-01 | an IPv6 subnet through the tunnel, arriving from the jump host; refused at once in a gap ([IPv6](../docs/later/ipv6.md)) |
| V6-02 | the uplink's IPv6 addresses change: a second address in the prefix is no network change, a new prefix restarts a tunnel whose first hop is IPv6, and not an IPv4 one |
| TP-01 | `method=tproxy` ([tproxy](../docs/later/tproxy.md)): sshuttle's mark chain and the plugin's rule and route; UDP echo, TCP and split DNS through the tunnel; UDP and TCP refused at once in a gap; nothing left after the disconnect |
@@ -134,7 +135,10 @@ run without a report:
- M2-19's race between NM's "activated" and the link's removal is not
controlled; the INFO line says which state the plugin gave up from.
- NetworkManager writing `/etc/resolv.conf` itself (`dns=default`, as on
- Debian) is not tested on Fedora; it belongs to a Debian or Ubuntu VM.
+ Debian) is not tested on Fedora; it belongs to a Debian or Ubuntu VM. The
+ plugin refuses `dns=split` and `dns=all` there, so that refusal is what
+ such a VM should check. M2-30 checks it for a `resolv.conf` that bypasses
+ resolved's stub on Fedora.
## Manual checks with GNOME
diff --git a/test-vm/lib.sh b/test-vm/lib.sh
index c0c26ce..59721e9 100644
--- a/test-vm/lib.sh
+++ b/test-vm/lib.sh
@@ -76,6 +76,7 @@ use_slot() { # use_slot N
LINK=nmss$1
TPROXY_MARK=$(printf '0x%x' $(( 0x4e530000 + $1 )))
TPROXY_TABLE=$(( 20051 + $1 ))
+ LISTEN_PORTS="$(( 225 + 2 * $1 )) $(( 226 + 2 * $1 ))" # the slot's own IPv4 redirect ports
BUS=$(cat "$STATE_DIR/$1/bus-name" 2> /dev/null)
[ -n "$BUS" ] || BUS=$FIXED_BUS
}
@@ -676,7 +677,51 @@ dns_checks() {
guard_present() { nft list table inet "$GUARD_TABLE" > /dev/null 2>&1; }
guard_gone() { ! guard_present; }
sshuttle_tables() { nft list tables 2> /dev/null | awk '$3 ~ /^sshuttle-ipv[46]-[0-9]+$/ {print $3}'; }
+slot_listens() { # sshuttle listens on one of the slot's own ports, as root, and has its table
+ local p line
+ for p in $LISTEN_PORTS; do
+ # ss -e prints uid: only for a user other than root
+ line=$(ss -ltnepH "src 127.0.0.1 and sport = :$p")
+ grep -q '"sshuttle\|"python' <<< "$line" && ! grep -q ' uid:' <<< "$line" &&
+ sshuttle_tables | grep -qx "sshuttle-ipv4-$p" && { echo "port $p"; return 0; }
+ done
+ echo "no root listener on $LISTEN_PORTS; tables: $(sshuttle_tables | xargs)"
+ return 1
+}
+# the redirect ports 225-240: those listened on, and those in TIME_WAIT (design §4.8)
+redirect_listens() { ss -ltnH 'src 127.0.0.1 and ( sport >= :225 and sport <= :240 )' | awk '{print $4}' | xargs; }
+redirect_waits() { ss -tanH state time-wait '( sport >= :225 and sport <= :240 )' | awk '{print $3}' | sort | uniq -c | xargs; }
+# hold_conn SECONDS : a TCP connection through the tunnel to the web server, held open in the background
+hold_conn() {
+ as_user python3 -c 'import socket, sys, time
+s = socket.create_connection((sys.argv[1], 8080), timeout=5)
+time.sleep(float(sys.argv[2]))' "$WEB_IP" "$1" > /dev/null 2>&1 &
+}
tunnel_state() { sc is-active "$TUNNEL_UNIT" 2> /dev/null; }
+# design §4.3: sshuttle has 127.0.0.1 as its remote, which it never looks up,
+# and the user's ssh the profile's remote, from the bridge
+bridge_remote() {
+ local pid args ssh
+ pid=$(sc show -p MainPID --value "$TUNNEL_UNIT" 2> /dev/null)
+ args=" $(tr '\0' ' ' < "/proc/$pid/cmdline" 2> /dev/null)"
+ ssh=$(pgrep -a -u "$USER_NAME" -x ssh)
+ echo "sshuttle:$args"
+ echo "ssh: $ssh"
+ grep -q -F -- " -r 127.0.0.1 " <<< "$args" &&
+ grep -q -F -- " --remote ${REMOTE:-$USER_NAME@$JUMP_IP} " <<< "$args" &&
+ grep -q -F -- " ${REMOTE:-$USER_NAME@$JUMP_IP} -- " <<< "$ssh"
+}
+# design §4.7, §4.8: /etc is read-only in the tunnel unit, so that sshuttle's
+# root firewall helper cannot write /etc/hosts
+tunnel_etc_read_only() {
+ local pid out
+ pid=$(sc show -p MainPID --value "$TUNNEL_UNIT" 2> /dev/null)
+ [ -n "$pid" ] && [ "$pid" != 0 ] || { echo "the tunnel unit has no main process"; return 1; }
+ out=$(LC_ALL=C nsenter -t "$pid" -m -- touch /etc/.nm-sshuttle-probe 2>&1)
+ rm -f /etc/.nm-sshuttle-probe
+ echo "touch in sshuttle's mount namespace: ${out:-succeeded}"
+ grep -q "Read-only file system" <<< "$out"
+}
# method=tproxy: sshuttle's chains in iptables' mangle table, the plugin's rule and route
mangle_chains() { iptables -w -t mangle -S 2> /dev/null | awk '$1 == "-N" && $2 ~ /^sshuttle-[mtd]-[0-9]+$/ {print $2}'; }
tproxy_rule() { ip rule list 2> /dev/null | grep "fwmark $TPROXY_MARK lookup $TPROXY_TABLE"; }
diff --git a/test-vm/run.sh b/test-vm/run.sh
index 3cb1caa..d49a3e2 100755
--- a/test-vm/run.sh
+++ b/test-vm/run.sh
@@ -27,6 +27,7 @@
# M2-26 park candidate M2-27 probe with forwarding dead
# M2-28 suspend and resume (only with --suspend: the VM must wake by RTC)
# M2-29 a ProxyJump host named inside the tunnelled DNS domain
+# M2-30 dns=split refused with /etc/resolv.conf not resolved's stub
# V6-01 IPv6 subnet through the tunnel, fail closed in a gap
# V6-02 roams that change only the uplink's IPv6 addresses
# TP-01 method=tproxy: UDP and TCP through the tunnel, fail closed in a gap
@@ -227,6 +228,10 @@ s_install() {
check M2-01b "SELinux labels are what policy expects (restorecon -n finds nothing to change)" labels_ok
result M2-01b-i INFO "label of nm-sshuttle@.service: $(stat -c %C /usr/lib/systemd/system/nm-sshuttle@.service 2> /dev/null); of the service script: $(stat -c %C "$LIBEXEC/nm-sshuttle-service" 2> /dev/null)"
check M2-01c "SELinux is enforcing" test "$(getenforce 2> /dev/null)" = Enforcing
+ # The plugin refuses dns=split unless every lookup goes to resolved's stub
+ # (design §4.5), so a differently set image would fail every DNS scenario.
+ check M2-01g "/etc/resolv.conf lists only resolved's stub ($(readlink /etc/resolv.conf || echo 'a file'))" \
+ sh -c "cd / && python3 -c 'import sys; from nm_sshuttle import tunnel; sys.exit(bool(tunnel.resolv_conf_problem()))'"
# conf.d 90-nm-sshuttle.conf: take it away and a new nmss0 is managed; put it
# back, 'nmcli general reload conf', and a new nmss0 is unmanaged (state 10)
local without with
@@ -261,6 +266,9 @@ s_connect() {
check M2-02g "the tunnel unit is active" tunnel_active
check M2-02h "the plugin is alive and owns $BUS" plugin_owns_bus
check M2-02k "NetworkManager gave the activation its own bus name (--bus-name)" per_activation_name
+ check M2-02l "sshuttle listens on a port of the slot's own ($LISTEN_PORTS), with its table" slot_listens
+ check M2-02m "sshuttle's remote is 127.0.0.1; ssh, as the user, gets the profile's from the bridge" bridge_remote
+ check M2-02n "the tunnel unit sees /etc read-only" tunnel_etc_read_only
if fw_running; then
check M2-02i "firewalld has $LINK bound to a zone" fw_bound
result M2-02i-z INFO "zone of $LINK: $(fw_zone_of_link); default zone $(fw_default_zone)"
@@ -541,9 +549,41 @@ s_reconnect_connect() {
fi
check M2-11g "plugin log: no Connect was ignored" plog_has_not "Connect ignored"
result M2-11h INFO "Connect arrived during teardown (queued): $(plog | grep -c 'Connect arrived during')"
+ # i: three more activations within a minute, each tunnel stopped with a
+ # connection open, which leaves its redirect port in TIME_WAIT for 60 s:
+ # the next tunnel takes another port (design §4.8)
+ local i
+ for i in 1 2 3; do
+ [ "$(con_state)" = activated ] || break
+ hold_conn 4
+ sleep 1
+ result "M2-11i$i-p" INFO "slot $SLOT listens on $(redirect_listens); in TIME_WAIT: '$(redirect_waits)'"
+ nmcli connection down "$CON" > /dev/null 2>&1
+ wait_for 20 con_gone
+ sleep 10 # the dispatcher hands a slot out again only after 10 s
+ connect_ok "M2-11i$i" "activation $i of 3 within a minute, after a stop with a connection open"
+ done
+ result M2-11j INFO "slot $SLOT listens on $(redirect_listens); in TIME_WAIT: '$(redirect_waits)'"
end_checks M2-11
}
+s_resolv_conf() {
+ begin M2-30 "dns=split with /etc/resolv.conf linked to resolved's list of the real servers"
+ rm -f "$VARDIR/resolv.conf.saved"
+ cp -a /etc/resolv.conf "$VARDIR/resolv.conf.saved" || { result M2-30 SKIP "cannot save /etc/resolv.conf"; return; }
+ ln -sf ../run/systemd/resolve/resolv.conf /etc/resolv.conf
+ activate
+ wait_for 20 con_gone
+ check M2-30a "the activation is refused" con_gone
+ check M2-30b "plugin log: dns=split needs systemd-resolved (resolv.conf or NM's DNS mode)" plog_show "dns=split needs"
+ rm -f /etc/resolv.conf
+ cp -a "$VARDIR/resolv.conf.saved" /etc/resolv.conf
+ restorecon /etc/resolv.conf 2> /dev/null
+ result M2-30c INFO "/etc/resolv.conf restored: $(readlink /etc/resolv.conf || echo 'a file')"
+ check M2-30d "nothing left: no link, guard, tunnel unit" all_clean
+ end_checks M2-30
+}
+
s_override() {
begin M2-12 "user override of the unmanaged setting"
printf '[keyfile]\nunmanaged-devices=interface-name:nmtest-nosuch\n' | write_file "$NM_OVERRIDE"
@@ -625,6 +665,18 @@ s_stoppost() {
make_leftovers
sc stop "$PLUGIN_UNIT"
check M2-14d "leftovers made while the plugin idles are removed by ExecStopPost on stop" all_clean
+ # e: another user's listener on a stale table's port does not keep the table
+ as_user python3 -c 'import socket, time
+s = [socket.create_server((a, 59998)) for a in ("127.0.0.1", "127.0.0.2")]
+time.sleep(30)' &
+ local lpid=$!
+ wait_for 5 sh -c "ss -ltnH 'sport = :59998' | grep -q ."
+ nft add table inet sshuttle-ipv4-59998
+ "$LIBEXEC/nm-sshuttle" sweep 2> /dev/null
+ check M2-14e "the sweep removes a stale table whose port another user listens on" \
+ sh -c "! nft list tables | grep -q sshuttle-ipv4-59998"
+ kill "$lpid" 2> /dev/null
+ nft delete table inet sshuttle-ipv4-59998 2> /dev/null
end_checks M2-14
}
@@ -1608,6 +1660,7 @@ want M2-26 && s_park
want M2-27 && s_probe
want M2-28 && s_suspend
want M2-29 && s_jump_name
+want M2-30 && s_resolv_conf
want V6-01 && s_ipv6
want V6-02 && s_ipv6_roam
want TP-01 && s_tproxy
diff --git a/tests/fakes.py b/tests/fakes.py
index bc7c16d..785a15d 100644
--- a/tests/fakes.py
+++ b/tests/fakes.py
@@ -66,6 +66,10 @@ def __init__(self):
self.claims = [] # claims taken, in order
self.conflict = None # what take_claim answers
self.released = 0
+ self.dns_backend = "systemd-resolved" # NetworkManager's DnsManager Mode
+ self.resolv_conf = None # why /etc/resolv.conf bypasses resolved, or None
+ self.guard_there = True # what guard_listed answers: True, False or None
+ self.guard_checks = 0
# recording helpers
def _rec(self, *event):
@@ -108,6 +112,12 @@ def find_device(self, iface, done):
else:
self.device_cbs.append(done)
+ def dns_mode(self, done):
+ done(self.dns_backend, None if self.dns_backend else "no answer")
+
+ def resolv_conf_problem(self):
+ return self.resolv_conf
+
def device_state(self, path, done):
self._rec("device_state", path)
self.device_state_cbs.append(done)
@@ -211,6 +221,10 @@ def remove_policy_routing(self):
def remove_guard(self):
self._rec("remove_guard")
+ def guard_listed(self):
+ self.guard_checks += 1
+ return self.guard_there
+
def sweep(self):
self._rec("sweep")
diff --git a/tests/profile-cases.json b/tests/profile-cases.json
index 960e03f..bf1ec9a 100644
--- a/tests/profile-cases.json
+++ b/tests/profile-cases.json
@@ -35,6 +35,33 @@
{"name": "remote with a shell command", "data": {"remote": "corp; rm -rf /"}, "error": "remote"},
{"name": "remote with a space", "data": {"remote": "corp example"}, "error": "remote"},
{"name": "remote with a trailing newline", "data": {"remote": "corp\n"}, "error": "remote"},
+ {"name": "remote with a user", "data": {"remote": "bob@corp"}},
+ {"name": "remote with an @ in the user", "data": {"remote": "bob@example.com@gw.example"}},
+ {"name": "remote as a bracketed address with a port", "data": {"remote": "[2001:db8::1]:2222"}},
+ {"name": "remote with a user and a bracketed address", "data": {"remote": "bob@[2001:db8::1]:22"}},
+ {"name": "remote as a bare IPv6 address", "data": {"remote": "2001:db8::1"}},
+ {"name": "remote as a link-local address with a scope id", "data": {"remote": "fe80::1%eth0"}},
+ {"name": "remote that is only an at sign", "data": {"remote": "@"}, "error": "remote"},
+ {"name": "remote with an empty user", "data": {"remote": "@corp"}, "error": "remote"},
+ {"name": "remote with an empty user and password", "data": {"remote": ":@"}, "error": "remote"},
+ {"name": "remote with a password", "data": {"remote": "alice:hunter2@corp"}, "error": "remote"},
+ {"name": "remote with an empty host", "data": {"remote": "bob@"}, "error": "remote"},
+ {"name": "remote whose host looks like an option", "data": {"remote": "@-gD1080"}, "error": "remote"},
+ {"name": "remote with a user whose host looks like an option", "data": {"remote": "bob@-gD1080"}, "error": "remote"},
+ {"name": "remote that is only a port", "data": {"remote": ":22"}, "error": "remote"},
+ {"name": "remote with an empty port", "data": {"remote": "corp:"}, "error": "remote"},
+ {"name": "remote with port 0", "data": {"remote": "corp:0"}, "error": "remote"},
+ {"name": "remote with port 65536", "data": {"remote": "corp:65536"}, "error": "remote"},
+ {"name": "remote with leading zeros in the port", "data": {"remote": "corp:000022"}},
+ {"name": "remote with a port that is not a number", "data": {"remote": "corp:ssh"}, "error": "remote"},
+ {"name": "remote with two colons that is no address", "data": {"remote": "corp:22:33"}, "error": "remote"},
+ {"name": "remote with empty brackets", "data": {"remote": "[]:22"}, "error": "remote"},
+ {"name": "remote that is only empty brackets", "data": {"remote": "[]"}, "error": "remote"},
+ {"name": "remote as a bracketed address without a port", "data": {"remote": "[2001:db8::1]"}},
+ {"name": "remote with a user, a name and a port", "data": {"remote": "bob@gw.example:2222"}},
+ {"name": "remote with a name in brackets", "data": {"remote": "[corp]:22"}, "error": "remote"},
+ {"name": "remote with text after the brackets", "data": {"remote": "[2001:db8::1]x"}, "error": "remote"},
+ {"name": "remote with a bracket in a name", "data": {"remote": "co[rp"}, "error": "remote"},
{"name": "local user with a space", "data": {"local-user": "alice x"}, "error": "local-user"},
{"name": "local user that looks like an option", "data": {"local-user": "-alice"}, "error": "local-user"},
@@ -72,10 +99,14 @@
{"name": "subnets that are a bare IPv6 address", "data": {"subnets": "2001:db8::1"}},
{"name": "subnets with an IPv6 prefix of 129", "data": {"subnets": "2001:db8::/129"}, "error": "subnets"},
{"name": "subnets with an IPv6 address that is too long", "data": {"subnets": "2001:db8::1::2/64"}, "error": "subnets"},
+ {"name": "subnets with a scope id", "data": {"subnets": "fe80::%eth0/64"}, "error": "subnets"},
+ {"name": "subnets with an nft include in a scope id", "data": {"subnets": "fe80::%x};include\"passwd\";/64"}, "error": "subnets"},
{"name": "exclude inside the subnets", "data": {"exclude": "10.0.5.0/24, 10.0.6.0/24"}},
{"name": "exclude that is nonsense", "data": {"exclude": "nonsense"}, "error": "exclude"},
{"name": "exclude that is IPv6", "data": {"exclude": "fd00::/8"}},
{"name": "exclude with an IPv6 prefix of 129", "data": {"exclude": "2001:db8::/129"}, "error": "exclude"},
+ {"name": "exclude with a scope id", "data": {"exclude": "fe80::1%eth0"}, "error": "exclude"},
+ {"name": "exclude with an nft include in a scope id", "data": {"exclude": "fe80::%x};include\"passwd\";/64"}, "error": "exclude"},
{"name": "dns none without servers", "data": {"dns": "none", "dns-servers": null, "dns-domains": null}},
{"name": "dns not set", "data": {"dns": null, "dns-servers": null, "dns-domains": null}},
@@ -89,6 +120,7 @@
{"name": "dns server out of range", "data": {"dns-servers": "10.1.0.300"}, "error": "dns-servers"},
{"name": "dns server that is a network", "data": {"dns-servers": "10.1.0.0/24"}, "error": "dns-servers"},
{"name": "dns server that is IPv6", "data": {"dns-servers": "fd00::53"}, "error": "dns-servers"},
+ {"name": "dns server with a scope id", "data": {"dns-servers": "fe80::53%eth0"}, "error": "dns-servers"},
{"name": "dns domains of several kinds", "data": {"dns-domains": "corp.example ~lab.example. ~. other"}},
{"name": "dns split without domains", "data": {"dns-domains": null}, "error": "dns-domains"},
{"name": "dns split with empty domains", "data": {"dns-domains": ""}, "error": "dns-domains"},
@@ -108,6 +140,9 @@
{"name": "gateway out of range", "data": {"gateway": "203.0.113.256"}, "error": "gateway"},
{"name": "gateway that is IPv6", "data": {"gateway": "2001:db8::1"}},
{"name": "gateway that is a bad IPv6 address", "data": {"gateway": "2001:db8::g"}, "error": "gateway"},
+ {"name": "gateway with a scope id", "data": {"gateway": "fe80::1%eth0"}, "error": "gateway"},
+ {"name": "gateway with a scope that holds spaces", "data": {"gateway": "fe80::1%x } include \"passwd\""}, "error": "gateway"},
+ {"name": "gateway with a scope that holds a newline", "data": {"gateway": "fe80::1%x\nflush ruleset"}, "error": "gateway"},
{"name": "probe", "data": {"probe": "10.1.0.10:22"}},
{"name": "probe that is empty", "data": {"probe": ""}},
@@ -115,6 +150,9 @@
{"name": "probe that is IPv6 without brackets", "data": {"probe": "2001:db8::10:22"}, "error": "probe"},
{"name": "probe that is IPv4 in brackets", "data": {"probe": "[10.1.0.10]:22"}, "error": "probe"},
{"name": "probe that is IPv6 with port 0", "data": {"probe": "[2001:db8::10]:0"}, "error": "probe"},
+ {"name": "probe with a scope id", "data": {"probe": "[fe80::1%eth0]:22"}, "error": "probe"},
+ {"name": "probe with a scope id without brackets", "data": {"probe": "fe80::1%eth0:22"}, "error": "probe"},
+ {"name": "probe with a scope that holds a newline", "data": {"probe": "[fe80::1%x\n}]:22"}, "error": "probe"},
{"name": "probe without a port", "data": {"probe": "10.1.0.10"}, "error": "probe"},
{"name": "probe with port 0", "data": {"probe": "10.1.0.10:0"}, "error": "probe"},
{"name": "probe with port 65536", "data": {"probe": "10.1.0.10:65536"}, "error": "probe"},
diff --git a/tests/test_cli.py b/tests/test_cli.py
index e564ac1..84e6178 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -125,12 +125,106 @@ def test_check_passes(dennis, capsys):
def run(argv):
ran.append(argv)
return SimpleNamespace(returncode=0)
- assert cli.check(argparse.Namespace(name="corp"), Nmcli({"u1": conn()}), ssh_g_ok, run) == 0
+ assert cli.check(argparse.Namespace(name="corp"), Nmcli({"u1": conn()}), ssh_g_ok, run,
+ port_start=lambda: 1024, cgroup=lambda unit: "/sys/fs/cgroup/x") == 0
assert ran == [["ssh", "-o", "ConnectTimeout=15", "--", "corp", "true"]]
out = capsys.readouterr().out
assert "first hop 192.0.2.7" in out and "WARN" not in out
+def test_check_refuses_a_first_hop_in_the_tunnelled_networks(dennis, capsys, monkeypatch):
+ # As the plugin does (design §4.2): the lookup may be spoofed.
+ def ssh_g(_user, target):
+ return "hostname gw.corp.example\nproxyjump none\n"
+ monkeypatch.setattr(cli.tunnel, "first_hop", lambda u, r, g: (["10.20.30.40"], False))
+ assert cli.check(argparse.Namespace(name="corp"), Nmcli({"u1": conn()}), ssh_g, None,
+ port_start=lambda: 1024, cgroup=lambda unit: "/x") == 1
+ out = capsys.readouterr().out
+ assert "WARN first hop 10.20.30.40 lies in the profile's networks" in out
+ assert "FAIL the first hop has no usable address" in out
+ data = "remote = corp, local-user = dennis, subnets = 10.0.0.0/8, exclude = 10.20.30.0/24"
+ ran = []
+ assert cli.check(argparse.Namespace(name="corp"), Nmcli({"u1": conn(**{"vpn.data": data})}),
+ ssh_g, lambda argv: ran.append(argv) or SimpleNamespace(returncode=0),
+ port_start=lambda: 1024, cgroup=lambda unit: "/x") == 0
+ assert "ok ssh -G; first hop 10.20.30.40" in capsys.readouterr().out
+
+
+def test_check_takes_a_first_hop_given_as_an_address(dennis, capsys):
+ # No lookup, so nothing to spoof: as 'gateway' (design §4.2).
+ def ssh_g(_user, target):
+ return "hostname 10.20.30.40\nproxyjump none\n"
+ ran = []
+ assert cli.check(argparse.Namespace(name="corp"), Nmcli({"u1": conn()}), ssh_g,
+ lambda argv: ran.append(argv) or SimpleNamespace(returncode=0),
+ port_start=lambda: 1024, cgroup=lambda unit: "/x") == 0
+ out = capsys.readouterr().out
+ assert "ok ssh -G; first hop 10.20.30.40" in out and "WARN" not in out
+
+
+def test_first_hop_prints_its_kind_for_the_plugin(monkeypatch, capsys):
+ monkeypatch.setattr(cli.tunnel, "first_hop", lambda u, r: (["10.0.0.5"], True))
+ assert cli.main(["first-hop", "--kind", "alice", "corp"]) == 0
+ assert capsys.readouterr().out == "given\n10.0.0.5\n"
+ monkeypatch.setattr(cli.tunnel, "first_hop", lambda u, r: (["192.0.2.7", "2001:db8::7"], False))
+ assert cli.main(["first-hop", "--kind", "alice", "corp"]) == 0
+ assert capsys.readouterr().out == "lookup\n192.0.2.7\n2001:db8::7\n"
+ # a plugin started before an upgrade asks without --kind
+ assert cli.main(["first-hop", "alice", "corp"]) == 0
+ assert capsys.readouterr().out == "192.0.2.7\n2001:db8::7\n"
+
+
+SPLIT = "remote = corp, local-user = dennis, subnets = 10.0.0.0/8, dns = split, " \
+ "dns-servers = 10.1.0.53, dns-domains = ~corp.example"
+
+
+def test_check_wants_resolved_for_split_dns(dennis, capsys):
+ nm = Nmcli({"u1": conn(**{"vpn.data": SPLIT})})
+ def run(argv):
+ return SimpleNamespace(returncode=0)
+ assert cli.check(argparse.Namespace(name="corp"), nm, ssh_g_ok, run,
+ dns_mode=lambda: "default") == 1
+ assert "FAIL dns=split needs NetworkManager to use systemd-resolved; its DNS mode is " \
+ "default" in capsys.readouterr().out
+ assert cli.check(argparse.Namespace(name="corp"), nm, ssh_g_ok, run,
+ dns_mode=lambda: "systemd-resolved", resolv_conf=lambda: None) == 0
+ assert cli.check(argparse.Namespace(name="corp"), nm, ssh_g_ok, run,
+ dns_mode=lambda: None, resolv_conf=lambda: None) == 0
+ assert "WARN cannot read NetworkManager's DNS mode" in capsys.readouterr().out
+ # resolv.conf linked to resolved's list of the real servers
+ assert cli.check(argparse.Namespace(name="corp"), nm, ssh_g_ok, run,
+ dns_mode=lambda: "systemd-resolved",
+ resolv_conf=lambda: "/etc/resolv.conf lists 192.168.1.1") == 1
+ assert "FAIL dns=split needs every lookup to go to systemd-resolved; /etc/resolv.conf " \
+ "lists 192.168.1.1" in capsys.readouterr().out
+
+
+def test_nm_dns_mode_from_busctl():
+ def run(argv, **kw):
+ assert argv[:3] == ["busctl", "--system", "get-property"] and argv[-1] == "Mode"
+ return SimpleNamespace(returncode=0, stdout='s "systemd-resolved"\n')
+ assert cli.nm_dns_mode(run) == "systemd-resolved"
+ assert cli.nm_dns_mode(lambda argv, **kw: SimpleNamespace(returncode=1, stdout="")) is None
+
+
+def test_check_warns_without_systemds_cgroups(dennis, capsys):
+ def run(argv):
+ return SimpleNamespace(returncode=0)
+ assert cli.check(argparse.Namespace(name="corp"), Nmcli({"u1": conn()}), ssh_g_ok, run,
+ port_start=lambda: 1024, cgroup=lambda unit: None) == 0
+ assert "WARN no cgroup hierarchy under /sys/fs/cgroup holds systemd's units" in \
+ capsys.readouterr().out
+
+
+def test_check_warns_when_users_may_bind_the_redirect_ports(dennis, capsys):
+ def run(argv):
+ return SimpleNamespace(returncode=0)
+ assert cli.check(argparse.Namespace(name="corp"), Nmcli({"u1": conn()}), ssh_g_ok, run,
+ port_start=lambda: 0) == 0
+ assert "WARN net.ipv4.ip_unprivileged_port_start is 0: any user may bind sshuttle's " \
+ "redirect ports 225-240" in capsys.readouterr().out
+
+
def test_check_reads_escaped_fields(dennis, capsys):
data = "remote = corp, local-user = dennis, subnets = 10.0.0.0/8, probe = 10.1.0.22:22"
nm = Nmcli({"u1": conn(**{"vpn.data": data})})
diff --git a/tests/test_data.py b/tests/test_data.py
index 20f257f..2b926eb 100644
--- a/tests/test_data.py
+++ b/tests/test_data.py
@@ -2,6 +2,7 @@
"""The installed files carry the settings the design depends on."""
import configparser
+import xml.etree.ElementTree as ET
from pathlib import Path
DATA = Path(__file__).resolve().parent.parent / "data"
@@ -19,6 +20,13 @@ def test_conf_d_keeps_every_link_unmanaged_without_replacing_the_list():
assert dict(cp["keyfile"]) == {"unmanaged-devices+": "interface-name:nmss*"}
+def test_bus_policy_denies_only_by_destination():
+ # dbus-daemon(1): a deny by interface alone also refuses every message
+ # without an interface field, to any service on the bus.
+ for deny in ET.parse(DATA / "nm-sshuttle.conf").getroot().iter("deny"):
+ assert "send_destination" in deny.attrib or "own_prefix" in deny.attrib, deny.attrib
+
+
def test_plugin_unit_cleans_up_its_slot_after_any_exit():
svc = ini("nm-sshuttle@.service.in")["Service"]
assert svc["Type"] == "notify"
@@ -58,3 +66,47 @@ def test_tunnel_unit_outlasts_the_plugins_longest_attempt():
from nm_sshuttle.supervisor import Supervisor
timeout = int(ini("nm-sshuttle-tunnel@.service.in")["Service"]["TimeoutStartSec"])
assert timeout > Supervisor.UNLOCK_START_TIMEOUT > Supervisor.TUNNEL_START_TIMEOUT
+
+
+def directives(name):
+ """The [Service] keys of a unit, with space-separated values as sets."""
+ return {k: set(v.split()) for k, v in ini(name)["Service"].items()}
+
+
+UNITS = ("nm-sshuttle-tunnel@.service.in", "nm-sshuttle@.service.in",
+ "nm-sshuttle-dispatcher.service.in")
+
+
+def test_every_unit_has_the_common_sandbox():
+ for name in UNITS:
+ svc = directives(name)
+ for key in ("ProtectKernelTunables", "ProtectControlGroups", "LockPersonality",
+ "RestrictRealtime", "RestrictSUIDSGID"):
+ assert svc[key] == {"yes"}, (name, key)
+ # iptables-legacy runs modprobe itself; nothing may set NoNewPrivileges,
+ # which would stop setuid helpers and SELinux transitions (design §4.7)
+ for key in ("ProtectKernelModules", "NoNewPrivileges", "ProtectClock",
+ "PrivateDevices", "SystemCallFilter", "MemoryDenyWriteExecute"):
+ assert key not in svc, (name, key)
+
+
+def test_the_tunnel_unit_keeps_etc_read_only_and_ssh_working():
+ svc = directives("nm-sshuttle-tunnel@.service.in")
+ # sshuttle's root firewall helper must not write /etc/hosts (design §4.8)
+ assert svc["ProtectSystem"] == {"full"}
+ assert not any(k.startswith(("ReadWritePaths", "ProtectHome", "PrivateTmp",
+ "RestrictAddressFamilies", "RestrictNamespaces"))
+ for k in svc)
+ assert svc["CapabilityBoundingSet"] == {
+ "CAP_NET_ADMIN", "CAP_NET_RAW", "CAP_NET_BIND_SERVICE", "CAP_SETUID", "CAP_SETGID",
+ "CAP_KILL", "CAP_DAC_READ_SEARCH", "CAP_SYS_PTRACE", "CAP_SYS_MODULE"}
+
+
+def test_the_units_that_clean_up_can_write_etc_hosts():
+ for name in ("nm-sshuttle@.service.in", "nm-sshuttle-dispatcher.service.in"):
+ svc = directives(name)
+ assert svc["ProtectSystem"] == {"true"}, name
+ # they start units through systemd's D-Bus API (CAP_SYS_ADMIN), and
+ # ssh-as-user resets the OOM floor (CAP_SYS_RESOURCE; design §4.7)
+ assert "CapabilityBoundingSet" not in svc and "ReadOnlyPaths" not in svc, name
+ assert "ProtectHome" not in directives("nm-sshuttle@.service.in") # ssh -G as the user
diff --git a/tests/test_events.py b/tests/test_events.py
index f17de51..0b4f3b7 100644
--- a/tests/test_events.py
+++ b/tests/test_events.py
@@ -2,6 +2,8 @@
"""Sleep, network changes, health checks, the lock screen and the NM version
mark (design §4.4), with fake events and a fake clock."""
+import logging
+
import pytest
from fakes import AC, NM, bring_up, drop_and_retry, make, settings
@@ -157,6 +159,65 @@ def test_network_change_while_up_restarts_at_once_with_a_new_first_hop(up):
assert config and config[0]["gateway"] == "198.51.100.200"
+def test_a_new_first_hop_only_in_the_tunnelled_networks_keeps_the_old_one(up):
+ # The lookup ran on the new network, which may spoof it (design §4.2).
+ fx, sup = up
+ sup.on_network(ONLINE, CONN_FULL, HOTEL)
+ answer_starting(sup)
+ fx.finish_stops()
+ fx.advance(0)
+ fx.clear()
+ fx.first_hop_cbs.pop(0)(["10.20.30.40", "198.51.100.200"], None)
+ assert fx.events[0] == ("install_guard", ["10.0.0.0/8"], ["198.51.100.200"])
+ assert fx.events[1][1]["pin"] is True # ssh must not take the refused one
+ reconnect(fx, sup)
+ sup.on_network(ONLINE, CONN_FULL, WIFI)
+ answer_starting(sup)
+ fx.finish_stops()
+ fx.advance(0)
+ fx.clear()
+ fx.first_hop_cbs.pop(0)(["10.20.30.40"], None)
+ assert "install_guard" not in fx.names() and "spec" not in fx.names()
+ assert sup.hops == ["198.51.100.200"] and fx.names() == ["start_tunnel"]
+ # a HostName that is an address was not looked up, so it is taken
+ reconnect(fx, sup)
+ sup.on_network(ONLINE, CONN_FULL, HOTEL)
+ answer_starting(sup)
+ fx.finish_stops()
+ fx.advance(0)
+ fx.clear()
+ fx.first_hop_cbs.pop(0)(["10.20.30.40"], None, True)
+ assert fx.events[0] == ("install_guard", ["10.0.0.0/8"], ["10.20.30.40"])
+ assert "pin" not in fx.events[1][1]
+
+
+def test_a_split_horizon_first_hop_pins_ssh_to_the_old_address(up, caplog):
+ # On the office network the name resolves inside the subnets; ssh would
+ # follow that answer into the guard's reset (design §4.2).
+ fx, sup = up
+ sup.on_network(ONLINE, CONN_FULL, HOTEL)
+ answer_starting(sup)
+ fx.finish_stops()
+ fx.advance(0)
+ fx.clear()
+ old = list(sup.hops)
+ fx.first_hop_cbs.pop(0)(["10.1.2.3"], None)
+ assert sup.hops == old and "install_guard" not in fx.names()
+ spec = [e[1] for e in fx.events if e[0] == "spec"][0]
+ assert spec["first_hop"] == old and spec["pin"] is True
+ with caplog.at_level(logging.WARNING, logger="nm-sshuttle"):
+ fx.finish_start(False, "start job failed\nConnection timed out")
+ assert "the first hop's name also resolves to 10.1.2.3" in caplog.text
+ # back on a network where it resolves outside them: no pin
+ sup.on_network(ONLINE, CONN_FULL, WIFI)
+ answer_starting(sup)
+ fx.finish_stops()
+ fx.advance(0)
+ fx.clear()
+ fx.first_hop_cbs.pop(0)(old, None)
+ assert "pin" not in [e[1] for e in fx.events if e[0] == "spec"][0]
+
+
def test_give_up_before_the_new_first_hop_was_sent_repeats_the_old_config(up):
# Branch 3 needs the Config NM has; the new first hop only goes out with a burst.
fx, sup = up
@@ -322,6 +383,79 @@ def test_health_drops_when_sshuttle_outlives_its_ssh(up):
assert sup.phase == "gap" and ("state", ST_STARTING) in fx.events
+def test_health_gives_up_once_without_systemds_cgroups(up, caplog):
+ # dropping every 10 s would never end on such a host (design §4.8)
+ fx, sup = up
+ fx.health = {"guard": True, "sshuttle": set(), "cgroup": False}
+ fx.advance(10)
+ assert sup.phase == "stopping" and ("failure", FAIL_CONNECT) in fx.events
+ assert "no listener counts as the tunnel's own" in caplog.text
+
+
+def test_a_reconnect_without_a_free_dns_port_says_why(up, caplog):
+ fx, sup = up
+ sup.on_tunnel_inactive()
+ sup.on_ac_state(AC, AC_ACTIVATING, 6)
+ fx.advance(1.0)
+ fx.finish_start(False, "c : TCP redirector listening on ('127.0.0.1', 225).\n"
+ "OSError: [Errno 98] Address already in use")
+ assert sup.phase == "gap"
+ assert "no free port for sshuttle's DNS redirector (9001-12300)" in caplog.text
+
+
+def test_a_gap_puts_back_a_flushed_guard_while_paused(up):
+ fx, sup = up
+ sup.on_network(OFFLINE, CONN_NONE, None) # a paused gap: no attempts at all
+ answer_starting(sup)
+ assert sup.phase == "gap" and "retry" not in sup.timers
+ fx.clear()
+ fx.guard_there = None # nft cannot be asked: nothing to do
+ fx.advance(10)
+ assert fx.names() == []
+ fx.guard_there = False
+ fx.advance(10)
+ assert fx.names() == ["install_guard"] and sup.phase == "gap"
+ fx.guard_there = True
+ fx.advance(30)
+ assert fx.names() == ["install_guard"] and fx.guard_checks == 5
+
+
+def test_each_reconnect_attempt_checks_the_guard_first(up):
+ fx, sup = up
+ sup.on_tunnel_inactive()
+ answer_starting(sup)
+ fx.clear()
+ fx.guard_there = False
+ fx.advance(1)
+ assert fx.names() == ["install_guard", "start_tunnel"]
+ reconnect(fx, sup)
+ fx.clear()
+ fx.advance(30) # up again: the health check takes over
+ assert "install_guard" not in fx.names() and fx.guard_checks == 1
+
+
+def test_a_guard_that_cannot_be_put_back_in_a_gap_gives_up(up):
+ fx, sup = up
+ sup.on_tunnel_inactive()
+ answer_starting(sup)
+ fx.guard_there = False
+ fx.raise_on["install_guard"] = RuntimeError("nft says no")
+ fx.advance(1)
+ assert sup.phase == "stopping" and ("failure", FAIL_CONNECT) in fx.events
+ assert "start_tunnel" not in fx.names()
+
+
+def test_no_guard_check_without_fail_closed():
+ fx, sup = make()
+ sup.on_network(ONLINE, CONN_FULL, WIFI)
+ bring_up(fx, sup, **{"fail-closed": "no"})
+ sup.on_tunnel_inactive()
+ answer_starting(sup)
+ fx.guard_there = False
+ fx.advance(20)
+ assert fx.guard_checks == 0 and "install_guard" not in fx.names()
+
+
def test_health_keeps_a_tunnel_whose_ssh_runs_or_cannot_be_read(up):
fx, sup = up
fx.health = {"guard": True, "sshuttle": {4}, "ssh": True}
diff --git a/tests/test_guard.py b/tests/test_guard.py
index 702c63a..bc4fb8e 100644
--- a/tests/test_guard.py
+++ b/tests/test_guard.py
@@ -74,3 +74,52 @@ def test_overlapping_networks_install_in_nft():
rules = guard.guard_ruleset(T, ["10.99.0.0/24", "10.99.0.53/32", "10.0.0.0/8"], ["1.2.3.4"])
p = subprocess.run(["nft", "-c", "-f", "-"], input=rules, text=True, capture_output=True)
assert p.returncode == 0, p.stderr
+
+
+INCLUDE = 'fe80::%x};include"passwd";/64'
+
+
+def test_guard_ruleset_holds_only_address_text():
+ # A scope id is refused by profile.parse; should one get past it, its text
+ # still never reaches the root nft script.
+ rules = guard.guard_ruleset(T, ["10.0.0.0/8", INCLUDE], [INCLUDE, "fe80::1%a }\nb"])
+ assert "set subnets6 { type ipv6_addr; flags interval; elements = { fe80::/64 } }" in rules
+ assert "set exclude6 { type ipv6_addr; flags interval; elements = { fe80::/64 } }" in rules
+ assert "%" not in rules and "include" not in rules and '"' not in rules
+
+
+@pytest.mark.skipif(not nft_usable(), reason="needs a working nft (root)")
+def test_guard_ruleset_with_a_scope_parses_in_nft():
+ rules = guard.guard_ruleset(T, ["10.0.0.0/8", INCLUDE], [INCLUDE])
+ p = subprocess.run(["nft", "-c", "-f", "-"], input=rules, text=True, capture_output=True)
+ assert p.returncode == 0, p.stderr
+
+
+def test_install_guard_reports_only_the_error_line_of_nft(monkeypatch):
+ # nft quotes the lines it could not parse, including those of a file that
+ # the script included; only the line naming the error is passed on.
+ out = ("Warning: a warning first\n"
+ "/etc/passwd:1:1-4: Error: syntax error, unexpected string\n"
+ "root:x:0:0:root:/root:/bin/bash\n^^^^")
+ monkeypatch.setattr(guard, "run", lambda argv, input=None: (False, out))
+ with pytest.raises(RuntimeError) as e:
+ guard.install_guard(T, ["10.0.0.0/8"], [])
+ assert str(e.value) == ("cannot install the guard table: "
+ "/etc/passwd:1:1-4: Error: syntax error, unexpected string")
+ monkeypatch.setattr(guard, "run", lambda argv, input=None: (False, "nft: odd\nmore"))
+ with pytest.raises(RuntimeError, match="table: nft: odd$"):
+ guard.install_guard(T, ["10.0.0.0/8"], [])
+ monkeypatch.setattr(guard, "run", lambda argv, input=None: (False, ""))
+ with pytest.raises(RuntimeError, match="nft failed"):
+ guard.install_guard(T, ["10.0.0.0/8"], [])
+
+
+def test_guard_listed_tells_gone_from_unknown(monkeypatch):
+ out = "table inet nm-sshuttle-guard-1\ntable inet sshuttle-ipv4-227\n"
+ monkeypatch.setattr(guard.subprocess, "run",
+ lambda *a, **k: subprocess.CompletedProcess(a, 0, out, ""))
+ assert guard.guard_listed("nm-sshuttle-guard-1") is True
+ assert guard.guard_listed("nm-sshuttle-guard-0") is False
+ monkeypatch.setattr(guard.subprocess, "run",
+ lambda *a, **k: subprocess.CompletedProcess(a, 1, "", "denied"))
+ assert guard.guard_listed("nm-sshuttle-guard-1") is None
diff --git a/tests/test_ipv6.py b/tests/test_ipv6.py
index bc32d13..afe89b6 100644
--- a/tests/test_ipv6.py
+++ b/tests/test_ipv6.py
@@ -120,3 +120,13 @@ def test_a_refreshed_first_hop_list_updates_guard_spec_and_config():
sup.on_ac_state(AC, AC_ACTIVATING, 6)
fx.finish_start(True)
assert [e[1] for e in fx.events if e[0] == "config"][-1]["gateway"] == "198.51.100.9"
+
+
+def test_an_ipv6_first_hop_in_a_tunnelled_ipv6_network_is_left_out():
+ # design §4.2: only 'gateway' or 'exclude' lets a first hop lie there
+ fx, sup = make()
+ connect(fx, sup, ["2001:db8:10::7", "203.0.113.7"], subnets=V6)
+ assert spec(fx)["first_hop"] == ["203.0.113.7"]
+ fx, sup = make()
+ connect(fx, sup, ["2001:db8:10::7"], subnets=V6, exclude="2001:db8:10::7/128")
+ assert spec(fx)["first_hop"] == ["2001:db8:10::7"]
diff --git a/tests/test_multi.py b/tests/test_multi.py
index 1dd9d24..cb24c17 100644
--- a/tests/test_multi.py
+++ b/tests/test_multi.py
@@ -121,7 +121,8 @@ def state_dir(tmp_path, monkeypatch):
def test_take_writes_the_claim_and_refuses_a_conflicting_one(state_dir):
- alive = {1, 2}.__contains__
+ def alive(pid, start):
+ return pid in {1, 2}
assert claims.take(0, dict(claim("corp", ["10.0.0.0/8"]), pid=1), alive) is None
path = state_dir / "0" / "claim.json"
assert json.loads(path.read_text())["id"] == "corp"
@@ -132,13 +133,13 @@ def test_take_writes_the_claim_and_refuses_a_conflicting_one(state_dir):
def test_a_dead_instances_claim_does_not_count(state_dir):
- claims.take(0, dict(claim("corp", ["10.0.0.0/8"]), pid=1), lambda pid: True)
+ claims.take(0, dict(claim("corp", ["10.0.0.0/8"]), pid=1), lambda pid, start: True)
assert claims.take(1, dict(claim("lab", ["10.1.0.0/16"]), pid=2),
- lambda pid: pid != 1) is None
+ lambda pid, start: pid != 1) is None
def test_an_instance_may_retake_its_own_slot(state_dir):
- alive = lambda pid: True # noqa: E731
+ alive = lambda pid, start: True # noqa: E731
claims.take(2, dict(claim("corp", ["10.0.0.0/8"]), pid=1), alive)
assert claims.take(2, dict(claim("corp", ["10.0.0.0/8"], hops=["1.2.3.4"]), pid=1),
alive) is None
@@ -146,16 +147,16 @@ def test_an_instance_may_retake_its_own_slot(state_dir):
def test_release_removes_the_claim(state_dir):
- claims.take(0, claim("corp"), lambda pid: True)
+ claims.take(0, claim("corp"), lambda pid, start: True)
claims.release(0)
claims.release(0) # twice is fine
- assert claims.read_claims(skip=None, alive=lambda pid: True) == []
+ assert claims.read_claims(skip=None, alive=lambda pid, start: True) == []
def test_a_broken_claim_file_is_ignored(state_dir):
(state_dir / "3").mkdir()
(state_dir / "3" / "claim.json").write_text("{")
- assert claims.read_claims(skip=None, alive=lambda pid: True) == []
+ assert claims.read_claims(skip=None, alive=lambda pid, start: True) == []
def test_alive_needs_a_plugin_process():
@@ -163,6 +164,33 @@ def test_alive_needs_a_plugin_process():
assert not claims._alive(os.getpid()) # pytest, not nm-sshuttle-service
+def fake_proc(tmp_path, pid, cmdline, start, uids):
+ """/proc/PID with a cmdline, user IDs and a stat whose command name has spaces."""
+ d = tmp_path / "proc" / str(pid)
+ d.mkdir(parents=True)
+ (d / "cmdline").write_bytes(cmdline)
+ fields = ["S"] + ["0"] * 18 + [str(start)] + ["0"] * 10
+ (d / "stat").write_text(f"{pid} (python3 (x) y) " + " ".join(fields) + "\n")
+ (d / "status").write_text("Name:\tx\nUid:\t" + "\t".join(map(str, uids)) + "\nGid:\t0\n")
+ return str(tmp_path / "proc")
+
+
+def test_alive_wants_roots_plugin_with_the_claimed_start_time(tmp_path):
+ plugin = b"/usr/bin/python3\0/usr/libexec/nm-sshuttle-service\0--slot\0001\0"
+ proc = fake_proc(tmp_path, 42, plugin, 777, (0, 0, 0, 0))
+ assert claims.process_start(42, proc) == 777
+ assert claims._alive(42, 777, proc)
+ assert claims._alive(42, None, proc) # a claim from before start times
+ assert not claims._alive(42, 778, proc) # the PID went to a later process
+ # any user can name a process so: only root's counts
+ other = fake_proc(tmp_path / "u", 43, b"sleep\0001d\0nm-sshuttle-service\0", 5, (1000,) * 4)
+ assert not claims._alive(43, None, other) and not claims._alive(43, 5, other)
+ # nor one with euid 0: sudo waiting for a password keeps the caller's real ID
+ sudo = fake_proc(tmp_path / "s", 44, b"sudo\0-S\0nm-sshuttle-service\0", 5, (1000, 0, 0, 0))
+ assert not claims._alive(44, None, sudo)
+ assert claims.process_start(44, proc) is None
+
+
# --------------------------------------------------------------- dispatcher
def test_pick_slot_takes_the_lowest_free_one():
states = {0: "active", 1: "inactive", 2: "failed"}
@@ -230,10 +258,14 @@ def test_the_plugin_reads_its_bus_name(state_dir):
# --------------------------------------------------------- one tunnel's ports
def proc_tree(tmp_path, unit, pids):
"""A fake cgroup and /proc: pid 10 holds socket 111 (port 0x3039), pid 20
- socket 222 (port 0x303a); both listen."""
+ socket 222 (port 0x303a), both root's, and socket 333 (port 0x303b) of
+ uid 1000, as a user's ssh with a LocalForward would; all listen."""
cg = tmp_path / "cg"
slice_dir = cg / "system.slice" / "system-nm\\x2dsshuttle\\x2dtunnel.slice"
- slice_dir.mkdir(parents=True)
+ if pids is not None:
+ slice_dir.mkdir(parents=True)
+ else:
+ (cg / "system.slice").mkdir(parents=True) # an empty slice goes too
if pids is not None:
(slice_dir / unit).mkdir()
(slice_dir / unit / "cgroup.procs").write_text("".join(f"{p}\n" for p in pids))
@@ -244,27 +276,29 @@ def proc_tree(tmp_path, unit, pids):
(proc / "net" / "tcp").write_text(
head
+ " 0: 0100007F:3039 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 111\n"
- + " 1: 0100007F:303A 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 222\n")
+ + " 1: 0100007F:303A 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 222\n"
+ + " 2: 0100007F:303B 00000000:0000 0A 00000000:00000000 00:00000000 00000000 "
+ "1000 0 333\n")
(proc / "net" / "tcp6").write_text(head)
- for pid, inode in ((10, 111), (20, 222)):
+ for pid, inode in ((10, 111), (20, 222), (30, 333)):
(proc / str(pid) / "fd").mkdir(parents=True)
os.symlink(f"socket:[{inode}]", proc / str(pid) / "fd" / "3")
os.symlink("/dev/null", proc / str(pid) / "fd" / "0")
- return str(cg), str(proc)
+ return (str(cg),), str(proc)
def test_unit_ports_are_only_the_units_own(tmp_path):
unit = "nm-sshuttle-tunnel@1.service"
- cg, proc = proc_tree(tmp_path, unit, [10])
- assert tunnel.unit_ports(unit, cg, proc) == {0x3039}
+ cg, proc = proc_tree(tmp_path, unit, [10, 30])
+ assert tunnel.unit_ports(unit, cg, proc) == {4: {0x3039}, 6: set()}
def test_unit_ports_of_a_stopped_unit_and_an_unknown_layout(tmp_path):
unit = "nm-sshuttle-tunnel@1.service"
cg, proc = proc_tree(tmp_path, unit, None)
- assert tunnel.unit_ports(unit, cg, proc) == set()
- # no slice where expected: the caller falls back to every listener
- assert tunnel.unit_ports(unit, str(tmp_path / "elsewhere"), proc) is None
+ assert tunnel.unit_ports(unit, cg, proc) == {4: set(), 6: set()}
+ # no hierarchy with systemd's units: the caller gives up (design §4.8)
+ assert tunnel.unit_ports(unit, (str(tmp_path / "elsewhere"),), proc) is None
def test_unit_runs_finds_a_command_among_the_units_processes(tmp_path):
@@ -278,13 +312,18 @@ def test_unit_runs_finds_a_command_among_the_units_processes(tmp_path):
assert tunnel.unit_runs(unit, "ssh", cg, proc) is False # sshuttle outlived its ssh
cg, proc = proc_tree(tmp_path / "c", unit, None)
assert tunnel.unit_runs(unit, "ssh", cg, proc) is False # the unit stopped
- assert tunnel.unit_runs(unit, "ssh", str(tmp_path / "elsewhere"), proc) is None
+ assert tunnel.unit_runs(unit, "ssh", (str(tmp_path / "elsewhere"),), proc) is None
-def test_unit_cgroup_of_a_plain_and_a_template_unit():
- assert tunnel.unit_cgroup("a.service", "/c") == "/c/system.slice/a.service"
- assert tunnel.unit_cgroup("nm-sshuttle-tunnel@0.service", "/c") == (
- "/c/system.slice/system-nm\\x2dsshuttle\\x2dtunnel.slice/nm-sshuttle-tunnel@0.service")
+def test_unit_cgroup_on_unified_hybrid_and_legacy_hosts(tmp_path):
+ roots = tuple(str(tmp_path / r) for r in ("v2", "v2/unified", "v2/systemd"))
+ assert tunnel.unit_cgroup("a.service", roots) is None
+ for root in reversed(roots): # legacy (name=systemd), hybrid, then cgroup v2
+ os.makedirs(os.path.join(root, "system.slice"))
+ assert tunnel.unit_cgroup("a.service", roots) == f"{root}/system.slice/a.service"
+ assert tunnel.unit_cgroup("nm-sshuttle-tunnel@0.service", roots) == (
+ f"{roots[0]}/system.slice/system-nm\\x2dsshuttle\\x2dtunnel.slice/"
+ "nm-sshuttle-tunnel@0.service")
# --------------------------------------------------------------- supervisor
@@ -357,7 +396,7 @@ def test_a_new_first_hop_is_claimed_again_and_a_loop_gives_up():
fx.finish_stops()
fx.conflict = "the first hops would run in a loop: corp -> lab -> corp"
fx.clear()
- fx.first_hop_cbs.pop(0)(["10.9.9.9"], None)
+ fx.first_hop_cbs.pop(0)(["198.51.100.9"], None)
assert "install_guard" not in fx.names() and "start_tunnel" not in fx.names()
assert ("failure", FAIL_CONNECT) in fx.events
@@ -434,7 +473,8 @@ def host(monkeypatch, tmp_path):
"""Record what cleanup does; plugin units in `running` are active."""
monkeypatch.setattr(const, "STATE_DIR", str(tmp_path))
monkeypatch.setattr(claims, "STATE_DIR", str(tmp_path))
- rec = SimpleNamespace(stopped=[], removed=[], routing=[], running=set(), swept=0)
+ rec = SimpleNamespace(stopped=[], removed=[], routing=[], running=set(), swept=0,
+ hosts=[], hosts_ok=True)
def systemctl(*args, timeout=30):
if args[0] == "stop":
@@ -453,6 +493,8 @@ def systemctl(*args, timeout=30):
def sweep():
rec.swept += 1
monkeypatch.setattr(cli.tunnel, "sweep", sweep)
+ monkeypatch.setattr(cli.tunnel, "strip_etc_hosts",
+ lambda: rec.hosts.append(rec.stopped[:]) or rec.hosts_ok)
return rec
@@ -468,6 +510,15 @@ def test_cleanup_of_one_slot_touches_only_that_slot(host, tmp_path):
assert not (tmp_path / "2" / "claim.json").exists()
+def test_cleanup_removes_sshuttles_lines_from_etc_hosts_after_the_tunnel_stopped(host):
+ # The tunnel unit cannot write /etc; the plugin unit's cleanup can (design §4.8).
+ assert cli.main(["cleanup", "--slot", "3"]) == 0
+ assert host.hosts == [["nm-sshuttle-tunnel@3.service"]]
+ assert cli.main(["cleanup", "--all"]) == 0 and len(host.hosts) == 2
+ host.hosts_ok = False
+ assert cli.main(["cleanup", "--slot", "3"]) == 1
+
+
def test_cleanup_all_skips_running_slots_and_takes_the_v1_names(host):
host.running = {"nm-sshuttle@0.service", "nm-sshuttle@5.service"}
assert cli.main(["cleanup", "--all"]) == 0
diff --git a/tests/test_packaging.py b/tests/test_packaging.py
new file mode 100644
index 0000000..b18ffb5
--- /dev/null
+++ b/tests/test_packaging.py
@@ -0,0 +1,324 @@
+# SPDX-License-Identifier: MIT
+"""The release pipeline signs only tags on main, and the install steps check the key."""
+
+import http.server
+import json
+import os
+import re
+import shutil
+import subprocess
+import threading
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent
+PACKAGING = ROOT / "packaging"
+PUBKEY = PACKAGING / "nm-sshuttle-release" / "RPM-GPG-KEY-nm-sshuttle"
+
+needs_tools = pytest.mark.skipif(
+ not all(shutil.which(t) for t in ("git", "curl", "jq")), reason="needs git, curl and jq"
+)
+
+
+def git(repo, *args):
+ return subprocess.run(
+ ["git", "-C", str(repo), *args], check=True, capture_output=True, text=True
+ ).stdout.strip()
+
+
+class NotFound(http.server.BaseHTTPRequestHandler):
+ """An empty site: nothing is published yet."""
+
+ def do_HEAD(self):
+ self.send_response(404)
+ self.end_headers()
+
+ do_GET = do_HEAD
+
+ def log_message(self, *args):
+ pass
+
+
+@pytest.fixture
+def site():
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), NotFound)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ yield f"http://127.0.0.1:{server.server_address[1]}"
+ server.shutdown()
+ server.server_close()
+
+
+@pytest.fixture
+def repo(tmp_path):
+ """A checkout with the planner, two commits on main (one tagged v1.0.0)
+ and a v1.0.1 tag on a branch that never reached main."""
+ repo = tmp_path / "repo"
+ files = [
+ "plan.sh",
+ "make-srpm.sh",
+ "fedora-releases",
+ "rpm/nm-sshuttle-gnome.spec",
+ "nm-sshuttle-release/nm-sshuttle-release.spec",
+ "nm-sshuttle-release/RPM-GPG-KEY-nm-sshuttle",
+ ]
+ for f in files:
+ (repo / "packaging" / f).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(PACKAGING / f, repo / "packaging" / f)
+ git(tmp_path, "init", "-q", "-b", "main", str(repo))
+ git(repo, "config", "user.email", "test@invalid")
+ git(repo, "config", "user.name", "test")
+ git(repo, "config", "commit.gpgsign", "false")
+ git(repo, "config", "tag.gpgsign", "false")
+ git(repo, "add", ".")
+ git(repo, "commit", "-q", "-m", "release")
+ git(repo, "tag", "-a", "v1.0.0", "-m", "nm-sshuttle 1.0.0")
+ git(repo, "checkout", "-q", "-b", "side")
+ git(repo, "commit", "-q", "--allow-empty", "-m", "not reviewed")
+ git(repo, "tag", "-a", "v1.0.1", "-m", "nm-sshuttle 1.0.1")
+ git(repo, "checkout", "-q", "main")
+ git(repo, "update-ref", "refs/remotes/origin/main", "main")
+ return repo
+
+
+def plan(repo, site, **env):
+ out = repo / "out"
+ out.unlink(missing_ok=True)
+ full = {
+ k: v
+ for k, v in os.environ.items()
+ if not k.lower().endswith("_proxy") and not k.startswith("GITHUB_")
+ }
+ full.update(PAGES_URL=site, GITHUB_OUTPUT=str(out), GITHUB_REF="refs/heads/main")
+ full.update(env)
+ r = subprocess.run(
+ [str(repo / "packaging" / "plan.sh")], env=full, capture_output=True, text=True
+ )
+ if not out.exists():
+ return r, {}
+ return r, dict(line.split("=", 1) for line in out.read_text().splitlines())
+
+
+@needs_tools
+def test_plan_publishes_a_tag_on_main(repo, site):
+ r, out = plan(repo, site, INPUT_TAG="v1.0.0")
+ assert r.returncode == 0, r.stdout + r.stderr
+ assert out["tag"] == "v1.0.0"
+ assert out["commit"] == git(repo, "rev-parse", "main")
+ assert out["publish"] == "real"
+
+
+@needs_tools
+def test_plan_refuses_a_tag_off_main(repo, site):
+ r, out = plan(repo, site, INPUT_TAG="v1.0.1")
+ assert r.returncode == 1
+ assert "not on main" in r.stdout
+ assert out == {}
+
+
+@needs_tools
+def test_plan_refuses_a_newest_tag_off_main(repo, site):
+ # Without an input, the newest tag is v1.0.1, which is not on main.
+ r, out = plan(repo, site, INPUT_TAG="")
+ assert r.returncode == 1
+ assert "v1.0.1" in r.stdout and "not on main" in r.stdout
+
+
+@needs_tools
+def test_plan_accepts_a_tag_once_main_has_it(repo, site):
+ git(repo, "merge", "-q", "--ff-only", "side")
+ git(repo, "update-ref", "refs/remotes/origin/main", "main")
+ r, out = plan(repo, site, INPUT_TAG="v1.0.1")
+ assert r.returncode == 0, r.stdout + r.stderr
+ assert out["commit"] == git(repo, "rev-parse", "v1.0.1^{commit}")
+
+
+@needs_tools
+def test_plan_needs_main_to_check_a_tag(repo, site):
+ git(repo, "update-ref", "-d", "refs/remotes/origin/main")
+ r, _ = plan(repo, site, INPUT_TAG="v1.0.0")
+ assert r.returncode == 1
+ assert "origin/main is missing" in r.stdout
+
+
+@needs_tools
+def test_plan_dry_run_names_no_tag_or_commit(repo, site):
+ r, out = plan(repo, site, INPUT_TAG="v1.0.0", GITHUB_REF="refs/pull/1/merge")
+ assert r.returncode == 0, r.stdout + r.stderr
+ assert out["tag"] == out["commit"] == ""
+ assert out["publish"] == "dry-run"
+
+
+def make_srpm(repo, *args):
+ return subprocess.run(
+ [str(repo / "packaging" / "make-srpm.sh"), str(repo / "out"), *args],
+ capture_output=True,
+ text=True,
+ )
+
+
+@needs_tools
+def test_srpm_refuses_a_tag_moved_since_the_plan(repo):
+ # The plan checked v1.0.0's commit; the tag now names another one.
+ checked = git(repo, "rev-parse", "v1.0.0^{commit}")
+ git(repo, "tag", "-f", "-a", "v1.0.0", "-m", "moved", "side")
+ r = make_srpm(repo, "v1.0.0", checked)
+ assert r.returncode == 1
+ assert "has moved" in r.stderr
+ assert not (repo / "out").exists()
+
+
+@needs_tools
+def test_srpm_refuses_an_empty_commit(repo):
+ r = make_srpm(repo, "v1.0.0", "")
+ assert r.returncode == 2
+
+
+@pytest.mark.skipif(
+ not all(shutil.which(t) for t in ("git", "rpmbuild")), reason="needs git and rpmbuild"
+)
+def test_srpm_builds_the_checked_commit(repo):
+ for f in PACKAGING.glob("rpm/*.spec"):
+ shutil.copy2(f, repo / "packaging" / "rpm")
+ git(repo, "add", ".")
+ git(repo, "commit", "-q", "-m", "specs")
+ r = make_srpm(repo, "v1.0.0", git(repo, "rev-parse", "v1.0.0^{commit}"))
+ assert r.returncode == 0, r.stdout + r.stderr
+ names = [p.name for p in (repo / "out").iterdir()]
+ assert any(n.startswith("nm-sshuttle-1.0.0-") for n in names), names
+
+
+def test_srpm_job_passes_the_checked_commit():
+ wf = (ROOT / ".github/workflows/packages.yaml").read_text()
+ assert "commit: ${{ steps.plan.outputs.commit }}" in wf
+ assert "COMMIT: ${{ needs.plan.outputs.commit }}" in wf
+ assert 'packaging/make-srpm.sh out ${TAG:+"$TAG" "$COMMIT"}' in wf
+
+
+def key_fingerprints(home):
+ if not shutil.which("gpg"):
+ pytest.skip("needs gpg")
+ home.mkdir(mode=0o700)
+ out = subprocess.run(
+ ["gpg", "--batch", "--with-colons", "--show-keys", str(PUBKEY)],
+ check=True,
+ capture_output=True,
+ text=True,
+ env={**os.environ, "GNUPGHOME": str(home)},
+ ).stdout
+ fprs, primary = [], False
+ for line in out.splitlines():
+ fields = line.split(":")
+ if fields[0] == "pub":
+ primary = True
+ elif fields[0] == "fpr" and primary:
+ fprs.append(fields[9])
+ primary = False
+ return fprs
+
+
+def test_readme_shows_the_fingerprint_of_the_committed_key(tmp_path):
+ # The README on GitHub is the copy users compare against; gpg --show-keys
+ # prints the fingerprint the same way.
+ readme = (ROOT / "README.md").read_text()
+ shown = re.findall(r"^([0-9A-F]{40})$", readme, re.M)
+ assert shown == key_fingerprints(tmp_path / "gnupg")
+
+
+INSTALL_DOCS = ["README.md", "docs/user-guide.md", "packaging/site/index.html"]
+
+
+@pytest.mark.parametrize("doc", INSTALL_DOCS)
+def test_install_steps_check_the_key_before_importing_it(doc):
+ text = (ROOT / doc).read_text()
+ # The key is imported from a downloaded file, after gpg shows its keys,
+ # and never straight from the site. gpg must show the listed keys, no
+ # other key and no error: a key file gpg cannot parse shows no key at all.
+ assert "rpm --import https://" not in text
+ assert re.search(r"each\s+fingerprint listed", text)
+ assert re.search(r"no\s+other\s+key,\s+and\s+reports\s+no\s+error", text)
+ site = "https://dennisklein.github.io/nm-sshuttle"
+ show = text.index("gpg --show-keys RPM-GPG-KEY-nm-sshuttle")
+ imp = text.index("sudo rpm --import RPM-GPG-KEY-nm-sshuttle")
+ assert text.index(f"curl -fsSLO {site}/RPM-GPG-KEY-nm-sshuttle") < show < imp
+ assert "github.com/dennisklein/nm-sshuttle" in text or doc == "README.md"
+ # dnf checks the repository package against that key only when told to.
+ release = f"{site}/nm-sshuttle-release.noarch.rpm"
+ assert text.count(release) == 1
+ assert imp < text.index(f"sudo dnf install --setopt=localpkg_gpgcheck=1 {release}")
+
+
+def test_smoke_test_installs_the_release_package_as_users_do():
+ text = (PACKAGING / "smoke-test.sh").read_text()
+ assert 'dnf -y install --setopt=localpkg_gpgcheck=1 "$base/nm-sshuttle-release' in text
+
+
+FAKE_GH = r"""#!/usr/bin/env python3
+import json, os, sys
+args = sys.argv[1:]
+call = {"args": args}
+if "--input" in args:
+ call["input"] = json.load(sys.stdin)
+with open(os.environ["GH_LOG"], "a") as f:
+ f.write(json.dumps(call) + "\n")
+if args[:2] == ["auth", "status"] or "--method" in args:
+ sys.exit(0)
+path = [a for a in args[1:] if a.startswith("repos/")][0]
+env = path.split("/")[4]
+if path.endswith("/deployment-branch-policies"):
+ if env == "rpm-signing":
+ print("1\tbranch\tmain\n2\ttag\tv*\n3\tbranch\tdev")
+ sys.exit(0)
+if env == "github-pages":
+ print("gh: Not Found (HTTP 404)", file=sys.stderr)
+ sys.exit(1)
+print(json.dumps({"name": env, "protection_rules": [
+ {"type": "required_reviewers", "prevent_self_review": True,
+ "reviewers": [{"type": "User", "reviewer": {"id": 42, "login": "maintainer"}}]},
+ {"type": "wait_timer", "wait_timer": 5},
+ {"type": "branch_policy"}]}))
+"""
+
+
+@pytest.mark.skipif(
+ not all(shutil.which(t) for t in ("git", "gpg", "jq")), reason="needs git, gpg and jq"
+)
+def test_signing_key_restricts_both_environments_to_main(tmp_path):
+ # In a checkout of its own: the tests also run from a source tarball.
+ repo = tmp_path / "repo"
+ (repo / "scripts").mkdir(parents=True)
+ shutil.copy2(ROOT / "scripts/signing-key.sh", repo / "scripts")
+ git(tmp_path, "init", "-q", str(repo))
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir()
+ (bin_dir / "gh").write_text(FAKE_GH)
+ (bin_dir / "gh").chmod(0o755)
+ log = tmp_path / "gh.log"
+ env = {**os.environ, "PATH": f"{bin_dir}:{os.environ['PATH']}", "GH_LOG": str(log)}
+ r = subprocess.run(
+ [str(repo / "scripts/signing-key.sh"), "--restrict"],
+ cwd=repo,
+ env=env,
+ capture_output=True,
+ text=True,
+ )
+ assert r.returncode == 0, r.stdout + r.stderr
+ calls = [json.loads(line) for line in log.read_text().splitlines()]
+ puts = {c["args"][-3].split("/")[-1]: c["input"] for c in calls if "PUT" in c["args"]}
+ branch_policy = {"protected_branches": False, "custom_branch_policies": True}
+ # The reviewers and wait timer of an existing environment stay.
+ assert puts["rpm-signing"] == {
+ "wait_timer": 5,
+ "prevent_self_review": True,
+ "reviewers": [{"type": "User", "id": 42}],
+ "deployment_branch_policy": branch_policy,
+ }
+ assert puts["github-pages"] == {"deployment_branch_policy": branch_policy}
+ # Every policy but main's goes, and main gets one.
+ changes = [c["args"][3:] for c in calls if "DELETE" in c["args"] or "POST" in c["args"]]
+ policies = "repos/dennisklein/nm-sshuttle/environments/{}/deployment-branch-policies"
+ assert changes == [
+ ["DELETE", policies.format("rpm-signing") + "/2"],
+ ["DELETE", policies.format("rpm-signing") + "/3"],
+ ["POST", policies.format("github-pages"), "-f", "name=main", "-f", "type=branch"],
+ ]
diff --git a/tests/test_profile.py b/tests/test_profile.py
index 7d7fc3b..0bd60fc 100644
--- a/tests/test_profile.py
+++ b/tests/test_profile.py
@@ -4,7 +4,8 @@
import pytest
from fakes import fake_getpwnam, settings
-from nm_sshuttle.profile import ProfileError, parse
+from nm_sshuttle.profile import (MAX_HOPS, ProfileError, collapse, listed, parse,
+ split_remote)
def p(s):
@@ -89,3 +90,89 @@ def test_persistent_and_ipv4_method_are_required():
def test_unknown_keys_are_reported_not_used():
assert p(settings(**{"ssh-options": "-oFoo"})).ignored_keys == ["ssh-options"]
+
+
+INCLUDE = 'fe80::%x};include"passwd";/64'
+
+
+@pytest.mark.parametrize("key,value", [
+ ("subnets", INCLUDE), ("subnets", "10.0.0.0/8 fe80::%eth0/64"), ("exclude", INCLUDE),
+ ("gateway", "fe80::1%x }\ninclude \"passwd\""), ("gateway", "fe80::1%eth0"),
+ ("probe", "[fe80::1%a b]:22"), ("dns-servers", "fe80::53%eth0")])
+def test_a_scope_id_is_refused(key, value):
+ # ipaddress keeps any text after "%" in str(), and that text would reach
+ # the root nft script and sshuttle's argv.
+ with pytest.raises(ProfileError, match=f"^{key}: .* has a scope id"):
+ p(settings(**{key: value}))
+
+
+def test_stored_networks_are_address_text_only():
+ prof = p(settings(subnets="10.1.2.3/8, 2001:DB8:10::1/48", exclude="2001:db8:10:5::7",
+ gateway="2001:DB8::7"))
+ assert prof.subnets == ["10.0.0.0/8", "2001:db8:10::/48"]
+ assert prof.exclude == ["2001:db8:10:5::7/128"]
+ assert prof.gateway == "2001:db8::7"
+
+
+def test_collapse_drops_a_scope_that_got_through():
+ # Even past validation, a network's text is rebuilt from its number.
+ assert collapse([INCLUDE, "fe80::1%eth0", "10.0.0.0/8"]) == [
+ "10.0.0.0/8", "fe80::/64"]
+ assert collapse(["fe80::%a b/10"]) == ["fe80::/10"]
+
+
+@pytest.mark.parametrize("key,value", [
+ ("remote", "corp:" + "1" * 4400), ("probe", "10.1.0.10:" + "1" * 4400),
+ ("probe", "10.1.0.10:\u00b2"), ("probe", "10.1.0.10:\u0661")],
+ ids=["remote-long", "probe-long", "probe-superscript", "probe-arabic-indic"])
+def test_a_port_beyond_int_or_ascii_is_a_profile_error(key, value):
+ # int() refuses over 4300 digits with a ValueError of its own, and
+ # str.isdigit() takes "²", which int() refuses, and "١", which it reads.
+ with pytest.raises(ProfileError, match=f"^{key}: "):
+ p(settings(**{key: value}))
+
+
+def test_a_port_may_have_leading_zeros():
+ assert p(settings(remote="corp:000022")).remote == "corp:000022"
+ assert p(settings(probe="10.1.0.10:000022")).probe == "10.1.0.10:22"
+
+
+@pytest.mark.parametrize("remote", ["alice:hunter2@corp", ":@", "a:b@c@corp"])
+def test_a_password_in_remote_is_refused_and_not_logged(remote):
+ with pytest.raises(ProfileError, match="^remote: the user part must not contain ':'") as e:
+ p(settings(remote=remote))
+ assert "hunter2" not in str(e.value) and remote not in str(e.value)
+
+
+def test_split_remote_splits_as_sshuttle_does():
+ assert split_remote("corp") == ("", "corp", None)
+ assert split_remote("alice@corp:022") == ("alice", "corp", 22)
+ assert split_remote("alice@[2001:db8::7]:2222") == ("alice", "2001:db8::7", 2222)
+ assert split_remote("2001:db8::7") == ("", "2001:db8::7", None)
+ with pytest.raises(ProfileError):
+ split_remote("corp:2222:1")
+
+
+def test_first_hop_addresses_inside_the_guarded_networks_are_refused():
+ # A lookup on the local network may be spoofed (design §4.2).
+ prof = p(settings(subnets="10.0.0.0/8, 2001:db8:10::/48", exclude="10.0.5.0/24",
+ **{"dns-servers": "192.168.5.5"}))
+ hops = ["203.0.113.7", "10.20.30.40", "192.168.5.5", "10.0.5.9", "2001:db8:10::7",
+ "2001:db8:ffff::7", "not-an-address"]
+ assert prof.first_hop_addresses(hops) == (
+ ["203.0.113.7", "10.0.5.9", "2001:db8:ffff::7"],
+ ["10.20.30.40", "192.168.5.5", "2001:db8:10::7"], [])
+ # given as an address, the first hop was never looked up: as 'gateway'
+ assert prof.first_hop_addresses(["10.20.30.40"], given=True) == (["10.20.30.40"], [], [])
+ # without DNS through the tunnel, its servers are not guarded
+ prof = p(settings(dns="none", **{"dns-servers": "192.168.5.5"}))
+ assert prof.first_hop_addresses(["192.168.5.5"]) == (["192.168.5.5"], [], [])
+
+
+def test_first_hop_addresses_are_capped():
+ hops = [f"198.51.100.{i}" for i in range(1, 12)]
+ usable, refused, dropped = p(settings()).first_hop_addresses(hops)
+ assert usable == hops[:MAX_HOPS] and dropped == hops[MAX_HOPS:] and refused == []
+ assert MAX_HOPS == 8
+ assert listed(hops) == ", ".join(hops[:MAX_HOPS]) + " and 3 more"
+ assert listed(hops[:2]) == "198.51.100.1, 198.51.100.2"
diff --git a/tests/test_service_dbus.py b/tests/test_service_dbus.py
index f8972c4..d0deb09 100644
--- a/tests/test_service_dbus.py
+++ b/tests/test_service_dbus.py
@@ -71,6 +71,9 @@
+
+
+
"""
LOGIN_XML = """
@@ -172,6 +175,7 @@ def __init__(self, address):
self.address = "192.168.1.20"
self.addresses6 = ["2001:db8:1::20", "fe80::20"]
self.locked = False
+ self.dns_mode = "systemd-resolved"
self.inhibit_fds = []
self.signals = []
self.jobs = 0
@@ -188,6 +192,8 @@ def __init__(self, address):
self.conn.register_object(PRIMARY_PATH, nm.interfaces[1], self.on_call, self.on_prop, None)
self.conn.register_object(IP4_PATH, nm.interfaces[3], self.on_call, self.on_prop, None)
self.conn.register_object(IP6_PATH, nm.interfaces[4], self.on_call, self.on_prop, None)
+ self.conn.register_object("/org/freedesktop/NetworkManager/DnsManager", nm.interfaces[5],
+ self.on_call, self.on_prop, None)
lg = Gio.DBusNodeInfo.new_for_xml(LOGIN_XML)
self.conn.register_object("/org/freedesktop/login1", lg.interfaces[0], self.on_call,
self.on_prop, None)
@@ -225,6 +231,7 @@ def on_prop(self, conn, sender, path, iface, prop):
"Gateway": GLib.Variant("s", "192.168.1.1"),
"Sessions": GLib.Variant("a(so)", [("2", SESSION_PATH)]),
"LockedHint": GLib.Variant("b", self.locked),
+ "Mode": GLib.Variant("s", self.dns_mode),
}
if iface == IP6_IFACE:
return {"AddressData": GLib.Variant("aa{sv}", [
@@ -344,11 +351,13 @@ def remove_link(name):
monkeypatch.setattr(guard, "remove_guard", lambda t: host["ops"].append("unguard"))
monkeypatch.setattr(tunnel, "sweep", lambda: None)
monkeypatch.setattr(tunnel, "nft_health",
- lambda method, table, ports=None: {"guard": True, "sshuttle": {4, 6}})
+ lambda method, table, ports: {"guard": True, "sshuttle": {4, 6}})
monkeypatch.setattr(tunnel, "unit_ports", lambda unit: None)
monkeypatch.setattr(service.Service, "take_claim", lambda self, claim: None)
monkeypatch.setattr(service.Service, "release_claim", lambda self: None)
+ monkeypatch.setattr(guard, "guard_listed", lambda table: True)
monkeypatch.setattr(tunnel, "ipv6_available", lambda: True)
+ monkeypatch.setattr(tunnel, "resolv_conf_problem", lambda: None)
monkeypatch.setattr(service.pwd, "getpwnam", fake_getpwnam)
monkeypatch.setattr(service.Service, "run_cleanup", lambda self, done: done())
monkeypatch.setattr(service.Service, "write_tunnel_spec", lambda self, spec: None)
@@ -586,3 +595,62 @@ def serve():
assert results["closed"] is False
banner.close()
silent.close()
+
+
+def test_only_networkmanager_may_call_the_plugin(world, bus):
+ fake, svc, host = world
+ other = connect(bus)
+ out = []
+ other.call("org.freedesktop.NetworkManager.sshuttle",
+ "/org/freedesktop/NetworkManager/VPN/Plugin",
+ "org.freedesktop.NetworkManager.VPN.Plugin", "Connect", settings_variant(), None,
+ Gio.DBusCallFlags.NONE, 2000, None, lambda c, res: out.append(res))
+ iterate_until(lambda: out)
+ with pytest.raises(GLib.Error, match="AccessDenied"):
+ other.call_finish(out[0])
+ assert svc.sup.phase == "idle" and fake.signals == []
+
+ # before the name watch has reported NM, the bus is asked
+ svc.sup.nm_current_owner = None
+ r = fake.call_plugin("NeedSecrets", GLib.Variant("(a{sa{sv}})", ({},)))
+ assert r.unpack() == ("",)
+
+
+def test_split_dns_needs_resolved_behind_networkmanager(world):
+ fake, svc, host = world
+ fake.dns_mode = "default" # NM writes /etc/resolv.conf itself
+ fake.call_plugin("Connect", settings_variant())
+ iterate_until(lambda: f"State{ST_STOPPED}" in fake.names())
+ assert fake.names() == [f"State{ST_STARTING}", "Failure", f"State{ST_STOPPED}"]
+ assert fake.signals[1][1] == FAIL_CONNECT and "create_link" not in host["ops"]
+
+
+def test_health_counts_no_listener_without_systemds_cgroups(monkeypatch):
+ seen = []
+ monkeypatch.setattr(tunnel, "unit_ports", lambda unit: None)
+ monkeypatch.setattr(tunnel, "unit_runs", lambda unit, comm: None)
+ monkeypatch.setattr(tunnel, "nft_health",
+ lambda method, table, ports: seen.append(ports) or
+ {"guard": True, "sshuttle": set()})
+ svc = service.Service(None, None, slot=2)
+ assert svc.nft_health("nft") == {"guard": True, "sshuttle": set(), "cgroup": False,
+ "ssh": None}
+ assert seen == [{}]
+ monkeypatch.setattr(tunnel, "unit_ports", lambda unit: {4: {229}, 6: set()})
+ assert svc.nft_health("nft")["cgroup"] is True and seen[1] == {4: {229}, 6: set()}
+
+
+def test_resolve_first_hop_reads_the_kind():
+ # first-hop --kind (design §4.2); a call without the kind is no answer.
+ calls = []
+ fake = type("S", (), {"_spawn": lambda self, argv, t, done: calls.append((argv, done))})()
+ got = []
+ service.Service.resolve_first_hop(fake, "alice", "corp", lambda *a: got.append(a))
+ argv, done = calls[0]
+ assert argv[1:] == ["first-hop", "--kind", "alice", "corp"]
+ done(True, "given\n10.0.0.5\n", "")
+ done(True, "lookup\n192.0.2.7\n2001:db8::7\n", "")
+ done(True, "192.0.2.7\n", "")
+ done(False, "", "first-hop: no address\n")
+ assert got == [(["10.0.0.5"], None, True), (["192.0.2.7", "2001:db8::7"], None, False),
+ (None, "no address"), (None, "first-hop: no address")]
diff --git a/tests/test_supervisor.py b/tests/test_supervisor.py
index 073caec..c945b7b 100644
--- a/tests/test_supervisor.py
+++ b/tests/test_supervisor.py
@@ -25,6 +25,12 @@ def up():
return fx, sup
+def retry_at(fx, sup):
+ """When the next reconnect attempt is due; the gap's guard check also has
+ a timer."""
+ return next(w for w, h, _ in fx.timers if h == sup.timers["retry"])
+
+
def gap(fx, sup):
sup.on_tunnel_inactive()
assert sup.phase == "gap"
@@ -89,6 +95,89 @@ def test_gateway_from_the_profile_skips_the_lookup():
assert fx.events[-1] == ("start_tunnel",)
+def test_first_hop_addresses_in_the_tunnelled_networks_are_left_out(caplog):
+ # A spoofed answer must not take internal addresses out of the guard (design §4.2).
+ fx, sup = make()
+ sup.connect(settings(exclude="10.0.5.0/24"), NM)
+ with caplog.at_level(logging.WARNING, logger="nm-sshuttle"):
+ fx.first_hop_cbs.pop(0)(["10.20.30.40", "203.0.113.7", "10.1.0.53", "10.0.5.9"], None)
+ guard = [e for e in fx.events if e[0] == "install_guard"][0]
+ assert guard[2] == ["203.0.113.7", "10.0.5.9", "10.0.5.0/24"]
+ assert [e[1] for e in fx.events if e[0] == "spec"][0]["first_hop"] == [
+ "203.0.113.7", "10.0.5.9"]
+ assert "ignoring the first hop's addresses 10.20.30.40, 10.1.0.53" in caplog.text
+
+
+def test_a_partly_refused_first_hop_pins_ssh_and_names_them_on_failure(caplog):
+ # ssh would look the name up itself and may take the refused address,
+ # which the guard rejects (design §4.2).
+ fx, sup = make()
+ sup.connect(settings(), NM)
+ fx.first_hop_cbs.pop(0)(["10.20.30.40", "2001:db8::7"], None)
+ spec = [e[1] for e in fx.events if e[0] == "spec"][0]
+ assert spec["first_hop"] == ["2001:db8::7"] and spec["pin"] is True
+ with caplog.at_level(logging.WARNING, logger="nm-sshuttle"):
+ fx.finish_start(False, "start job failed\nNetwork is unreachable")
+ assert ("failure", FAIL_CONNECT) in fx.events
+ assert ("Network is unreachable; the first hop's name also resolves to 10.20.30.40, "
+ "inside the profile's networks or DNS servers") in caplog.text
+
+
+def test_no_pin_and_no_hint_without_refused_addresses(caplog):
+ fx, sup = make()
+ sup.connect(settings(), NM)
+ fx.first_hop_cbs.pop(0)(["203.0.113.7"], None)
+ assert "pin" not in [e[1] for e in fx.events if e[0] == "spec"][0]
+ with caplog.at_level(logging.WARNING, logger="nm-sshuttle"):
+ fx.finish_start(False, "start job failed\nConnection timed out")
+ assert "also resolves" not in caplog.text
+
+
+def test_a_first_hop_only_in_the_tunnelled_networks_fails(caplog):
+ fx, sup = make()
+ sup.connect(settings(), NM)
+ with caplog.at_level(logging.WARNING, logger="nm-sshuttle"):
+ fx.first_hop_cbs.pop(0)(["10.20.30.40"], None)
+ assert ("failure", FAIL_CONNECT) in fx.events
+ assert "create_link" not in fx.names() and "install_guard" not in fx.names()
+ assert "resolves only into the profile's networks or DNS servers (10.20.30.40)" in caplog.text
+
+
+def test_a_first_hop_given_as_an_address_in_the_tunnelled_networks_is_taken():
+ # A HostName that is an address was never looked up (design §4.2).
+ fx, sup = make()
+ sup.connect(settings(), NM)
+ fx.first_hop_cbs.pop(0)(["10.20.30.40"], None, True)
+ assert [e for e in fx.events if e[0] == "install_guard"][0][2] == ["10.20.30.40"]
+ assert fx.events[-1] == ("start_tunnel",)
+
+
+def test_a_long_forged_answer_is_not_logged_in_full(caplog):
+ fx, sup = make()
+ sup.connect(settings(), NM)
+ with caplog.at_level(logging.WARNING, logger="nm-sshuttle"):
+ fx.first_hop_cbs.pop(0)([f"10.20.30.{i}" for i in range(1, 201)], None)
+ assert ("failure", FAIL_CONNECT) in fx.events
+ assert "10.20.30.8 and 192 more)" in caplog.text and "10.20.30.9," not in caplog.text
+
+
+def test_a_gateway_in_the_tunnelled_networks_is_taken():
+ fx, sup = make()
+ sup.connect(settings(gateway="10.20.30.40"), NM)
+ assert [e for e in fx.events if e[0] == "install_guard"][0][2] == ["10.20.30.40"]
+ assert fx.events[-1] == ("start_tunnel",)
+
+
+def test_at_most_eight_first_hop_addresses(caplog):
+ fx, sup = make()
+ sup.connect(settings(), NM)
+ hops = [f"198.51.100.{i}" for i in range(1, 21)]
+ with caplog.at_level(logging.WARNING, logger="nm-sshuttle"):
+ fx.first_hop_cbs.pop(0)(hops, None)
+ assert [e[1] for e in fx.events if e[0] == "spec"][0]["first_hop"] == hops[:8]
+ assert "more than 8 addresses; ignoring 198.51.100.9," in caplog.text
+
+
def test_config_waits_for_nm_device():
fx, sup = make()
fx.device_answer = None
@@ -283,7 +372,7 @@ def test_backoff_and_reconnect_timeout(up):
sup.on_tunnel_inactive()
delays = []
for _ in range(8):
- when = min(w for w, h, _ in fx.timers if h not in fx.cancelled)
+ when = retry_at(fx, sup)
delays.append(round(when - fx.t))
fx.advance(when - fx.t)
fx.finish_start(False, "start job failed\nConnection timed out")
@@ -663,10 +752,10 @@ def test_deadline_restarts_with_a_drop_during_reconfig(up):
sup.on_tunnel_inactive() # the tunnel dies in the middle of reconfig
assert sup.phase == "gap"
while fx.t < first_burst + 70: # attempts keep failing past the old deadline
- when = min(w for w, h, _ in fx.timers if h not in fx.cancelled)
+ when = retry_at(fx, sup)
fx.advance(when - fx.t)
fx.finish_start(False, "start job failed\nConnection timed out")
- when = min(w for w, h, _ in fx.timers if h not in fx.cancelled)
+ when = retry_at(fx, sup)
fx.advance(when - fx.t)
fx.finish_start(True)
assert sup.phase == "reconfig"
@@ -694,3 +783,38 @@ def test_touch_restarts_the_idle_timer():
assert not fx.quit_called
fx.advance(11)
assert fx.quit_called
+
+
+# ------------------------------------------------------------ DNS backend
+def test_split_dns_without_resolved_is_refused(caplog):
+ # without resolved, lookups fall back to the LAN's resolver in a gap
+ for mode in ("default", "dnsmasq", None):
+ fx, sup = make()
+ fx.dns_backend = mode
+ sup.connect(settings(), NM)
+ assert fx.names() == ["state", "failure", "state", "stop_tunnel"]
+ assert fx.signals() == [("state", ST_STARTING), ("failure", FAIL_CONNECT),
+ ("state", ST_STOPPED)]
+ assert sup.phase == "stopping"
+ assert "dns=split needs NetworkManager to use systemd-resolved, and its DNS mode is " \
+ "default" in caplog.text
+
+
+def test_split_dns_is_refused_when_resolv_conf_bypasses_resolved(caplog):
+ # NM reports systemd-resolved also with resolv.conf linked to resolved's
+ # list of the real servers: glibc asks them itself and falls back
+ fx, sup = make()
+ fx.resolv_conf = "/etc/resolv.conf lists 10.1.0.53, 192.168.1.1, not only resolved's stub"
+ sup.connect(settings(), NM)
+ assert fx.signals() == [("state", ST_STARTING), ("failure", FAIL_CONNECT),
+ ("state", ST_STOPPED)]
+ assert "dns=split needs every lookup to go to systemd-resolved, and /etc/resolv.conf " \
+ "lists 10.1.0.53" in caplog.text
+
+
+def test_dns_none_does_not_ask_for_the_dns_backend():
+ fx, sup = make()
+ fx.dns_backend = "default"
+ fx.resolv_conf = "/etc/resolv.conf lists 192.168.1.1"
+ bring_up(fx, sup, dns="none", **{"dns-servers": "", "dns-domains": ""})
+ assert sup.phase == "up"
diff --git a/tests/test_tproxy.py b/tests/test_tproxy.py
index 04e407f..1e232b7 100644
--- a/tests/test_tproxy.py
+++ b/tests/test_tproxy.py
@@ -105,7 +105,7 @@ def test_mangle_chains_are_parsed():
def test_the_sweep_removes_the_chains_of_a_port_without_listener():
- cmds = tunnel.stale_chain_commands(MANGLE, ports={12301})
+ cmds = tunnel.stale_chain_commands(MANGLE, ports={12301}) # this family's
assert cmds == [["-D", "PREROUTING", "-j", "sshuttle-t-12300"],
["-D", "OUTPUT", "-j", "sshuttle-m-12300"],
["-F", "sshuttle-d-12300"], ["-F", "sshuttle-m-12300"],
@@ -119,10 +119,10 @@ def test_health_reads_the_mark_chain_for_tproxy(monkeypatch):
monkeypatch.setattr(tunnel.subprocess, "run", lambda argv, **kw: SimpleNamespace(
returncode=0, stdout=MANGLE if argv[0].endswith("tables") else
"table inet g\ntable inet sshuttle-ipv4-12300\n"))
- monkeypatch.setattr(tunnel, "listening_ports", lambda: {12300})
- assert tunnel.nft_health("tproxy", "g") == {"guard": True, "sshuttle": {4, 6}}
- monkeypatch.setattr(tunnel, "listening_ports", lambda: {12399})
- assert tunnel.nft_health("tproxy", "g")["sshuttle"] == set()
+ assert tunnel.nft_health("tproxy", "g", {4: {12300}, 6: {12300}}) == \
+ {"guard": True, "sshuttle": {4, 6}}
+ assert tunnel.nft_health("tproxy", "g", {4: {12300}, 6: set()})["sshuttle"] == {4}
+ assert tunnel.nft_health("tproxy", "g", {4: {12399}, 6: set()})["sshuttle"] == set()
# -------------------------------------------------------------- supervisor
diff --git a/tests/test_tunnel.py b/tests/test_tunnel.py
index 577da78..0dfbabc 100644
--- a/tests/test_tunnel.py
+++ b/tests/test_tunnel.py
@@ -1,10 +1,17 @@
# SPDX-License-Identifier: MIT
+import json
+import os
+import shlex
import socket
import subprocess
+import sys
import time
from types import SimpleNamespace
-from nm_sshuttle import tunnel
+import pytest
+
+from nm_sshuttle import const, profile, tunnel
+from nm_sshuttle.const import LISTEN_PORTS, SLOTS, Slot
SPEC = {"remote": "corp", "user": "alice", "subnets": ["10.0.0.0/8"], "exclude": ["10.0.5.0/24"],
"dns": "split", "dns_servers": ["10.1.0.53", "10.1.0.54"], "method": "nft",
@@ -14,9 +21,9 @@
def test_sshuttle_argv():
argv = tunnel.sshuttle_argv(SPEC, "/usr/bin/sshuttle")
assert argv[:5] == ["/usr/bin/sshuttle", "-v", "--method", "nft", "--disable-ipv6"]
- assert argv[argv.index("-r") + 1] == "corp"
+ assert argv[argv.index("-r") + 1] == "127.0.0.1" # the stand-in: never looked up
assert ["-x", "203.0.113.7", "-x", "10.0.5.0/24"] == argv[7:11]
- assert argv[argv.index("-e") + 1].endswith("/nm-sshuttle ssh-as-user alice")
+ assert argv[argv.index("-e") + 1].endswith("/nm-sshuttle ssh-as-user alice --remote corp")
assert argv[argv.index("--to-ns") + 1] == "10.1.0.53"
assert argv[argv.index("--ns-hosts") + 1] == "10.1.0.53,10.1.0.54"
assert argv[-1] == "10.0.0.0/8" # the DNS /32s lie inside it and are merged
@@ -94,16 +101,16 @@ def test_first_hop_follows_a_jump_alias_from_the_users_config():
def ssh_g(user, target):
asked.append((user, target))
return config[target]
- assert tunnel.first_hop("alice", "corp", ssh_g=ssh_g) == ["127.0.0.2"]
+ assert tunnel.first_hop("alice", "corp", ssh_g=ssh_g) == (["127.0.0.2"], True)
assert asked == [("alice", "corp"), ("alice", "bastion")]
def test_first_hop_direct_and_nested_jumps():
assert tunnel.first_hop("a", "h", ssh_g=lambda u, t: "hostname 127.0.0.3\nproxyjump none\n") \
- == ["127.0.0.3"]
+ == (["127.0.0.3"], True)
chain = {"a": "hostname x\nproxyjump b\n", "b": "hostname y\nproxyjump c\n",
"c": "hostname 127.0.0.4\nproxyjump none\n"}
- assert tunnel.first_hop("u", "a", ssh_g=lambda u, t: chain[t]) == ["127.0.0.4"]
+ assert tunnel.first_hop("u", "a", ssh_g=lambda u, t: chain[t]) == (["127.0.0.4"], True)
def test_first_hop_returns_every_address_of_either_family():
@@ -116,11 +123,19 @@ def getaddrinfo(host, port, family, kind):
def ssh_g(u, t):
return "hostname gw.example\nproxyjump none\n"
- assert tunnel.first_hop("u", "h", ssh_g, gai(["198.51.100.1"])) == ["198.51.100.1"]
- assert tunnel.first_hop("u", "h", ssh_g, gai(["2001:db8::1"])) == ["2001:db8::1"]
+ assert tunnel.first_hop("u", "h", ssh_g, gai(["198.51.100.1"])) == (["198.51.100.1"], False)
+ assert tunnel.first_hop("u", "h", ssh_g, gai(["2001:db8::1"])) == (["2001:db8::1"], False)
assert tunnel.first_hop("u", "h", ssh_g, gai(["2001:db8::1", "198.51.100.1",
- "2001:db8::1", "fe80::1%eth0"])) == [
- "2001:db8::1", "198.51.100.1", "fe80::1"]
+ "2001:db8::1", "fe80::1%eth0"])) == ([
+ "2001:db8::1", "198.51.100.1", "fe80::1"], False)
+
+
+def test_a_first_hop_given_as_an_address_is_marked():
+ # Only a name is looked up, and only a lookup can be spoofed (design §4.2).
+ for hostname, addr in (("203.0.113.7", "203.0.113.7"), ("2001:db8::7", "2001:db8::7"),
+ ("fe80::7%eth0", "fe80::7")):
+ out = f"hostname {hostname}\nproxyjump none\n"
+ assert tunnel.first_hop("u", "h", lambda u, t, out=out: out) == ([addr], True)
def test_first_hop_gives_up_on_a_loop_and_on_option_like_hosts():
@@ -160,6 +175,18 @@ def ssh_g_fails(u, t):
assert pinned(config={"corp": "hostname a%h\nproxyjump none\n"}) is None
+def test_a_first_hop_that_also_resolved_into_the_tunnel_is_pinned_anyway():
+ # The guard rejects the refused addresses, so ssh must not follow its own
+ # lookup (design §4.2); dns does not matter, and nothing is looked up.
+ looked_up = []
+ text = pinned(dict(SPEC, dns="none", pin=True), resolves=lambda name: looked_up.append(name))
+ assert looked_up == []
+ assert "also resolved into the tunnelled" in text
+ assert "Host bastion\n HostName 203.0.113.7\n HostKeyAlias bastion.corp.example\n" in text
+ assert pinned(dict(SPEC, pin=True, first_hop=[]), resolves=lambda name: True) is None
+ assert pinned(dict(SPEC, pin=True), config={"corp": "hostname 192.0.2.9\n"}) is None
+
+
def test_a_pin_prefers_an_ipv4_address():
text = pinned(dict(SPEC, first_hop=["2001:db8::7", "203.0.113.7"]))
assert " HostName 203.0.113.7\n" in text
@@ -177,7 +204,150 @@ def test_the_pinned_config_goes_to_ssh(tmp_path):
assert open(path).read() == "Host x\n"
assert (tmp_path / "ssh" / "ssh_config").stat().st_mode & 0o777 == 0o644
argv = tunnel.sshuttle_argv(SPEC, "sshuttle", path)
- assert argv[argv.index("-e") + 1].endswith(f"/nm-sshuttle ssh-as-user alice -F {path}")
+ assert argv[argv.index("-e") + 1].endswith(
+ f"/nm-sshuttle ssh-as-user alice --remote corp -F {path}")
+
+
+def sshuttle_runs(argv):
+ """What sshuttle 1.3.1 and 2.0.0 run for -e and the stand-in -r, which has
+ no user and no port (their ssh.connect)."""
+ return shlex.split(argv[argv.index("-e") + 1]) + [argv[argv.index("-r") + 1], "--",
+ "/bin/sh -c 'exec python3'"]
+
+
+# ssh's arguments as sshuttle 1.3.1 and 2.0.0 split these remotes (parse_hostport):
+# the same user, host and port. The host goes on as written, as `check` gives it to
+# ssh; sshuttle wrote an IPv6 address in short form and, with a port, in lower case.
+@pytest.mark.parametrize("remote,ssh", [
+ ("Corp:2222", ["-p", "2222", "Corp"]),
+ ("2001:DB8:0::7", ["2001:DB8:0::7"]),
+ ("corp", ["corp"]),
+ ("alice@corp", ["alice@corp"]),
+ ("corp:2222", ["-p", "2222", "corp"]),
+ ("alice@gw.corp.example:022", ["-p", "22", "alice@gw.corp.example"]),
+ ("2001:db8::7", ["2001:db8::7"]),
+ ("alice@[2001:db8::7]:2222", ["-p", "2222", "alice@2001:db8::7"]),
+ ("alice@[2001:db8::7]", ["alice@2001:db8::7"]),
+ ("fe80::7%eth0", ["fe80::7%eth0"]),
+])
+def test_the_bridge_gives_ssh_the_remote_split_as_sshuttle_splits_it(remote, ssh):
+ for config in (None, "/run/nm-sshuttle-ssh/ssh_config-0"):
+ argv = tunnel.sshuttle_argv(dict(SPEC, remote=remote), "sshuttle", config)
+ bridge = sshuttle_runs(argv)
+ assert bridge[1:4] == ["ssh-as-user", "alice", "--remote"] and bridge[4] == remote
+ assert tunnel.bridged_args(bridge[4], bridge[5:]) == (
+ (["-F", config] if config else []) + ssh + ["--", "/bin/sh -c 'exec python3'"])
+
+
+@pytest.mark.parametrize("args", [
+ ["127.0.0.1"],
+ ["-G", "127.0.0.1"], # a patched sshuttle's lookup (upstream §3)
+ ["-p", "22", "127.0.0.1", "--", "x"],
+ ["alice@127.0.0.1", "--", "x"],
+ ["corp", "--", "x"],
+ ["127.0.0.1", "x", "y"],
+ ["127.0.0.1", "--", "x", "y"],
+ ["-F", "/c", "-o", "ProxyCommand=x", "127.0.0.1", "--", "x"],
+])
+def test_the_bridge_refuses_other_arguments(args):
+ with pytest.raises(ValueError, match="unexpected arguments"):
+ tunnel.bridged_args("corp", args)
+
+
+def test_the_bridge_checks_the_remote_again():
+ with pytest.raises(profile.ProfileError):
+ tunnel.bridged_args("-oProxyCommand=x", ["127.0.0.1", "--", "x"])
+
+
+def test_ssh_as_user_execs_ssh_with_the_remote(monkeypatch):
+ pw = SimpleNamespace(pw_uid=1000, pw_gid=1000, pw_dir="/home/alice")
+ monkeypatch.setattr(tunnel.pwd, "getpwnam", lambda n: pw)
+ monkeypatch.setattr(tunnel, "user_environment", lambda u, p: {"SSH_AUTH_SOCK": "/a"})
+ monkeypatch.setattr(tunnel, "reset_oom_score_adj", lambda: None)
+ ran = []
+ monkeypatch.setattr(tunnel.os, "execvp", lambda f, argv: ran.append(argv))
+ tunnel.ssh_as_user("alice", ["--remote", "corp:2222", "127.0.0.1", "--", "cmd"])
+ assert ran[0][-5:] == ["-p", "2222", "corp", "--", "cmd"]
+ assert ran[0][ran[0].index("ssh") + 1:][:len(tunnel.SSH_OPTIONS)] == tunnel.SSH_OPTIONS
+ tunnel.ssh_as_user("alice", ["-G", "--", "corp"]) # ssh_g: passed on as before
+ assert ran[1][-3:] == ["-G", "--", "corp"]
+ with pytest.raises(ValueError):
+ tunnel.ssh_as_user("alice", ["--remote", "corp", "corp", "--", "cmd"])
+ assert len(ran) == 2
+
+
+def test_ssh_as_user_resets_the_oom_score_before_anything_runs_as_the_user(monkeypatch):
+ # The plugin unit's OOMScoreAdjust=-500 must not reach ssh -G's Match exec
+ # or the tunnel's ssh (design §4.7).
+ pw = SimpleNamespace(pw_uid=1000, pw_gid=1000, pw_dir="/home/alice")
+ monkeypatch.setattr(tunnel.pwd, "getpwnam", lambda n: pw)
+ order = []
+ monkeypatch.setattr(tunnel, "reset_oom_score_adj", lambda: order.append("oom"))
+ monkeypatch.setattr(tunnel, "user_environment", lambda u, p: order.append("env") or {})
+ monkeypatch.setattr(tunnel.os, "execvp", lambda f, argv: order.append(argv[0]))
+ tunnel.ssh_as_user("alice", ["-G", "--", "corp"])
+ assert order == ["oom", "env", "setpriv"]
+ order.clear()
+ with pytest.raises(ValueError): # refused arguments: nothing runs at all
+ tunnel.ssh_as_user("alice", ["--remote", "corp", "corp", "--", "cmd"])
+ assert order == []
+
+
+def test_reset_oom_score_adj(tmp_path, capsys):
+ adj = tmp_path / "oom_score_adj"
+ adj.write_text("-500\n")
+ tunnel.reset_oom_score_adj(str(adj))
+ assert adj.read_text() == "0"
+ tunnel.reset_oom_score_adj(str(tmp_path / "missing" / "oom_score_adj")) # warns only
+ assert "cannot reset the OOM score adjustment" in capsys.readouterr().err
+
+
+OOM_FLOOR_CHECK = """
+import ctypes, os, sys
+from nm_sshuttle import tunnel
+
+def write(value):
+ try:
+ with open(tunnel.OOM_SCORE_ADJ, "w") as f:
+ f.write(value)
+ except PermissionError:
+ return False
+ return True
+
+if not write("-500"):
+ print("no CAP_SYS_RESOURCE")
+else:
+ if sys.argv[1] == "reset":
+ tunnel.reset_oom_score_adj()
+ os.setgroups([])
+ os.setresgid(65534, 65534, 65534)
+ os.setresuid(65534, 65534, 65534)
+ # The uid change made the process non-dumpable, which gives /proc/self to
+ # root; exec would undo that, as for ssh. PR_SET_DUMPABLE is 4.
+ ctypes.CDLL(None, use_errno=True).prctl(4, 1, 0, 0, 0)
+ with open(tunnel.OOM_SCORE_ADJ) as f:
+ now = f.read().strip()
+ print(now, "writable" if write(now) else "not writable",
+ "allowed" if write("-500") else "refused")
+"""
+
+
+@pytest.mark.skipif(os.geteuid() != 0 or not os.path.exists(tunnel.OOM_SCORE_ADJ),
+ reason="needs root and /proc")
+def test_reset_oom_score_adj_also_resets_the_floor():
+ # As systemd does for OOMScoreAdjust=-500: root writes it, which also sets
+ # the floor that an unprivileged process may go back down to.
+ root = os.path.dirname(os.path.dirname(os.path.abspath(tunnel.__file__)))
+
+ def check(mode):
+ p = subprocess.run([sys.executable, "-c", OOM_FLOOR_CHECK, mode], capture_output=True,
+ text=True, cwd=root, timeout=30)
+ assert p.returncode == 0, p.stderr
+ if p.stdout.strip() == "no CAP_SYS_RESOURCE":
+ pytest.skip(p.stdout.strip())
+ return p.stdout.strip()
+ assert check("keep") == "-500 writable allowed" # the floor without the reset
+ assert check("reset") == "0 writable refused"
def test_resolves():
@@ -201,32 +371,328 @@ def test_classify_failure():
assert tunnel.classify_failure("ssh: connect to host corp port 22: timed out") == "connect"
-def test_stale_tables(tmp_path):
- tcp = tmp_path / "tcp"
- tcp.write_text(
- " sl local_address rem_address st\n"
- " 0: 0100007F:3011 00000000:0000 0A 00000000:00000000\n" # 12305 listening
- " 1: 0100007F:300C 0100007F:9999 01 00000000:00000000\n") # 12300 established
- ports = tunnel.listening_ports((str(tcp), str(tmp_path / "missing")))
- assert ports == {12305}
+def test_port_failure_names_the_port_sshuttle_found_none_for():
+ in_use = "OSError: [Errno 98] Address already in use\n"
+ tcp = "c : TCP redirector listening on ('127.0.0.1', 225).\n"
+ none_free = "exec-tunnel: no free redirect port among 225-240; trying 225\n"
+ assert tunnel.port_failure("ssh: connect to host corp port 22: timed out", True) is None
+ assert "DNS redirector" in tunnel.port_failure(tcp + in_use, False)
+ assert "IPv6 redirector" in tunnel.port_failure(in_use, True)
+ assert "redirect port (225-240) was taken" in tunnel.port_failure(in_use, False)
+ assert "redirect port (225-240) was taken" in tunnel.port_failure(none_free + in_use, True)
+
+
+HEAD = (" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid "
+ "timeout inode\n")
+
+
+def tcp_line(local, state="0A", uid=0, inode=1):
+ return (f" 0: {local} 00000000:0000 {state} 00000000:00000000 00:00000000 00000000 "
+ f"{uid} 0 {inode}\n")
+
+
+def fake_net(tmp_path, tcp, tcp6=""):
+ (tmp_path / "net").mkdir()
+ (tmp_path / "net" / "tcp").write_text(HEAD + tcp)
+ (tmp_path / "net" / "tcp6").write_text(HEAD + tcp6)
+ return str(tmp_path)
+
+
+def test_listening_ports_are_roots_on_the_address_sshuttle_listens_on(tmp_path):
+ lo6 = tunnel.socket.inet_pton(socket.AF_INET6, "::1")
+ hex6 = "".join(f"{tunnel.struct.unpack('=I', lo6[i:i + 4])[0]:08X}" for i in range(0, 16, 4))
+ proc = fake_net(tmp_path,
+ tcp_line("0100007F:3011") # 127.0.0.1:12305, root
+ + tcp_line("0100007F:300C", state="01") # established
+ + tcp_line("0100007F:3012", uid=1000) # another user's
+ + tcp_line("0200007F:3013") # 127.0.0.2
+ + tcp_line("00000000:3014"), # 0.0.0.0, an admin's --listen
+ tcp_line(f"{hex6}:300C") # [::1]:12300
+ + tcp_line(f"{hex6}:3015", uid=1000))
+ assert tunnel.listening_ports(proc) == {4: {12305, 12308}, 6: {12300}}
+ assert tunnel.listening_ports(str(tmp_path / "missing")) == {4: set(), 6: set()}
+
+
+def test_stale_tables():
+ ports = {4: {12305}, 6: {12300}}
tables = ("table inet sshuttle-ipv4-12305\ntable inet sshuttle-ipv4-12300\n"
- "table inet nm-sshuttle-guard-0\ntable ip nat\ntable inet sshuttle-ipv6-12299\n")
- assert tunnel.stale_tables(tables, ports) == ["sshuttle-ipv4-12300", "sshuttle-ipv6-12299"]
- assert tunnel.sshuttle_tables(tables, ports, live=True) == ["sshuttle-ipv4-12305"]
+ "table inet nm-sshuttle-guard-0\ntable ip nat\ntable inet sshuttle-ipv6-12299\n"
+ "table inet sshuttle-ipv6-12300\ntable inet sshuttle-ipv6-12305\n")
+ assert tunnel.stale_tables(tables, ports) == ["sshuttle-ipv4-12300", "sshuttle-ipv6-12299",
+ "sshuttle-ipv6-12305"]
+ assert tunnel.sshuttle_tables(tables, ports, live=True) == ["sshuttle-ipv4-12305",
+ "sshuttle-ipv6-12300"]
+
+
+def run_sweep(monkeypatch, proc, tables):
+ ran = []
+
+ def run(argv, **kw):
+ ran.append(argv)
+ return subprocess.CompletedProcess(argv, 0, tables if argv[1] == "list" else "", "")
+ monkeypatch.setattr(tunnel.subprocess, "run", run)
+ monkeypatch.setattr(tunnel.shutil, "which", lambda *a, **k: None)
+ tunnel.sweep(proc)
+ return ran[1:]
+
+
+def test_the_sweep_ignores_another_users_listener(tmp_path, monkeypatch, caplog):
+ # a user listening on a leftover table's port must not keep the table
+ caplog.set_level("INFO", "nm-sshuttle")
+ proc = fake_net(tmp_path, tcp_line("0100007F:3011") + tcp_line("0100007F:300C", uid=1000)
+ + tcp_line("0200007F:3012"))
+ ran = run_sweep(monkeypatch, proc, "table inet sshuttle-ipv4-12305\n"
+ "table inet sshuttle-ipv4-12300\ntable inet sshuttle-ipv4-12306\n")
+ assert ran == [["nft", "delete", "table", "inet", "sshuttle-ipv4-12300"],
+ ["nft", "delete", "table", "inet", "sshuttle-ipv4-12306"]]
+ assert "deleted table sshuttle-ipv4-12300 although uid 1000 listens on its port" in \
+ caplog.text
+ assert "deleted stale table sshuttle-ipv4-12306" in caplog.text
+
+
+def fake_process(proc, pid, ppid, cmdline, uids=(0, 0, 0, 0), sockets=()):
+ d = proc / str(pid)
+ (d / "fd").mkdir(parents=True)
+ (d / "stat").write_text(f"{pid} (x) S {ppid} " + "0 " * 40 + "\n")
+ (d / "cmdline").write_bytes(b"\0".join(cmdline) + b"\0")
+ (d / "status").write_text("Uid:\t" + "\t".join(map(str, uids)) + "\n")
+ for n, inode in enumerate(sockets):
+ os.symlink(f"socket:[{inode}]", d / "fd" / str(n + 3))
+
+
+def test_the_sweep_spares_an_sshuttle_a_user_runs(tmp_path, monkeypatch):
+ # the client listens as the user; its firewall helper runs as root via sudo
+ proc = fake_net(tmp_path, tcp_line("0100007F:300C", uid=1000, inode=50)
+ + tcp_line("0100007F:3011", uid=1001, inode=60)
+ + tcp_line("0100007F:3012", uid=1002, inode=70))
+ root = tmp_path
+ user = (1000,) * 4
+ fake_process(root, 100, 1, [b"/usr/bin/python3", b"/usr/bin/sshuttle", b"-r", b"h", b"0/0"],
+ user, [50])
+ fake_process(root, 101, 100, [b"sudo", b"-p", b"x", b"/usr/bin/sshuttle", b"--firewall"])
+ fake_process(root, 102, 101, [b"/usr/bin/python3", b"/usr/bin/sshuttle", b"-v",
+ b"--method", b"nft", b"--firewall"])
+ # 1001 has sudo wait for a password below its listener: euid 0, real ID 1001
+ fake_process(root, 200, 1, [b"camp"], (1001,) * 4, [60])
+ fake_process(root, 201, 200, [b"sudo", b"-S", b"/usr/bin/sshuttle", b"--firewall"],
+ (1001, 0, 0, 0))
+ # 1002's listener has no helper below it, though root runs one elsewhere
+ fake_process(root, 300, 1, [b"camp"], (1002,) * 4, [70])
+ fake_process(root, 400, 1, [b"/usr/bin/python3", b"/usr/bin/sshuttle", b"--firewall"])
+ ran = run_sweep(monkeypatch, proc, "table inet sshuttle-ipv4-12300\n"
+ "table inet sshuttle-ipv4-12305\ntable inet sshuttle-ipv4-12306\n")
+ assert ran == [["nft", "delete", "table", "inet", "sshuttle-ipv4-12305"],
+ ["nft", "delete", "table", "inet", "sshuttle-ipv4-12306"]]
+ assert tunnel.user_sshuttle_ports(
+ [(4, 12300, 1000, "50"), (4, 12305, 1001, "60")], proc) == {4: {12300}, 6: set()}
+
+
+# -------------------------------------------------------------- /etc/hosts
+def sshuttle_hosts_line(ip, name, port):
+ """A line as sshuttle's firewall helper writes it (rewrite_etc_hosts)."""
+ return "%-30s %s\n" % (f"{ip} {name}", f"# sshuttle-firewall-{port} AUTOCREATED")
+
+
+def fake_hosts(tmp_path, text, mode=0o644):
+ (tmp_path / "etc").mkdir()
+ hosts = tmp_path / "etc" / "hosts"
+ hosts.write_text(text)
+ hosts.chmod(mode)
+ return hosts
+
+
+def test_strip_etc_hosts_removes_what_a_stopped_sshuttle_left(tmp_path, caplog):
+ caplog.set_level("INFO", "nm-sshuttle")
+ # root listens on 226, so that sshuttle still runs; 1000 on 12300, without
+ # sshuttle's helper below it, which does not count (design §4.8)
+ proc = fake_net(tmp_path, tcp_line("0100007F:00E2") + tcp_line("0100007F:300C", uid=1000))
+ localhost = "127.0.0.1 localhost\n"
+ not_sshuttles = ("# 203.0.113.6 x # sshuttle-firewall-225 AUTOCREATED\n"
+ "192.0.2.1 by-hand # sshuttle-firewall-225 AUTOCREATED, kept\n")
+ live = sshuttle_hosts_line("10.0.0.1", "kept.example", 226)
+ hosts = fake_hosts(tmp_path, localhost + sshuttle_hosts_line("203.0.113.6", "pypi.org", 225)
+ + not_sshuttles + live
+ + sshuttle_hosts_line("203.0.113.7", "git.corp.example", 12300), 0o640)
+ assert tunnel.strip_etc_hosts(str(hosts), proc)
+ assert hosts.read_text() == localhost + not_sshuttles + live
+ assert oct(hosts.stat().st_mode & 0o7777) == oct(0o640)
+ assert os.listdir(hosts.parent) == ["hosts"] # no temporary file left
+ assert "removed from %s what sshuttle left there: 203.0.113.6 pypi.org" % hosts in caplog.text
+ assert "203.0.113.7 git.corp.example" in caplog.text
+
+
+def test_strip_etc_hosts_keeps_the_lines_of_an_sshuttle_a_user_runs(tmp_path):
+ proc = fake_net(tmp_path, tcp_line("0100007F:300C", uid=1000, inode=50))
+ fake_process(tmp_path, 100, 1, [b"/usr/bin/sshuttle", b"-r", b"h", b"0/0"], (1000,) * 4,
+ [50])
+ fake_process(tmp_path, 101, 100, [b"sudo", b"/usr/bin/sshuttle", b"--firewall"])
+ assert tunnel.live_sshuttle_ports({12300, 225}, proc) == {12300}
+ text = sshuttle_hosts_line("10.0.0.1", "auto.example", 12300)
+ hosts = fake_hosts(tmp_path, text)
+ inode = hosts.stat().st_ino
+ assert tunnel.strip_etc_hosts(str(hosts), proc)
+ assert hosts.read_text() == text and hosts.stat().st_ino == inode # not rewritten
+
+
+def test_strip_etc_hosts_follows_no_symlink(tmp_path):
+ proc = fake_net(tmp_path, "")
+ text = sshuttle_hosts_line("203.0.113.6", "pypi.org", 225)
+ (tmp_path / "real").write_text(text)
+ (tmp_path / "etc").mkdir()
+ (tmp_path / "etc" / "hosts").symlink_to(tmp_path / "real")
+ assert tunnel.strip_etc_hosts(str(tmp_path / "etc" / "hosts"), proc)
+ assert (tmp_path / "etc" / "hosts").is_symlink() and (tmp_path / "real").read_text() == text
+ assert tunnel.strip_etc_hosts(str(tmp_path / "etc" / "missing"), proc)
+
+
+def test_strip_etc_hosts_keeps_the_selinux_label(tmp_path, monkeypatch):
+ proc = fake_net(tmp_path, "")
+ text = sshuttle_hosts_line("203.0.113.6", "pypi.org", 225)
+ hosts = fake_hosts(tmp_path, text)
+ label = b"system_u:object_r:net_conf_t:s0\0"
+ labelled = []
+ monkeypatch.setattr(tunnel.os, "getxattr", lambda fd, name: label)
+ monkeypatch.setattr(tunnel.os, "setxattr",
+ lambda fd, name, value: labelled.append((name, value)))
+ assert tunnel.strip_etc_hosts(str(hosts), proc)
+ assert labelled == [("security.selinux", label)] and hosts.read_text() == ""
+
+ def refused(fd, name, value):
+ raise PermissionError(13, "Permission denied")
+ hosts.write_text(text)
+ monkeypatch.setattr(tunnel.os, "setxattr", refused)
+ assert not tunnel.strip_etc_hosts(str(hosts), proc) # never with another label
+ assert hosts.read_text() == text and os.listdir(hosts.parent) == ["hosts"]
+
+
+def test_strip_etc_hosts_leaves_a_file_that_changed_meanwhile(tmp_path, monkeypatch, caplog):
+ proc = fake_net(tmp_path, "")
+ hosts = fake_hosts(tmp_path, sshuttle_hosts_line("203.0.113.6", "pypi.org", 225))
+ mkstemp = tunnel.tempfile.mkstemp
+
+ def racing(**kw):
+ with open(hosts, "a") as f:
+ f.write("192.0.2.9 new\n")
+ return mkstemp(**kw)
+ monkeypatch.setattr(tunnel.tempfile, "mkstemp", racing)
+ assert not tunnel.strip_etc_hosts(str(hosts), proc)
+ assert hosts.read_text().endswith("192.0.2.9 new\n") and "pypi.org" in hosts.read_text()
+ assert os.listdir(hosts.parent) == ["hosts"]
+ assert "it changed meanwhile" in caplog.text
def test_nft_health(monkeypatch):
out = "table inet sshuttle-ipv4-12305\ntable inet nm-sshuttle-guard-0\n"
monkeypatch.setattr(tunnel.subprocess, "run",
lambda *a, **k: subprocess.CompletedProcess(a, 0, out, ""))
- monkeypatch.setattr(tunnel, "listening_ports", lambda: {12305})
- assert tunnel.nft_health("nft", "nm-sshuttle-guard-0") == {"guard": True, "sshuttle": {4}}
- monkeypatch.setattr(tunnel, "listening_ports", lambda: set())
- assert tunnel.nft_health("nft", "nm-sshuttle-guard-0") == {"guard": True, "sshuttle": set()}
- out = ("table inet sshuttle-ipv4-12305\ntable inet sshuttle-ipv6-12305\n"
- "table inet sshuttle-ipv6-12300\n")
- monkeypatch.setattr(tunnel, "listening_ports", lambda: {12305})
- assert tunnel.nft_health("nft", "nm-sshuttle-guard-0") == {"guard": False, "sshuttle": {4, 6}}
+ assert tunnel.nft_health("nft", "nm-sshuttle-guard-0", {4: {12305}, 6: set()}) == \
+ {"guard": True, "sshuttle": {4}}
+ assert tunnel.nft_health("nft", "nm-sshuttle-guard-0", {4: set(), 6: set()}) == \
+ {"guard": True, "sshuttle": set()}
+ # the unit's cgroup was not found: no listener counts
+ assert tunnel.nft_health("nft", "nm-sshuttle-guard-0", {}) == \
+ {"guard": True, "sshuttle": set()}
+ out = ("table inet sshuttle-ipv4-225\ntable inet sshuttle-ipv6-12300\n"
+ "table inet sshuttle-ipv6-12299\n")
+ assert tunnel.nft_health("nft", "nm-sshuttle-guard-0", {4: {225}, 6: {12300}}) == \
+ {"guard": False, "sshuttle": {4, 6}}
+ assert tunnel.nft_health("nft", "g", {4: {12300}, 6: {225}}) == {"guard": False,
+ "sshuttle": set()}
monkeypatch.setattr(tunnel.subprocess, "run",
lambda *a, **k: subprocess.CompletedProcess(a, 1, "", "denied"))
- assert tunnel.nft_health("nft", "nm-sshuttle-guard-0") is None
+ assert tunnel.nft_health("nft", "nm-sshuttle-guard-0", {4: {12305}}) is None
+
+
+# -------------------------------------------------------------- redirect port
+def test_each_slot_tries_its_own_privileged_ports_first():
+ assert Slot(0).listen_ports[:2] == [225, 226] and Slot(7).listen_ports[:2] == [239, 240]
+ own = [p for n in range(SLOTS) for p in Slot(n).listen_ports[:2]]
+ assert sorted(own) == list(LISTEN_PORTS) and max(own) < 1024
+ # then the others, from those of the slots used least
+ assert Slot(0).listen_ports[2:4] == [240, 239] and Slot(7).listen_ports[2] == 238
+ assert all(sorted(Slot(n).listen_ports) == list(LISTEN_PORTS) for n in range(SLOTS))
+
+
+def test_quick_restarts_take_another_slots_port():
+ # two stops of slot 0 within a minute left both its own ports in TIME_WAIT
+ taken = {225, 226}
+ port = tunnel.listen_port(Slot(0).listen_ports, bindable=lambda p, k=0: p not in taken,
+ port_start=lambda: 1024)
+ assert port == 240
+
+
+def test_exec_tunnel_passes_the_slots_port(tmp_path, monkeypatch):
+ monkeypatch.setattr(const, "STATE_DIR", str(tmp_path))
+ os.makedirs(Slot(2).dir)
+ with open(Slot(2).spec, "w") as f:
+ json.dump(SPEC, f)
+ asked, ran = [], []
+ monkeypatch.setattr(tunnel.shutil, "which", lambda *a, **k: "/usr/bin/sshuttle")
+ monkeypatch.setattr(tunnel, "pinned_ssh_config", lambda spec: None)
+ monkeypatch.setattr(tunnel, "listen_port",
+ lambda ports, udp=False: asked.append((ports, udp)) or ports[1])
+ monkeypatch.setattr(tunnel.os, "execv", lambda path, argv: ran.append(argv))
+ tunnel.exec_tunnel(2)
+ assert asked == [(Slot(2).listen_ports, False)]
+ assert ran[0][ran[0].index("--listen") + 1] == "127.0.0.1:230"
+
+
+def test_sshuttle_argv_listens_on_the_slots_port():
+ argv = tunnel.sshuttle_argv(SPEC, "sshuttle", port=227)
+ assert argv[argv.index("--listen") + 1] == "127.0.0.1:227"
+ # sshuttle fails when both families get a port: IPv6 keeps its own search
+ argv = tunnel.sshuttle_argv(dict(SPEC, ipv6=True), "sshuttle", port=227)
+ assert argv[argv.index("--listen") + 1] == "127.0.0.1:227,[::1]:0"
+ assert "--listen" not in tunnel.sshuttle_argv(SPEC, "sshuttle")
+
+
+def test_listen_port_skips_a_port_in_use(capsys):
+ taken = {(225, socket.SOCK_STREAM)}
+
+ def bindable(port, kind=socket.SOCK_STREAM):
+ return (port, kind) not in taken
+ assert tunnel.listen_port([225, 226], bindable=bindable, port_start=lambda: 1024) == 226
+ taken.add((226, socket.SOCK_DGRAM))
+ # tproxy binds UDP on it too; with neither free, sshuttle gets the first and fails
+ assert tunnel.listen_port([225, 226], True, bindable, lambda: 1024) == 225
+ assert "no free redirect port among 225-226" in capsys.readouterr().err
+ assert tunnel.listen_port([225, 226], bindable=lambda p, k=0: True,
+ port_start=lambda: 0) == 225
+ assert "ip_unprivileged_port_start is 0" in capsys.readouterr().err
+
+
+def test_bindable_sees_a_port_in_time_wait():
+ listener = socket.socket()
+ listener.bind(("127.0.0.1", 0))
+ port = listener.getsockname()[1]
+ listener.listen(1)
+ assert not tunnel.bindable(port)
+ client = socket.create_connection(("127.0.0.1", port))
+ conn, _ = listener.accept()
+ conn.close() # the listener's side closes first: TIME_WAIT
+ listener.close()
+ time.sleep(0.05)
+ client.close()
+ assert not tunnel.bindable(port)
+
+
+def test_resolv_conf_must_point_at_resolveds_stub(tmp_path):
+ f = tmp_path / "resolv.conf"
+ f.write_text("# stub\nnameserver 127.0.0.53\noptions edns0 trust-ad\nsearch .\n")
+ assert tunnel.resolv_conf_problem(str(f)) is None
+ f.write_text("nameserver 127.0.0.54\n")
+ assert tunnel.resolv_conf_problem(str(f)) is None
+ # resolved's own list of the real servers (/run/systemd/resolve/resolv.conf)
+ f.write_text("nameserver 10.1.0.53\nnameserver 192.168.1.1\nsearch corp.example\n")
+ assert tunnel.resolv_conf_problem(str(f)) == \
+ f"{f} lists 10.1.0.53, 192.168.1.1, not only resolved's stub 127.0.0.53"
+ f.write_text("search corp.example\n") # glibc then asks 127.0.0.1
+ assert tunnel.resolv_conf_problem(str(f)) == f"{f} lists no nameserver"
+ assert "cannot read" in tunnel.resolv_conf_problem(str(tmp_path / "missing"))
+
+
+def test_unprivileged_port_start(tmp_path):
+ f = tmp_path / "start"
+ f.write_text("1024\n")
+ assert tunnel.unprivileged_port_start(str(f)) == 1024
+ assert tunnel.unprivileged_port_start(str(tmp_path / "missing")) is None