From 4c34f7baaada54531822ff467b5735a375843943 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 23 Oct 2026 15:15:46 +0000
Subject: [PATCH 01/16] fix(profile): reject IPv6 scope IDs in addresses and
networks
- ipaddress accepts a scope id after "%" and keeps its text, spaces,
quotes and braces included, in str(); a crafted scope in subnets,
exclude or gateway reached the root nft script, where an include
made root read a file and log its lines
- refuse "%" in subnets, exclude, gateway, probe and dns-servers
- collapse() and the stored networks rebuild each network from its
number and prefix, so only address characters reach nft and
sshuttle's arguments even if a check is missed
- a failed guard logs only nft's error line, not the source lines it
quotes after it
- the editor's inet_pton already refused scope ids; shared cases now
cover each address field
Co-Authored-By: Claude Opus 5.5 (1M context)
---
CHANGELOG.md | 12 ++++++++++++
docs/design.md | 11 ++++++++++-
docs/later/ipv6.md | 4 ++++
docs/user-guide.md | 2 +-
nm_sshuttle/guard.py | 8 +++++++-
nm_sshuttle/profile.py | 24 ++++++++++++++++++++++--
tests/profile-cases.json | 11 +++++++++++
tests/test_guard.py | 38 ++++++++++++++++++++++++++++++++++++++
tests/test_profile.py | 32 +++++++++++++++++++++++++++++++-
9 files changed, 136 insertions(+), 6 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index efa411b..b6d9fc2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,17 @@ 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
+
+- 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.
+
## [0.1.0] - 2026-10-11
The first release.
@@ -45,4 +56,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/docs/design.md b/docs/design.md
index c54cfa9..84eec48 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -878,7 +878,10 @@ $ nm-sshuttle check corp # as the user: ssh -G, host key, test login
- `remote` must match `^[A-Za-z0-9._@:%\[\]-]+$` and must not start with
`-`;
-- every address and network must parse with `ipaddress`;
+- 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:`;
- `vpn.persistent` must be `yes`, so that NM keeps the VPN across drops
@@ -1497,6 +1500,12 @@ ahead of the `dnat` ones accept what sshuttle's mangle chain marked
(`ip daddr @subnets4 meta mark 0x4e530000 accept`, and the same for IPv6;
[tproxy](later/tproxy.md)).
+The set elements are written from each network's number, never from the
+profile's text, so nothing but address characters reaches `nft -f -`, even
+if a check of §4.2 were missed. When nft refuses the script, the plugin logs
+only nft's line that names the error: the lines after it quote the script,
+or a file that the script included.
+
**[lab T4]** In the lab, while the tunnel was down, connections failed in
about 10 ms instead of leaking to the default route. In the lab's container,
that default route even answered queries for the internal DNS server's
diff --git a/docs/later/ipv6.md b/docs/later/ipv6.md
index 29483b6..bf61f9d 100644
--- a/docs/later/ipv6.md
+++ b/docs/later/ipv6.md
@@ -86,6 +86,10 @@ places below) and NetworkManager `main` (1.59.2-dev, ef234f8).
| `probe` | `ADDRESS:PORT` or `[IPV6]:PORT`. |
| `dns-servers` | Unchanged: IPv4 only. An IPv6 server is refused with a message that names this limit. |
+No address or network key takes a scope id (`fe80::1%eth0`): `ipaddress`
+accepts one and keeps its text, which is free, so `profile.parse` refuses it
+(design §4.2). Only `remote` may have one, since it never reaches nft.
+
`profile.parse` keeps networks as strings; `Profile` gains nothing new.
`guarded_networks()` returns both families, each collapsed on its own.
The IPv6 /128s of DNS servers do not arise, since servers stay IPv4.
diff --git a/docs/user-guide.md b/docs/user-guide.md
index da03215..b78066b 100644
--- a/docs/user-guide.md
+++ b/docs/user-guide.md
@@ -109,7 +109,7 @@ The options of `add`:
| Option | Meaning |
|---|---|
| `--remote` | The ssh destination, as you would type it after `ssh`; usually a `Host` alias. Required. |
-| `--subnets` | The networks to send through the tunnel, IPv4 or IPv6, separated by commas. Required. |
+| `--subnets` | The networks to send through the tunnel, IPv4 or IPv6, separated by commas. Required. A scope id (`fe80::%eth0/64`) is refused, here and in the other address options. |
| `--exclude` | Networks inside those to leave out. |
| `--dns` | `none` (the default) leaves DNS alone. `split` sends lookups for `--dns-domains` to `--dns-servers` through the tunnel, and everything else as before. `all` sends every lookup through the tunnel. |
| `--dns-servers` | The DNS servers on the far side, IPv4 only. Required for `split` and `all`. |
diff --git a/nm_sshuttle/guard.py b/nm_sshuttle/guard.py
index 060fd07..07a1715 100644
--- a/nm_sshuttle/guard.py
+++ b/nm_sshuttle/guard.py
@@ -77,6 +77,8 @@ def guard_ruleset(table, networks, exclude, mark=None):
takes (priority mangle, before this hook), so a packet with that mark is
let through (docs/later/tproxy.md)."""
def set_def(name, items, version):
+ # collapse() rebuilds each network from its number, so only address
+ # characters reach the script, whatever text the profile held.
items = collapse(items, version)
body = f"type ipv{version}_addr; flags interval;"
if items:
@@ -113,7 +115,11 @@ def install_guard(table, networks, exclude, mark=None):
script += guard_ruleset(table, networks, exclude, mark)
ok, out = run(["nft", "-f", "-"], input=script)
if not ok:
- raise RuntimeError(f"cannot install the guard table: {out}")
+ # Only the line that names the error (a warning may come before it):
+ # the lines after it quote the script, or a file that the script included.
+ lines = out.splitlines() or ["nft failed"]
+ first = next((line for line in lines if "Error:" in line), lines[0])
+ raise RuntimeError(f"cannot install the guard table: {first}")
def guard_present(table):
diff --git a/nm_sshuttle/profile.py b/nm_sshuttle/profile.py
index 0b61424..942dfb1 100644
--- a/nm_sshuttle/profile.py
+++ b/nm_sshuttle/profile.py
@@ -72,13 +72,23 @@ def family(network):
return ipaddress.ip_network(network, strict=False).version
+def _network(text):
+ """An address or network string as an ipaddress network without a scope id.
+
+ ipaddress takes "fe80::%eth0/64" and keeps the scope, which is free text, in
+ str(). Rebuilt from its number, the network prints as address characters
+ only, whatever text it came from: its str() may go into the root nft script."""
+ net = ipaddress.ip_network(text, strict=False)
+ return type(net)((int(net.network_address), net.prefixlen))
+
+
def collapse(networks, version=None):
"""Merge overlapping and adjacent networks, as strings: IPv4 first, then
IPv6, each family on its own (version: only that family).
nft refuses an interval set with overlapping elements ("conflicting
intervals"), and a DNS server's /32 usually lies inside a profile subnet."""
- nets = [ipaddress.ip_network(n, strict=False) for n in networks]
+ nets = [_network(n) for n in networks]
out = []
for v in (4, 6):
if version in (None, v):
@@ -91,17 +101,26 @@ def _split(value):
return [v for v in re.split(r"[\s,]+", value or "") if v]
+def _unscoped(key, value):
+ """Refuse an IPv6 scope id ("fe80::1%eth0"). ipaddress takes any text after
+ the "%", spaces and newlines included, and keeps it."""
+ if "%" in value:
+ raise ProfileError(f"{key}: {value!r} has a scope id; addresses with % are not supported")
+
+
def _networks(key, value):
nets = []
for item in _split(value):
+ _unscoped(key, item)
try:
- nets.append(str(ipaddress.ip_network(item, strict=False)))
+ nets.append(str(_network(item)))
except ValueError:
raise ProfileError(f"{key}: {item!r} is not a network") from None
return nets
def _address(key, value):
+ _unscoped(key, value)
try:
return str(ipaddress.ip_address(value))
except ValueError:
@@ -109,6 +128,7 @@ def _address(key, value):
def _ipv4(key, value):
+ _unscoped(key, value)
try:
return str(ipaddress.IPv4Address(value))
except ValueError:
diff --git a/tests/profile-cases.json b/tests/profile-cases.json
index 960e03f..87af231 100644
--- a/tests/profile-cases.json
+++ b/tests/profile-cases.json
@@ -72,10 +72,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 +93,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 +113,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 +123,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_guard.py b/tests/test_guard.py
index 702c63a..5b1d957 100644
--- a/tests/test_guard.py
+++ b/tests/test_guard.py
@@ -74,3 +74,41 @@ 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"], [])
diff --git a/tests/test_profile.py b/tests/test_profile.py
index 7d7fc3b..9b3eead 100644
--- a/tests/test_profile.py
+++ b/tests/test_profile.py
@@ -4,7 +4,7 @@
import pytest
from fakes import fake_getpwnam, settings
-from nm_sshuttle.profile import ProfileError, parse
+from nm_sshuttle.profile import ProfileError, collapse, parse
def p(s):
@@ -89,3 +89,33 @@ 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"]
+
From 6a1b9ba2959132b3dd182fd1e9c8d98be4113dc2 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 23 Oct 2026 15:16:05 +0000
Subject: [PATCH 02/16] fix(profile): check the ssh destination as sshuttle
splits it
- the remote only had to match a character class, so "@corp",
"@-gD1080" and "user:password@host" passed; sshuttle then ran its
server locally as root without ssh, passed the host to ssh as an
option, or put the password on its command line and in the journal
- split the destination as sshuttle's parse_hostport does,
[USER@]HOST[:PORT]: the user part is not empty and has no ":", the
host is not empty, does not start with "-" and is an IPv6 address
when bracketed or with several colons, and a port is 1 to 65535
- the error for a ":" in the user part leaves out the value, which
holds the password
- port checks for remote and probe read ASCII digits only and refuse
a number too long for int() with a profile error
- the GNOME editor applies the same rules; shared cases cover both
Co-Authored-By: Claude Opus 5.5 (1M context)
---
CHANGELOG.md | 4 ++
docs/design.md | 12 +++++-
docs/later/gnome-editor.md | 5 +++
docs/user-guide.md | 2 +-
gnome/nm-sshuttle-validate.c | 83 ++++++++++++++++++++++++++++++++----
nm_sshuttle/profile.py | 62 ++++++++++++++++++++++++---
tests/profile-cases.json | 27 ++++++++++++
tests/test_profile.py | 22 ++++++++++
8 files changed, 200 insertions(+), 17 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b6d9fc2..5690492 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,10 @@ uses [semantic versioning](https://semver.org/).
`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.
## [0.1.0] - 2026-10-11
diff --git a/docs/design.md b/docs/design.md
index 84eec48..7f148a4 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -876,8 +876,16 @@ $ 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
- `-`;
+- `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
diff --git a/docs/later/gnome-editor.md b/docs/later/gnome-editor.md
index 444eadd..db5b9fe 100644
--- a/docs/later/gnome-editor.md
+++ b/docs/later/gnome-editor.md
@@ -272,6 +272,11 @@ NetworkManager or the plugin.
- **Shared cases found a gap in the plugin:** `$` in a Python regex also
matches before a trailing newline, so `profile.parse` accepted
`remote="corp\n"`. It now matches the whole value.
+- **The SSH destination is split as sshuttle splits it,** on both sides:
+ `user@`, `@host`, `@-x` and `user:password@host` are refused, as design
+ §4.2 lists. The editor's `inet_pton` already refused IPv6 scope ids in
+ address fields, which the plugin had accepted; the plugin now refuses them
+ too, and a shared case covers each field.
- **IPv6 networks** (subnets, exclude, first hop, probe) are accepted, as in
the plugin; DNS servers stay IPv4. The IPv6 tab has the same "Use this
connection only for resources on its network" switch, so the note names
diff --git a/docs/user-guide.md b/docs/user-guide.md
index b78066b..f4d0765 100644
--- a/docs/user-guide.md
+++ b/docs/user-guide.md
@@ -108,7 +108,7 @@ The options of `add`:
| Option | Meaning |
|---|---|
-| `--remote` | The ssh destination, as you would type it after `ssh`; usually a `Host` alias. Required. |
+| `--remote` | The ssh destination, as you would type it after `ssh`; usually a `Host` alias. `user@host` works too; put a port in the alias (`Port` in `~/.ssh/config`). A password (`user:password@host`) is refused: use a key. Required. |
| `--subnets` | The networks to send through the tunnel, IPv4 or IPv6, separated by commas. Required. A scope id (`fe80::%eth0/64`) is refused, here and in the other address options. |
| `--exclude` | Networks inside those to leave out. |
| `--dns` | `none` (the default) leaves DNS alone. `split` sends lookups for `--dns-domains` to `--dns-servers` through the tunnel, and everything else as before. `all` sends every lookup through the tunnel. |
diff --git a/gnome/nm-sshuttle-validate.c b/gnome/nm-sshuttle-validate.c
index dc11bb4..d982ed6 100644
--- a/gnome/nm-sshuttle-validate.c
+++ b/gnome/nm-sshuttle-validate.c
@@ -127,6 +127,35 @@ all_digits(const char *s)
return TRUE;
}
+/* An IPv6 address with an optional scope id ("fe80::1%eth0"), as Python's
+ * ipaddress.IPv6Address takes it. Only an ssh destination may have a scope. */
+static gboolean
+parse_ipv6_scoped(const char *s)
+{
+ const char *percent = strchr(s, '%');
+ g_autofree char *addr = NULL;
+
+ if (!percent)
+ return parse_ipv6(s);
+ if (!percent[1] || strchr(percent + 1, '%'))
+ return FALSE;
+ addr = g_strndup(s, percent - s);
+ return parse_ipv6(addr);
+}
+
+/* 1 to 65535 in decimal digits, leading zeros allowed, as int() reads it. */
+static gboolean
+valid_port(const char *s)
+{
+ guint64 port = 0;
+
+ if (!all_digits(s))
+ return FALSE;
+ for (; *s && port <= 65535; s++)
+ port = port * 10 + (*s - '0');
+ return port > 0 && port <= 65535;
+}
+
/* A prefix length, a netmask or a hostmask, as Python's ipaddress takes them. */
static gboolean
valid_ipv4_mask(const char *s)
@@ -174,16 +203,56 @@ check_networks(NmssField field, const char *value, gboolean required, GError **e
return TRUE;
}
+/* [USER@]HOST[:PORT] as sshuttle's parse_hostport splits it, and as profile.py's
+ * _remote() checks it: USER is not empty and has no ":"; HOST is not empty, does
+ * not start with "-", and may be an IPv6 address, in brackets when a port
+ * follows. */
gboolean
nmss_check_remote(const char *value, GError **error)
{
+ const char *at;
+ const char *rest;
+ const char *port = NULL;
+ g_autofree char *host = NULL;
+ gboolean ok;
+
if (is_blank(value))
return fail(error, NMSS_FIELD_REMOTE, _("SSH destination is required"));
- if (*value == '-' || strspn(value, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
- "0123456789._@:%[]-") != strlen(value))
+ at = strrchr(value, '@');
+ if (at && memchr(value, ':', at - value))
+ return fail(error, NMSS_FIELD_REMOTE,
+ _("SSH destination: the part before “@” must not contain “:”, which "
+ "sshuttle reads as the start of a password"));
+ rest = at ? at + 1 : value;
+ ok = *value != '-' && at != value
+ && strspn(value, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+ "0123456789._@:%[]-") == strlen(value);
+ if (ok && *rest == '[') {
+ const char *close = strchr(rest, ']');
+
+ ok = close && (close[1] == '\0' || close[1] == ':');
+ if (ok) {
+ host = g_strndup(rest + 1, close - rest - 1);
+ ok = parse_ipv6_scoped(host);
+ port = close[1] ? close + 2 : NULL;
+ }
+ } else if (ok) {
+ const char *colon = strchr(rest, ':');
+
+ if (colon && !strchr(colon + 1, ':')) {
+ host = g_strndup(rest, colon - rest);
+ port = colon + 1;
+ } else {
+ host = g_strdup(rest);
+ ok = !colon || parse_ipv6_scoped(host);
+ }
+ }
+ ok = ok && (!port || valid_port(port)) && *host && *host != '-' && !strpbrk(host, "[]");
+ if (!ok)
return fail(error, NMSS_FIELD_REMOTE,
_("SSH destination: “%s” is not valid. Use a host name, an alias from "
- "~/.ssh/config or user@host, and do not start with “-”"),
+ "~/.ssh/config or an address, optionally as user@host, and do not "
+ "start the host with “-”"),
value);
return TRUE;
}
@@ -302,18 +371,14 @@ nmss_check_probe(const char *value, GError **error)
const char *colon;
g_autofree char *host = NULL;
gsize len;
- guint64 port = 0;
gboolean ok = FALSE;
if (is_blank(value))
return TRUE;
colon = strrchr(value, ':');
- if (colon && all_digits(colon + 1)) {
- for (const char *p = colon + 1; *p && port <= 65535; p++)
- port = port * 10 + (*p - '0');
+ if (colon && valid_port(colon + 1))
host = g_strndup(value, colon - value);
- }
- if (host && port > 0 && port <= 65535) {
+ if (host) {
len = strlen(host);
if (len >= 2 && host[0] == '[' && host[len - 1] == ']') {
g_autofree char *inner = g_strndup(host + 1, len - 2);
diff --git a/nm_sshuttle/profile.py b/nm_sshuttle/profile.py
index 942dfb1..373fb89 100644
--- a/nm_sshuttle/profile.py
+++ b/nm_sshuttle/profile.py
@@ -141,6 +141,59 @@ def _ipv4(key, value):
raise ProfileError(f"{key}: {value} is IPv6; only IPv4 DNS servers are supported")
+def _port(text):
+ """1 to 65535 in ASCII digits, leading zeros allowed, as an int; else None.
+ The length check comes first: int() refuses a string of over 4300 digits
+ with a ValueError of its own."""
+ digits = text.lstrip("0")
+ if not (text.isascii() and text.isdigit() and 0 < len(digits) <= 5):
+ return None
+ port = int(digits)
+ return port if port < 65536 else None
+
+
+def _is_ipv6(text):
+ try:
+ ipaddress.IPv6Address(text)
+ except ValueError:
+ return False
+ return True
+
+
+def _remote(value):
+ """Check an ssh destination as sshuttle's parse_hostport splits it:
+ [USER@]HOST[:PORT], where HOST may be an IPv6 address, in brackets when a
+ port follows. sshuttle starts its server locally, as root and without ssh,
+ when HOST is empty, passes a HOST that starts with "-" to ssh as an option,
+ and reads USER:PASSWORD@HOST as a password.
+
+ A scope id is fine here, unlike in the address keys: ssh takes it, and the
+ destination never reaches nft."""
+ user, at, host = value.rpartition("@")
+ if ":" in user:
+ # Not in the message, which is logged: what follows ":" is a password.
+ raise ProfileError("remote: the user part must not contain ':' (sshuttle takes "
+ "what follows as a password)")
+ bad = ProfileError(f"remote: {value!r} is not a valid ssh destination")
+ if not REMOTE_RE.fullmatch(value) or value.startswith("-") or (at and not user):
+ raise bad
+ port = None
+ if host.startswith("["):
+ host, sep, rest = host[1:].partition("]")
+ if not sep or rest[:1] not in ("", ":") or not _is_ipv6(host):
+ raise bad
+ port = rest[1:] if rest else None
+ elif host.count(":") == 1:
+ host, _, port = host.partition(":")
+ elif ":" in host and not _is_ipv6(host):
+ raise bad
+ if port is not None and _port(port) is None:
+ raise bad
+ if not host or host.startswith("-") or "[" in host or "]" in host:
+ raise bad
+ return value
+
+
def _bool(key, value, default):
if value is None or value == "":
return default
@@ -158,9 +211,7 @@ def parse(settings, getpwnam=pwd.getpwnam):
s_ip4 = settings.get("ipv4", {})
data = s_vpn.get("data", {})
- remote = data.get("remote", "")
- if not REMOTE_RE.fullmatch(remote) or remote.startswith("-"):
- raise ProfileError(f"remote: {remote!r} is not a valid ssh destination")
+ remote = _remote(data.get("remote", ""))
user = data.get("local-user", "")
if not USER_RE.fullmatch(user):
@@ -215,13 +266,14 @@ def parse(settings, getpwnam=pwd.getpwnam):
probe = data.get("probe") or None
if probe:
host, sep, port = probe.rpartition(":")
- if not sep or not port.isdigit() or not 0 < int(port) < 65536:
+ port = _port(port)
+ if not sep or port is None:
raise ProfileError(f"probe: expected ADDRESS:PORT or [IPV6]:PORT, got {probe!r}")
bracketed = host.startswith("[") and host.endswith("]")
addr = _address("probe", host[1:-1] if bracketed else host)
if (family(addr) == 6) != bracketed:
raise ProfileError(f"probe: expected ADDRESS:PORT or [IPV6]:PORT, got {probe!r}")
- probe = f"[{addr}]:{int(port)}" if bracketed else f"{addr}:{int(port)}"
+ probe = f"[{addr}]:{port}" if bracketed else f"{addr}:{port}"
return Profile(
id=s_con.get("id", "?"), uuid=s_con.get("uuid", ""), remote=remote, user=user,
diff --git a/tests/profile-cases.json b/tests/profile-cases.json
index 87af231..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"},
diff --git a/tests/test_profile.py b/tests/test_profile.py
index 9b3eead..d59f8eb 100644
--- a/tests/test_profile.py
+++ b/tests/test_profile.py
@@ -119,3 +119,25 @@ def test_collapse_drops_a_scope_that_got_through():
"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)
From ecde9cdc850104f0b34cf7a47dab0d510c111347 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 23 Oct 2026 16:31:36 +0000
Subject: [PATCH 03/16] fix(service): tie a claim to the start time of its
process
- a claim counted while any process with its PID had
nm-sshuttle-service in its command line; any user can name a process
so, and one that got the PID of a killed instance kept that
instance's leftover claim alive and blocked overlapping activations
- the instance records its start time (field 22 of /proc/PID/stat) in
the claim, and the claim counts only while that process runs as root
with that start time
- a claim from an older version, without a start time, needs a process
with every user ID 0, not euid 0 alone, which sudo has while it waits
for a password
Co-Authored-By: Claude Opus 5.5 (1M context)
---
CHANGELOG.md | 4 +++
docs/design.md | 6 +++++
docs/later/multiple-tunnels.md | 3 ++-
nm_sshuttle/claims.py | 49 +++++++++++++++++++++++++++++-----
nm_sshuttle/service.py | 3 ++-
tests/test_multi.py | 42 ++++++++++++++++++++++++-----
6 files changed, 91 insertions(+), 16 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5690492..afe2e36 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,10 @@ uses [semantic versioning](https://semver.org/).
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.
+- 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.
## [0.1.0] - 2026-10-11
diff --git a/docs/design.md b/docs/design.md
index 7f148a4..d9a8af9 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -1620,6 +1620,12 @@ minimal path under it; `ip` and `nft` there are untested.
- **The bridge never runs anything as root except `setpriv`**, and ssh
never runs as root.
- **D-Bus access:** only root may own or call the plugin's name.
+- **Claims** count while the process they name has the start time
+ recorded in the claim (`/proc/PID/stat`), so a process that reuses the
+ PID never counts. A claim written before start times, during an upgrade,
+ needs a process with `nm-sshuttle-service` in its command line and every
+ user ID 0 (`/proc/PID/status`): euid 0 alone would admit sudo waiting
+ for a password, with that string among its arguments.
### 4.9 Code layout and size
diff --git a/docs/later/multiple-tunnels.md b/docs/later/multiple-tunnels.md
index 451f938..54a2a72 100644
--- a/docs/later/multiple-tunnels.md
+++ b/docs/later/multiple-tunnels.md
@@ -224,7 +224,8 @@ Two active profiles must not claim the same traffic or the same DNS. At
exist, the instance takes `/run/nm-sshuttle/claims.lock` (`flock`), reads
the other slots' `claim.json` files, checks, writes its own and releases
the lock. A claim counts while the PID in it is a running
-`nm-sshuttle-service`. The instance removes its claim when it sends
+`nm-sshuttle-service` with the start time the claim recorded
+(design §4.8). The instance removes its claim when it sends
STOPPED, and `cleanup --slot N` removes it after a kill.
A claim holds the profile's id and UUID, its *effective networks* (the
diff --git a/nm_sshuttle/claims.py b/nm_sshuttle/claims.py
index 32407f8..9656f2f 100644
--- a/nm_sshuttle/claims.py
+++ b/nm_sshuttle/claims.py
@@ -5,7 +5,7 @@
Each plugin instance writes its claim to its slot's claim.json while it holds
the claims lock, after reading the others' claims; a claim counts while the
-PID in it is a running plugin.
+process it names, by PID and start time, is a running plugin.
"""
import fcntl
@@ -40,7 +40,8 @@ def effective_networks(networks, exclude):
def make_claim(profile, hops, pid=None):
- """The claim of an activation: what the conflict rules compare."""
+ """The claim of an activation: what the conflict rules compare. The
+ instance adds its PID and start time when it takes it."""
return {"id": profile.id, "uuid": profile.uuid, "pid": pid,
"networks": effective_networks(profile.guarded_networks(), profile.exclude),
"dns": profile.dns,
@@ -110,13 +111,47 @@ def visit(i, path):
return [nodes[i].get("id") or nodes[i].get("uuid") or "?" for i in loop] if loop else None
-def _alive(pid):
- """pid is a running plugin instance."""
+def process_start(pid, proc="/proc"):
+ """When the process started, in clock ticks since boot (field 22 of
+ /proc/PID/stat), or None. With the PID it names one process for good."""
try:
- with open(f"/proc/{int(pid)}/cmdline", "rb") as f:
- return b"nm-sshuttle-service" in f.read()
+ with open(f"{proc}/{int(pid)}/stat") as f:
+ text = f.read()
+ # the command name in field 2 may hold spaces and parentheses
+ return int(text[text.rindex(")") + 2:].split()[19])
+ except (OSError, ValueError, TypeError, IndexError):
+ return None
+
+
+def runs_as_root(pid, proc="/proc"):
+ """Whether every user ID of the process is 0 (/proc/PID/status). A
+ setuid-root program such as sudo has euid 0 at once, but keeps its
+ caller's real user ID until it has checked a password."""
+ try:
+ with open(f"{proc}/{int(pid)}/status") as f:
+ for line in f:
+ if line.startswith("Uid:"):
+ return line.split()[1:] == ["0"] * 4
except (OSError, ValueError, TypeError):
+ pass
+ return False
+
+
+def _alive(pid, start=None, proc="/proc"):
+ """pid is a running plugin instance: with the start time the claim
+ recorded, so that another process that got the PID later never counts.
+ A claim from before start times (an upgrade) needs a process that runs as
+ root, not only one with euid 0, with nm-sshuttle-service in its command
+ line."""
+ try:
+ with open(f"{proc}/{int(pid)}/cmdline", "rb") as f:
+ if b"nm-sshuttle-service" not in f.read():
+ return False
+ except (OSError, ValueError, TypeError):
+ return False
+ if not runs_as_root(pid, proc):
return False
+ return start is None or process_start(pid, proc) == start
def read_claims(skip, alive=_alive, slots=range(SLOTS)):
@@ -130,7 +165,7 @@ def read_claims(skip, alive=_alive, slots=range(SLOTS)):
claim = json.load(f)
except (OSError, ValueError):
continue
- if alive(claim.get("pid")):
+ if alive(claim.get("pid"), claim.get("start")):
out.append(claim)
return out
diff --git a/nm_sshuttle/service.py b/nm_sshuttle/service.py
index 3f7efe8..65ddf77 100644
--- a/nm_sshuttle/service.py
+++ b/nm_sshuttle/service.py
@@ -537,7 +537,8 @@ def policy_routing_present(self, families):
return guard.policy_routing_present(families, self.slot.n)
def take_claim(self, claim):
- return claims.take(self.slot.n, dict(claim, pid=os.getpid()))
+ pid = os.getpid()
+ return claims.take(self.slot.n, dict(claim, pid=pid, start=claims.process_start(pid)))
def release_claim(self):
claims.release(self.slot.n)
diff --git a/tests/test_multi.py b/tests/test_multi.py
index 1dd9d24..e602b1b 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"}
From 700ebeb03c2ee5e53fe40f6152dbe9ddd64f1359 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 23 Oct 2026 16:31:40 +0000
Subject: [PATCH 04/16] fix(service): answer VPN.Plugin calls only from
NetworkManager
- an instance took Connect and Disconnect from any sender the bus let
through; its per-activation names rely only on the bus's default deny
of method calls, so a confined root process, or a principal a local
policy lets send, could make the plugin reroute traffic to a server
of its choice and run ssh as any user
- other senders get org.freedesktop.DBus.Error.AccessDenied and a
warning in the journal; when NetworkManager's name watch has not
reported yet, the plugin asks the bus who owns the name
- the bus policy gets no deny by interface, which would also refuse
every message without an interface field to any service; a test
keeps it that way
Co-Authored-By: Claude Opus 5.5 (1M context)
---
CHANGELOG.md | 1 +
docs/design.md | 8 +++++++-
nm_sshuttle/service.py | 22 ++++++++++++++++++++++
tests/test_data.py | 8 ++++++++
tests/test_service_dbus.py | 19 +++++++++++++++++++
5 files changed, 57 insertions(+), 1 deletion(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index afe2e36..cc8fcea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ uses [semantic versioning](https://semver.org/).
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 plugin answers `VPN.Plugin` calls only from NetworkManager.
- 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
diff --git a/docs/design.md b/docs/design.md
index d9a8af9..56def9f 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -1619,7 +1619,13 @@ minimal path under it; `ip` and `nft` there are untested.
user.
- **The bridge never runs anything as root except `setpriv`**, and ssh
never runs as root.
-- **D-Bus access:** only root may own or call the plugin's name.
+- **D-Bus access:** only root may own or call the plugin's name, and the
+ plugin answers `VPN.Plugin` calls only from NetworkManager's current
+ unique name, others with `AccessDenied`. When the name watch has not
+ reported NM yet, it asks the bus (`GetNameOwner`). The per-activation
+ names rely on the bus's default deny of method calls. The policy adds no
+ deny by interface: one without a destination also refuses every message
+ that has no interface field, to any service on the bus (dbus-daemon(1)).
- **Claims** count while the process they name has the start time
recorded in the claim (`/proc/PID/stat`), so a process that reuses the
PID never counts. A claim written before start times, during an upgrade,
diff --git a/nm_sshuttle/service.py b/nm_sshuttle/service.py
index 65ddf77..bf6dfa9 100644
--- a/nm_sshuttle/service.py
+++ b/nm_sshuttle/service.py
@@ -40,6 +40,7 @@
PROPS_IFACE = "org.freedesktop.DBus.Properties"
VPN_ERROR_LAUNCH_FAILED = "org.freedesktop.NetworkManager.VPN.Error.LaunchFailed"
+ACCESS_DENIED = "org.freedesktop.DBus.Error.AccessDenied"
FIRST_HOP_TIMEOUT_S = 25
LINK_CHECK_MS = 500
@@ -239,8 +240,29 @@ def on_get_property(self, conn, sender, path, iface, prop):
return GLib.Variant("u", self.sup.state)
return None
+ def from_nm(self, sender):
+ """Whether sender is NetworkManager. Its name watch may not have
+ reported NM yet, as for a Connect right after the start, or NM may
+ have just restarted: then ask the bus."""
+ if sender and sender == self.sup.nm_current_owner:
+ return True
+ try:
+ r = self.conn.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus",
+ "org.freedesktop.DBus", "GetNameOwner",
+ GLib.Variant("(s)", (NM_NAME,)), GLib.VariantType("(s)"),
+ Gio.DBusCallFlags.NONE, 1000, None)
+ except GLib.Error:
+ return False
+ return bool(sender) and r.unpack()[0] == sender
+
def on_method_call(self, conn, sender, path, iface, method, params, inv):
try:
+ if not self.from_nm(sender):
+ # Only NetworkManager drives the plugin (design §4.8); the bus
+ # policy alone would let any root process through.
+ log.warning("refused D-Bus call %s from %s: not NetworkManager", method, sender)
+ inv.return_dbus_error(ACCESS_DENIED, "only NetworkManager may call the plugin")
+ return
log.info("D-Bus call %s from %s", method, sender)
self.sup.touch()
if method in ("Connect", "ConnectInteractive"):
diff --git a/tests/test_data.py b/tests/test_data.py
index 20f257f..10e24a7 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"
diff --git a/tests/test_service_dbus.py b/tests/test_service_dbus.py
index f8972c4..787ac4b 100644
--- a/tests/test_service_dbus.py
+++ b/tests/test_service_dbus.py
@@ -586,3 +586,22 @@ 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() == ("",)
From 248fdd3df5c03bba88d91826dad96f0adc31b81b Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 23 Oct 2026 16:31:44 +0000
Subject: [PATCH 05/16] fix(guard): put back a flushed guard during a reconnect
- only the health check while up re-installed a missing guard; after a
ruleset flush in a gap, which can last long while asleep or offline,
traffic to the tunnelled networks took the default route until the
tunnel was up again
- a gap and the reconfiguration after it check the guard every 10 s,
paused or not, and before each attempt, and install it again when nft
lists no guard table; the plugin gives up when that fails
- guard_listed() tells a missing table from nft that cannot be asked,
which is left alone
Co-Authored-By: Claude Opus 5.5 (1M context)
---
CHANGELOG.md | 2 ++
docs/design.md | 4 ++-
nm_sshuttle/guard.py | 11 ++++++++
nm_sshuttle/service.py | 3 +++
nm_sshuttle/supervisor.py | 47 +++++++++++++++++++++++++++------
tests/fakes.py | 6 +++++
tests/test_events.py | 53 ++++++++++++++++++++++++++++++++++++++
tests/test_guard.py | 11 ++++++++
tests/test_service_dbus.py | 1 +
tests/test_supervisor.py | 13 +++++++---
10 files changed, 139 insertions(+), 12 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cc8fcea..a5a9406 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,8 @@ uses [semantic versioning](https://semver.org/).
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 plugin answers `VPN.Plugin` calls only from NetworkManager.
+- 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
diff --git a/docs/design.md b/docs/design.md
index 56def9f..a945573 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -1292,7 +1292,9 @@ Events and what the supervisor does:
port; with `method=tproxy`, its mark chain in iptables' `mangle` table
does, for each tunnelled family, and the plugin's rule and route are
there (put back if not);
- - the guard table exists (re-install it if something flushed the ruleset);
+ - the guard table exists (re-install it if something flushed the ruleset).
+ A gap and the reconfiguration after it check that too, every 10 s,
+ paused or not, and before each attempt;
- an `ssh` process runs in the tunnel unit: sshuttle 1.3 can outlive
its ssh and keep listening with nothing behind it (VM MT-02, where the
lab's ssh ran over corp's tunnel and corp's sshuttle was killed);
diff --git a/nm_sshuttle/guard.py b/nm_sshuttle/guard.py
index 07a1715..4853430 100644
--- a/nm_sshuttle/guard.py
+++ b/nm_sshuttle/guard.py
@@ -13,6 +13,7 @@
from .profile import collapse
from .const import TPROXY_MARK, TPROXY_PRIORITY, TPROXY_TABLE
+from .tunnel import inet_tables
log = logging.getLogger("nm-sshuttle")
@@ -126,6 +127,16 @@ def guard_present(table):
return run(["nft", "list", "table", "inet", table])[0]
+def guard_listed(table):
+ """Whether the guard table is there, from 'nft list tables'. Unlike
+ guard_present, None when nft cannot be asked, which is not "gone"."""
+ try:
+ p = subprocess.run(["nft", "list", "tables"], capture_output=True, text=True, timeout=10)
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ return None if p.returncode else table in inet_tables(p.stdout)
+
+
def remove_guard(table):
if not guard_present(table):
return True
diff --git a/nm_sshuttle/service.py b/nm_sshuttle/service.py
index bf6dfa9..6ee1435 100644
--- a/nm_sshuttle/service.py
+++ b/nm_sshuttle/service.py
@@ -549,6 +549,9 @@ def install_guard(self, networks, exclude, mark=None):
def remove_guard(self):
guard.remove_guard(self.slot.guard_table)
+ def guard_listed(self):
+ return guard.guard_listed(self.slot.guard_table)
+
def install_policy_routing(self, families):
guard.install_policy_routing(families, self.slot.n)
diff --git a/nm_sshuttle/supervisor.py b/nm_sshuttle/supervisor.py
index a3f9556..9ee0158 100644
--- a/nm_sshuttle/supervisor.py
+++ b/nm_sshuttle/supervisor.py
@@ -71,7 +71,8 @@ class Supervisor:
QUIT_CAP = 5.0 # whatever happens, a stopping process exits by then
STOP_CAP = 20.0 # tunnel stop not confirmed: carry on regardless
IDLE_EXIT = 60.0
- HEALTH_INTERVAL = 10.0 # health checks while up (design §4.4, "Health")
+ HEALTH_INTERVAL = 10.0 # health checks while up (design §4.4, "Health"),
+ # and guard checks during a gap
PROBE_TIMEOUT = 5.0 # connect and read the probe's first byte
PROBE_FAILURES = 2 # in a row, before the tunnel is restarted
PORTAL_INTERVAL = 60.0 # at most one attempt a minute behind a captive portal
@@ -747,6 +748,7 @@ def _drop(self, why, at_once=False):
self.phase = "gap"
self.escalated = False
self._tick()
+ self._arm_guard_check()
if at_once:
self.attempts = 0
self.next_at_once = True
@@ -815,6 +817,8 @@ def _kick(self, why):
def _retry(self):
if self.phase != "gap" or self._paused():
return
+ if not self._check_guard():
+ return
if self.retry_after_stop and self.stops:
# An at-once attempt must not race the stop of the tunnel it replaces.
if "stop-wait" not in self.timers:
@@ -1032,7 +1036,7 @@ def _escalate(self):
def _end_gap(self):
self.starting_pending = False
self.starting_sent = False
- self._cancel("escalate", "deadline", "burst-wait", "starting-wait")
+ self._cancel("escalate", "deadline", "burst-wait", "starting-wait", "guard-check")
self.phase = "up"
self.gap_started = None
self.counting_since = None
@@ -1044,6 +1048,38 @@ def _end_gap(self):
self.probe_failures = 0
self._arm_health()
+ # --------------------------------------------------------------- guard
+ def _arm_guard_check(self):
+ self._timer("guard-check", self.HEALTH_INTERVAL, self._guard_tick)
+
+ def _guard_tick(self):
+ """Every 10 s of a gap, paused or not, and of the reconfiguration after
+ it: the health check, which puts the guard back, runs only while up."""
+ if self.phase not in ("gap", "reconfig"):
+ return
+ self._arm_guard_check()
+ self._check_guard()
+
+ def _check_guard(self):
+ """Install the guard again if it is gone (was the ruleset flushed?);
+ False when that failed and the plugin gave up."""
+ if not (self.profile.fail_closed and self.guard_installed):
+ return True
+ if self.fx.guard_listed() is not False:
+ return True # there, or nft cannot be asked
+ return self._restore_guard("during a reconnect")
+
+ def _restore_guard(self, when):
+ """Install the guard again; False when that failed and the plugin gave up."""
+ log.warning("the guard table is gone %s (was the ruleset flushed?); installing it "
+ "again", when)
+ try:
+ self._install_guard()
+ except (OSError, RuntimeError) as e:
+ self.give_up(FAIL_CONNECT, f"cannot restore the guard: {e}")
+ return False
+ return True
+
# --------------------------------------------------------------- health
def _arm_health(self):
self.health_id += 1
@@ -1059,12 +1095,7 @@ def _health(self, hid):
snap = self.fx.nft_health(method)
if snap is not None:
if self.profile.fail_closed and not snap["guard"]:
- log.warning("the guard table is gone (was the ruleset flushed?); installing it "
- "again")
- try:
- self._install_guard()
- except (OSError, RuntimeError) as e:
- self.give_up(FAIL_CONNECT, f"cannot restore the guard: {e}")
+ if not self._restore_guard("while up"):
return
missing = self._tunnelled_families() - snap["sshuttle"]
if method in ("nft", "tproxy") and missing:
diff --git a/tests/fakes.py b/tests/fakes.py
index bc7c16d..8585256 100644
--- a/tests/fakes.py
+++ b/tests/fakes.py
@@ -66,6 +66,8 @@ def __init__(self):
self.claims = [] # claims taken, in order
self.conflict = None # what take_claim answers
self.released = 0
+ self.guard_there = True # what guard_listed answers: True, False or None
+ self.guard_checks = 0
# recording helpers
def _rec(self, *event):
@@ -211,6 +213,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/test_events.py b/tests/test_events.py
index f17de51..110b438 100644
--- a/tests/test_events.py
+++ b/tests/test_events.py
@@ -322,6 +322,59 @@ def test_health_drops_when_sshuttle_outlives_its_ssh(up):
assert sup.phase == "gap" and ("state", ST_STARTING) in fx.events
+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 5b1d957..bc4fb8e 100644
--- a/tests/test_guard.py
+++ b/tests/test_guard.py
@@ -112,3 +112,14 @@ def test_install_guard_reports_only_the_error_line_of_nft(monkeypatch):
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_service_dbus.py b/tests/test_service_dbus.py
index 787ac4b..e60bd5e 100644
--- a/tests/test_service_dbus.py
+++ b/tests/test_service_dbus.py
@@ -348,6 +348,7 @@ def remove_link(name):
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(service.pwd, "getpwnam", fake_getpwnam)
monkeypatch.setattr(service.Service, "run_cleanup", lambda self, done: done())
diff --git a/tests/test_supervisor.py b/tests/test_supervisor.py
index 073caec..21865aa 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"
@@ -283,7 +289,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 +669,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 +700,4 @@ def test_touch_restarts_the_idle_timer():
assert not fx.quit_called
fx.advance(11)
assert fx.quit_called
+
From 8b5ff86cee90d05b86ffc961f58554b6e000d051 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 23 Oct 2026 16:31:49 +0000
Subject: [PATCH 06/16] fix(service): refuse split and all DNS unless lookups
go to resolved
- without systemd-resolved, or with /etc/resolv.conf not pointing at
its stub, glibc asks the listed servers itself and moves on to the
LAN's as soon as the guard refuses the VPN's in a gap; every lookup,
intranet names included, then went to the local network's resolver,
which could also answer them
- at Connect with dns split or all, the plugin reads NetworkManager's
DnsManager Mode and gives up unless it is systemd-resolved and every
nameserver in /etc/resolv.conf is 127.0.0.53 or 127.0.0.54
- nm-sshuttle check reports both; the docs and the Debian description
no longer say that DNS degrades without resolved, and a VM scenario
checks the refusal
Co-Authored-By: Claude Opus 5.5 (1M context)
---
CHANGELOG.md | 4 +++
debian/control | 4 +--
docs/design.md | 52 ++++++++++++++++++++++++--------------
docs/user-guide.md | 15 ++++++++++-
nm_sshuttle/cli.py | 32 ++++++++++++++++++++---
nm_sshuttle/const.py | 2 ++
nm_sshuttle/service.py | 10 +++++++-
nm_sshuttle/supervisor.py | 26 +++++++++++++++++++
nm_sshuttle/tunnel.py | 23 +++++++++++++++++
test-vm/README.md | 8 ++++--
test-vm/run.sh | 23 +++++++++++++++++
tests/fakes.py | 8 ++++++
tests/test_cli.py | 34 +++++++++++++++++++++++++
tests/test_service_dbus.py | 17 +++++++++++++
tests/test_supervisor.py | 34 +++++++++++++++++++++++++
tests/test_tunnel.py | 15 +++++++++++
16 files changed, 279 insertions(+), 28 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a5a9406..a9941c2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,10 @@ uses [semantic versioning](https://semver.org/).
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 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,
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 a945573..e7da816 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -1205,9 +1205,10 @@ Events and what the supervisor does:
`nm-sshuttle.service` (§4.7) remove the link, and the new instance then
exits. With resolved
and `split`, removing the link ends the leak's effect on lookups (R4k).
- With `all`, or without resolved, the leak lasts until NM restarts
- (§4.5). Make kills rare: no `Restart=`, an `OOMScoreAdjust`, and
- packaging that never restarts the plugin under an active VPN.
+ With `all`, the leak lasts until NM restarts (§4.5); without resolved, a
+ profile with DNS is refused (§4.5). Make kills rare: no `Restart=`, an
+ `OOMScoreAdjust`, and packaging that never restarts the plugin under an
+ active VPN.
- **Fallback, the invisible reconnect:** the plugin stays STARTED and sends
nothing during a gap, so NM and GNOME show "connected" while the guard
keeps traffic failing closed (R4d). It is used when the plugin cannot
@@ -1463,19 +1464,31 @@ A user override that makes `nmss0` managed brings the risk back, and the
plugin logs it (§4.1). A profile `dns-priority` above 100 would not
cover the reapply entry and does not suit `all`.
-**Without resolved** (NM writing `/etc/resolv.conf` itself, common on
-Debian), `split` degrades to "every lookup goes to `dns-servers`". Document
-it rather than special-case it. **[src]** A VPN DNS entry that NM fails to
-remove, after a give-up from "connecting", a plugin kill in a gap (R4m, R8m)
-or a relink (§4.4), would then stay in `/etc/resolv.conf` until NM restarts.
-**[src]** NM merges every entry into the file by priority without checking
-that its link exists. A leaked server therefore comes first, and its domain
-becomes a search domain. With the tunnel and guard gone, each lookup would
-first wait out the resolver timeout (5 s in glibc), and query names would
-leave over the uplink. Untested. With resolved and `all`, a leaked entry
-keeps claiming `~.`, so the uplink stays without DNS servers until NM
-restarts **[src]**, untested. The give-up order in §4.4 is therefore
-required, not cosmetic.
+**Without resolved** (NM writing `/etc/resolv.conf` itself), the VPN's
+servers come first in the file, and glibc moves on to the next server, the
+LAN's, as soon as the guard refuses a lookup during a gap, or after its
+timeout. Every lookup, intranet names included, would then go to the LAN's
+resolver. The same happens with resolved when `/etc/resolv.conf` is not its
+stub: NM reports `DnsManager.Mode` `systemd-resolved` also when the file
+links to `/run/systemd/resolve/resolv.conf`, resolved's list of every
+link's real servers, or when NM leaves the file alone **[src]**, and glibc
+then asks the listed servers itself. The plugin therefore refuses `split`
+and `all` at `Connect` unless the mode is `systemd-resolved` and every
+`nameserver` in `/etc/resolv.conf` is resolved's stub (`127.0.0.53` or
+`127.0.0.54`). `nm-sshuttle check` reports both. The packages require
+resolved (RPM) or recommend it (deb).
+
+**[src]** Before the refusal, a VPN DNS entry that NM failed to remove,
+after a give-up from "connecting", a plugin kill in a gap (R4m, R8m) or a
+relink (§4.4), stayed in `/etc/resolv.conf` until NM restarted. NM merges
+every entry into the file by priority without checking that its link
+exists, so a leaked server came first and its domain became a search
+domain; each lookup would first wait out the resolver timeout (5 s in
+glibc), and query names would leave over the uplink (untested). A refused
+profile sends NM no DNS, so this no longer happens. With resolved and
+`all`, a leaked entry keeps claiming `~.`, so the uplink stays without DNS
+servers until NM restarts **[src]**, untested. The give-up order in §4.4
+is therefore required, not cosmetic.
### 4.6 Fail-closed guard
@@ -1904,8 +1917,9 @@ Later, also propose a hook for an externally provided firewall helper
all worked. Two bugs found there are fixed: `nm-sshuttle check` read
`nmcli -g`'s escaped output and rejected every profile, and reconnects
failed when the jump host's name lay in the tunnelled domain (M2-29).
- Still to do: resolv.conf without resolved, which needs a Debian or
- Ubuntu VM. M2-28 (suspend in the VM) remains opt-in.
+ resolv.conf without resolved is settled by refusing DNS there (§4.5);
+ that refusal still needs a run on a Debian or Ubuntu VM. M2-28
+ (suspend in the VM) remains opt-in.
The full scope: persistence, reconnect and backoff, sleep, roaming,
guard, sweeper, startup and `ExecStopPost` cleanup, the unmanaged
`nmss0` setting and its check, health checks and unit tests. The park
@@ -1919,7 +1933,7 @@ Later, also propose a hook for an externally provided firewall helper
and install-checked in CI; the [user guide](user-guide.md) and the
README; and the VM tests in CI, on demand and weekly, on hosted runners
with KVM (about 12 min). Suspend and the GNOME checks passed by hand
- on a notebook; DNS without resolved stays open under M2.
+ on a notebook. DNS without resolved is refused at `Connect` (§4.5).
5. **Later (all four implemented):** GTK4 editor plugin for GNOME Settings,
several tunnels at once (template units), UDP through `tproxy`, IPv6
guard sets. Each has a design in [`later/`](later/README.md). **IPv6 is in:** IPv6 subnets
diff --git a/docs/user-guide.md b/docs/user-guide.md
index f4d0765..db3ba45 100644
--- a/docs/user-guide.md
+++ b/docs/user-guide.md
@@ -14,7 +14,9 @@ it.
- Fedora 43 or 44, Debian 13 or Ubuntu 26.04, with NetworkManager 1.42 or
later, nftables and sshuttle 1.3.1 or later. systemd-resolved is needed
- for the tunnel's DNS (`dns split` or `all`).
+ for the tunnel's DNS (`dns split` or `all`), with `/etc/resolv.conf`
+ linked to its stub: otherwise lookups would go to the local network's
+ resolver whenever the tunnel is down, and such a profile is refused.
- SSH access to a host on the far side that has Python 3. sshuttle needs
nothing else there and no root.
- A key that logs you in without a password prompt from ssh itself: a key
@@ -237,6 +239,17 @@ Common causes:
- **The journal says `nmss0` is managed:** the setting in
`/usr/lib/NetworkManager/conf.d/90-nm-sshuttle.conf` is overridden or
not loaded. Switch the VPN off and run `sudo nm-sshuttle post-install`.
+- **"dns=split needs NetworkManager to use systemd-resolved":** install
+ and enable systemd-resolved, and let NetworkManager use it (its `dns`
+ setting, or `/etc/resolv.conf` linked to resolved's stub). `check`
+ reports it too.
+- **"dns=split needs every lookup to go to systemd-resolved":**
+ `/etc/resolv.conf` lists other servers than resolved's stub
+ `127.0.0.53`, for example because it links to
+ `/run/systemd/resolve/resolv.conf`, resolved's list of the real servers.
+ Programs then ask those servers directly, and fall back to the local
+ network's when the tunnel is down. Link it to the stub:
+ `sudo ln -sf ../run/systemd/resolve/stub-resolv.conf /etc/resolv.conf`.
- **`check` warns about `ipv6.auto-route-ext-gw`:** the profile was made
before IPv6 support. Run the `nmcli connection modify` command it
prints.
diff --git a/nm_sshuttle/cli.py b/nm_sshuttle/cli.py
index 317fbff..3a4dff1 100644
--- a/nm_sshuttle/cli.py
+++ b/nm_sshuttle/cli.py
@@ -31,8 +31,8 @@
import sys
from . import claims, guard, profile, tunnel
-from .const import (SERVICE_TYPE, SLOTS, V1_GUARD_TABLE, V1_PLUGIN_UNIT, V1_TUNNEL_SPEC,
- V1_TUNNEL_UNIT, Slot, slot_number)
+from .const import (NM_DNS_IFACE, NM_DNS_PATH, NM_NAME, SERVICE_TYPE, SLOTS, V1_GUARD_TABLE,
+ V1_PLUGIN_UNIT, V1_TUNNEL_SPEC, V1_TUNNEL_UNIT, Slot, slot_number)
log = logging.getLogger("nm-sshuttle")
@@ -280,8 +280,19 @@ def active_conflict(uuid, prof, hops, nmcli, ssh_g):
return claims.conflict(claims.make_claim(prof, hops), others)
+def nm_dns_mode(run=subprocess.run):
+ """NetworkManager's DNS mode (systemd-resolved, default, dnsmasq, none), or None."""
+ try:
+ p = run(["busctl", "--system", "get-property", NM_NAME, NM_DNS_PATH, NM_DNS_IFACE,
+ "Mode"], capture_output=True, text=True, timeout=10)
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ m = re.fullmatch(r's "(.*)"', p.stdout.strip()) if p.returncode == 0 else None
+ return m.group(1) if m else None
+
+
def check(args, nmcli=nmcli_run, ssh_g=ssh_g_as_self, run=subprocess.run,
- iptables_available=None):
+ iptables_available=None, dns_mode=None, resolv_conf=None):
"""Check a profile as the user it belongs to (design §4.2, §4.3).
Returns 0 when everything passes. The test login may prompt for a host key
@@ -299,6 +310,21 @@ def check(args, nmcli=nmcli_run, ssh_g=ssh_g_as_self, run=subprocess.run,
if prof.method == "tproxy" and not (iptables_available or tunnel.iptables_available)():
print("FAIL method=tproxy needs iptables and ip6tables; install iptables")
return 1
+ if prof.dns != "none":
+ # The plugin refuses it too (design §4.5): unless every lookup goes to
+ # resolved, they fall back to the LAN's resolver whenever the tunnel is down.
+ mode = (dns_mode or nm_dns_mode)()
+ if mode is None:
+ print("WARN cannot read NetworkManager's DNS mode; dns=split and dns=all need "
+ "systemd-resolved")
+ elif mode != "systemd-resolved":
+ print(f"FAIL dns={prof.dns} needs NetworkManager to use systemd-resolved; its DNS "
+ f"mode is {mode}")
+ return 1
+ why = (resolv_conf or tunnel.resolv_conf_problem)()
+ if why:
+ print(f"FAIL dns={prof.dns} needs every lookup to go to systemd-resolved; {why}")
+ return 1
if settings["ipv6"]["auto-route-ext-gw"] != "no":
# Profiles added before IPv6 support lack it; NM then adds a host route
# towards an IPv6 first hop (docs/later/ipv6.md).
diff --git a/nm_sshuttle/const.py b/nm_sshuttle/const.py
index b993dab..4dc718b 100644
--- a/nm_sshuttle/const.py
+++ b/nm_sshuttle/const.py
@@ -15,6 +15,8 @@
NM_DEVICE_IFACE = "org.freedesktop.NetworkManager.Device"
NM_IP4_IFACE = "org.freedesktop.NetworkManager.IP4Config"
NM_IP6_IFACE = "org.freedesktop.NetworkManager.IP6Config"
+NM_DNS_PATH = "/org/freedesktop/NetworkManager/DnsManager"
+NM_DNS_IFACE = "org.freedesktop.NetworkManager.DnsManager"
SYSTEMD_NAME = "org.freedesktop.systemd1"
SYSTEMD_PATH = "/org/freedesktop/systemd1"
diff --git a/nm_sshuttle/service.py b/nm_sshuttle/service.py
index 6ee1435..979e944 100644
--- a/nm_sshuttle/service.py
+++ b/nm_sshuttle/service.py
@@ -27,7 +27,8 @@
from . import claims, guard, tunnel, watch # noqa: E402
from .const import (BUS_NAME, INVISIBLE_MARK, LIBEXEC, LOGIN_MANAGER_IFACE, # noqa: E402
- LOGIN_NAME, LOGIN_PATH, NM_AC_IFACE, NM_DEVICE_IFACE, NM_NAME, NM_PATH,
+ LOGIN_NAME, LOGIN_PATH, NM_AC_IFACE, NM_DEVICE_IFACE, NM_DNS_IFACE,
+ NM_DNS_PATH, NM_NAME, NM_PATH,
PLUGIN_IFACE, PLUGIN_PATH, STATE_DIR, SYSTEMD_MANAGER_IFACE, SYSTEMD_NAME,
SYSTEMD_PATH, SYSTEMD_UNIT_IFACE, Slot, slot_number)
from .supervisor import Supervisor # noqa: E402
@@ -354,6 +355,13 @@ def find_device(self, iface, done):
self._call(NM_NAME, NM_PATH, NM_NAME, "GetDeviceByIpIface", GLib.Variant("(s)", (iface,)),
"(o)", lambda r, e: done(r[0] if r else None), timeout_ms=1000)
+ def dns_mode(self, done):
+ """NetworkManager's DNS mode, such as systemd-resolved; done(mode, error)."""
+ self._get_property(NM_NAME, NM_DNS_PATH, NM_DNS_IFACE, "Mode", done)
+
+ def resolv_conf_problem(self):
+ return tunnel.resolv_conf_problem()
+
def device_state(self, path, done):
self._get_property(NM_NAME, path, NM_DEVICE_IFACE, "State", lambda v, e: done(v))
diff --git a/nm_sshuttle/supervisor.py b/nm_sshuttle/supervisor.py
index 9ee0158..964fd0a 100644
--- a/nm_sshuttle/supervisor.py
+++ b/nm_sshuttle/supervisor.py
@@ -454,6 +454,32 @@ def _begin_connect(self, settings, sender):
log.info("NetworkManager %s never completed an nbns reconnect here; reconnects "
"will not show in NetworkManager (invisible reconnect)", self.nm_version)
self.invisible = True
+ if p.dns != "none":
+ self.fx.dns_mode(self._callback(self._dns_mode_known, self.activation_id))
+ else:
+ self._find_first_hop()
+
+ def _dns_mode_known(self, aid, mode, error):
+ """dns=split and dns=all need systemd-resolved behind NetworkManager,
+ and every lookup going to resolved's stub: when glibc asks the servers
+ itself, it falls back to the LAN's whenever the guard refuses the VPN's
+ (design §4.5)."""
+ if aid != self.activation_id or self.phase != "connecting":
+ return
+ if mode != "systemd-resolved":
+ why = f"its DNS mode is {mode}" if mode else f"its DNS mode is unknown ({error})"
+ self.give_up(FAIL_CONNECT, f"dns={self.profile.dns} needs NetworkManager to use "
+ f"systemd-resolved, and {why}")
+ return
+ why = self.fx.resolv_conf_problem()
+ if why:
+ self.give_up(FAIL_CONNECT, f"dns={self.profile.dns} needs every lookup to go to "
+ f"systemd-resolved, and {why}")
+ return
+ self._find_first_hop()
+
+ def _find_first_hop(self):
+ p = self.profile
self.fx.find_active_connection(p.uuid,
self._callback(self._on_ac_found, self.activation_id))
if p.gateway:
diff --git a/nm_sshuttle/tunnel.py b/nm_sshuttle/tunnel.py
index 3f00340..d73f3c2 100644
--- a/nm_sshuttle/tunnel.py
+++ b/nm_sshuttle/tunnel.py
@@ -110,6 +110,29 @@ def exec_tunnel(slot=None):
os.execv(sshuttle, argv)
+# systemd-resolved's stub listeners: the full one and the proxy-only one
+RESOLVED_STUBS = ("127.0.0.53", "127.0.0.54")
+
+
+def resolv_conf_problem(path="/etc/resolv.conf"):
+ """None when path sends every lookup to systemd-resolved's stub, else why
+ not (design §4.5). NM's DNS mode is systemd-resolved also when the file
+ links to resolved's list of the real servers, or when NM leaves it alone:
+ glibc then asks the listed servers itself, the LAN's among them."""
+ try:
+ with open(path) as f:
+ servers = [w[1] for w in (line.split() for line in f)
+ if len(w) > 1 and w[0] == "nameserver"]
+ except OSError as e:
+ return f"cannot read {path}: {e.strerror}"
+ others = [s for s in servers if s not in RESOLVED_STUBS]
+ if others:
+ return f"{path} lists {', '.join(others)}, not only resolved's stub {RESOLVED_STUBS[0]}"
+ if not servers:
+ return f"{path} lists no nameserver"
+ return None
+
+
def classify_failure(journal):
"""'login' when the tunnel failed on authentication, else 'connect'."""
return "login" if any(m in journal for m in AUTH_MARKERS) else "connect"
diff --git a/test-vm/README.md b/test-vm/README.md
index 3ecbfb2..58552b9 100644
--- a/test-vm/README.md
+++ b/test-vm/README.md
@@ -21,7 +21,7 @@ slot.
| id | scenario |
|---|---|
-| M2-01 | install: files, SELinux labels, `90-nm-sshuttle.conf` takes effect after `nmcli general reload conf` |
+| 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 |
| 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 |
@@ -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/run.sh b/test-vm/run.sh
index 3cb1caa..1708b59 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
@@ -544,6 +549,23 @@ s_reconnect_connect() {
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"
@@ -1608,6 +1630,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 8585256..785a15d 100644
--- a/tests/fakes.py
+++ b/tests/fakes.py
@@ -66,6 +66,8 @@ 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
@@ -110,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)
diff --git a/tests/test_cli.py b/tests/test_cli.py
index e564ac1..2ac66bb 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -131,6 +131,40 @@ def run(argv):
assert "first hop 192.0.2.7" in out and "WARN" not in out
+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_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_service_dbus.py b/tests/test_service_dbus.py
index e60bd5e..05f7f01 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}", [
@@ -350,6 +357,7 @@ def remove_link(name):
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)
@@ -606,3 +614,12 @@ def test_only_networkmanager_may_call_the_plugin(world, bus):
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"]
diff --git a/tests/test_supervisor.py b/tests/test_supervisor.py
index 21865aa..1877be8 100644
--- a/tests/test_supervisor.py
+++ b/tests/test_supervisor.py
@@ -701,3 +701,37 @@ def test_touch_restarts_the_idle_timer():
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_tunnel.py b/tests/test_tunnel.py
index 577da78..1168be3 100644
--- a/tests/test_tunnel.py
+++ b/tests/test_tunnel.py
@@ -230,3 +230,18 @@ def test_nft_health(monkeypatch):
monkeypatch.setattr(tunnel.subprocess, "run",
lambda *a, **k: subprocess.CompletedProcess(a, 1, "", "denied"))
assert tunnel.nft_health("nft", "nm-sshuttle-guard-0") is None
+
+
+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"))
From 62d271d83468208078bc2ef977f09b46b0076d63 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 23 Oct 2026 16:31:54 +0000
Subject: [PATCH 07/16] fix(tunnel): count only root's listeners for sshuttle's
tables
- the sweep kept an sshuttle table while any user listened on its
port, so a user who bound the port of a table left by a killed
sshuttle received the redirected tunnel traffic and DNS, past the
guard; the health check fell back to every listener when it could not
find the tunnel unit's cgroup
- a listener counts only when uid 0 holds it on 127.0.0.1 or ::1, or
the wildcard address, and only for its own family; the sweep also
keeps a user's listener while sshuttle's root firewall helper runs
below its process, as for an sshuttle the user runs, and warns with
the user ID when it deletes a table under a user's listener
- the unit's cgroup is also found on hybrid and legacy cgroup hosts;
where none holds systemd's units the plugin gives up at the first
health check instead of reconnecting every 10 s, and check warns
- nft_health() needs the tunnel's own ports and has no global fallback
Co-Authored-By: Claude Opus 5.5 (1M context)
---
CHANGELOG.md | 13 ++
docs/design.md | 41 +++++-
docs/later/multiple-tunnels.md | 6 +-
docs/later/tproxy.md | 8 +-
docs/user-guide.md | 10 ++
nm_sshuttle/cli.py | 6 +-
nm_sshuttle/service.py | 8 +-
nm_sshuttle/supervisor.py | 5 +
nm_sshuttle/tunnel.py | 248 +++++++++++++++++++++++++--------
test-vm/README.md | 2 +-
test-vm/run.sh | 12 ++
tests/test_cli.py | 12 +-
tests/test_events.py | 9 ++
tests/test_multi.py | 45 +++---
tests/test_service_dbus.py | 17 ++-
tests/test_tproxy.py | 10 +-
tests/test_tunnel.py | 137 +++++++++++++++---
17 files changed, 475 insertions(+), 114 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a9941c2..5c24111 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,19 @@ uses [semantic versioning](https://semver.org/).
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.
- 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;
diff --git a/docs/design.md b/docs/design.md
index e7da816..a671bca 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -1289,10 +1289,10 @@ Events and what the supervisor does:
- **Health (every 10 s while up)**, from the plugin's own checks; NM's
state is not evidence (see "Activated is not proof"):
- the tunnel unit is active (an unreadable state is no failure);
- - with `method=nft`, sshuttle's nft table exists and a listener holds its
- port; with `method=tproxy`, its mark chain in iptables' `mangle` table
- does, for each tunnelled family, and the plugin's rule and route are
- there (put back if not);
+ - with `method=nft`, sshuttle's nft table exists and a listener of
+ root's in the tunnel unit holds its port (§4.8); with `method=tproxy`,
+ its mark chain in iptables' `mangle` table does, for each tunnelled
+ family, and the plugin's rule and route are there (put back if not);
- the guard table exists (re-install it if something flushed the ruleset).
A gap and the reconfiguration after it check that too, every 10 s,
paused or not, and before each attempt;
@@ -1641,6 +1641,39 @@ minimal path under it; `ip` and `nft` there are untested.
names rely on the bus's default deny of method calls. The policy adds no
deny by interface: one without a destination also refuses every message
that has no interface field, to any service on the bus (dbus-daemon(1)).
+- **Other local users** must not be able to take sshuttle's traffic:
+ - **What counts as a listener.** The sweep and the health check count
+ only TCP listeners of uid 0 on `127.0.0.1` or `::1` (or the wildcard
+ address, as an admin's `--listen` gives), each for its own family; the
+ sweep makes one exception, below. A
+ user's listener on a leftover table's port, or on `127.0.0.2` with the
+ same port, would otherwise keep the table, and the user would receive
+ what it still redirects, past the guard. The health check further
+ counts only the sockets in the tunnel unit's cgroup. It looks for
+ systemd's `system.slice` in cgroup v2 (`/sys/fs/cgroup`), then in the
+ unified hierarchy of a hybrid host (`/sys/fs/cgroup/unified`), then in
+ systemd's own v1 hierarchy (`/sys/fs/cgroup/systemd`). Where none has
+ it, no listener could count, and the plugin gives up at the first
+ health check with that reason rather than drop and reconnect every
+ 10 s; `check` warns about it.
+ - **What the sweep removes.** Every sshuttle table and chain without such
+ a listener, whoever made it. A root listener keeps it, also outside the
+ plugin's units: another tunnel of the plugin keeps its tables, and so
+ does an sshuttle run as root by hand (`sudo sshuttle …`, lab T7c), as
+ long as it listens on loopback or the wildcard. One that listens on
+ another address, such as a LAN gateway's `-l 192.168.1.5:0`, loses
+ them. **An sshuttle a user runs the usual way** listens as that user,
+ and only its firewall helper runs as root, through sudo, below the
+ client. The sweep therefore also counts another user's listener, but
+ only while a process below the one that holds the socket is sshuttle's
+ firewall helper (`--firewall` and `sshuttle` in its command line) with
+ every user ID 0. Only root, or a user whom sudo lets run that helper
+ and who could therefore redirect any traffic anyway, can start one:
+ sudo waiting for a password already has euid 0 but keeps its caller's
+ real user ID. Any other user listener does not count. The tables of a
+ user's `sshuttle --daemon` are lost: the daemon is no longer the
+ helper's ancestor. Each table or chain deleted while a user listens on
+ its port gets a warning in the journal that names the user ID.
- **Claims** count while the process they name has the start time
recorded in the claim (`/proc/PID/stat`), so a process that reuses the
PID never counts. A claim written before start times, during an upgrade,
diff --git a/docs/later/multiple-tunnels.md b/docs/later/multiple-tunnels.md
index 54a2a72..0dea6e5 100644
--- a/docs/later/multiple-tunnels.md
+++ b/docs/later/multiple-tunnels.md
@@ -378,8 +378,10 @@ The design as above, with these results and details:
- **The health check finds the tunnel's own listener through its unit's
cgroup** (`cgroup.procs` of `nm-sshuttle-tunnel@N.service`), not
through `MainPID`, so it does not depend on which process holds the
- socket. Where the cgroup is not at the expected path, it falls back to
- any listener, as v1 did.
+ socket. It finds the cgroup under cgroup v2, a hybrid host's unified
+ hierarchy or systemd's v1 hierarchy. Where none holds systemd's units,
+ the plugin gives up at the first health check; it never falls back to
+ every listener (design §4.8).
- **`list` marks active profiles without their slot:** the claims under
`/run/nm-sshuttle/` are readable by root only.
- **An error while reading or writing the claims fails the activation**,
diff --git a/docs/later/tproxy.md b/docs/later/tproxy.md
index 098c0f2..ea3f4f1 100644
--- a/docs/later/tproxy.md
+++ b/docs/later/tproxy.md
@@ -157,10 +157,10 @@ chains (below).
- **Sweep:** a `tproxy` tunnel's leftovers are iptables chains, not an
nft table. `tunnel.sweep()` also lists `iptables -t mangle -S` and
`ip6tables -t mangle -S`, and for every `sshuttle-[mtd]-PORT` chain
- whose port has no listener it deletes the jump from `OUTPUT` or
- `PREROUTING`, then flushes and deletes the chain. It skips this when
- iptables is missing. It runs through iptables, not nft, so that it also
- works on hosts that use iptables-legacy.
+ whose port has no root listener of that family (design §4.8) it deletes
+ the jump from `OUTPUT` or `PREROUTING`, then flushes and deletes the
+ chain. It skips this when iptables is missing. It runs through iptables,
+ not nft, so that it also works on hosts that use iptables-legacy.
- **Health:** the check that sshuttle's table exists becomes, for
`tproxy`, a check that `sshuttle-m-PORT` exists in `mangle` for each
family the tunnel uses, with a listener on its port, and that the
diff --git a/docs/user-guide.md b/docs/user-guide.md
index db3ba45..51ae7b5 100644
--- a/docs/user-guide.md
+++ b/docs/user-guide.md
@@ -250,6 +250,9 @@ Common causes:
Programs then ask those servers directly, and fall back to the local
network's when the tunnel is down. Link it to the stub:
`sudo ln -sf ../run/systemd/resolve/stub-resolv.conf /etc/resolv.conf`.
+- **`check` warns that no cgroup hierarchy holds systemd's units:** the
+ plugin cannot find the tunnel unit's processes, so it gives up 10 s
+ after connecting. This happens only with an unusual cgroup setup.
- **`check` warns about `ipv6.auto-route-ext-gw`:** the profile was made
before IPv6 support. Run the `nmcli connection modify` command it
prints.
@@ -277,6 +280,13 @@ Common causes:
- The tunnelled networks need a route on your machine; a default route is
enough. On a network without one, the tunnel comes up but connections to
those networks fail.
+- An sshuttle you run yourself next to these tunnels keeps its firewall
+ rules when it runs in the foreground, as root or as a user (whose
+ firewall helper runs through sudo), and listens on `127.0.0.1`, `::1`
+ or the wildcard address, as it does by default. Run with `--daemon` as
+ a user, or listening on another address (`-l 192.168.1.5:0`), it loses
+ them whenever one of these tunnels starts or stops, and its traffic
+ then goes around it. The journal then has a warning from the sweep.
- GNOME Settings can edit these profiles only with the `nm-sshuttle-gnome`
package. `nm-connection-editor` (GTK3) has no editor yet; use the commands
above there.
diff --git a/nm_sshuttle/cli.py b/nm_sshuttle/cli.py
index 3a4dff1..8bfff30 100644
--- a/nm_sshuttle/cli.py
+++ b/nm_sshuttle/cli.py
@@ -292,7 +292,7 @@ def nm_dns_mode(run=subprocess.run):
def check(args, nmcli=nmcli_run, ssh_g=ssh_g_as_self, run=subprocess.run,
- iptables_available=None, dns_mode=None, resolv_conf=None):
+ iptables_available=None, dns_mode=None, resolv_conf=None, cgroup=None):
"""Check a profile as the user it belongs to (design §4.2, §4.3).
Returns 0 when everything passes. The test login may prompt for a host key
@@ -325,6 +325,10 @@ def check(args, nmcli=nmcli_run, ssh_g=ssh_g_as_self, run=subprocess.run,
if why:
print(f"FAIL dns={prof.dns} needs every lookup to go to systemd-resolved; {why}")
return 1
+ if (cgroup or tunnel.unit_cgroup)("nm-sshuttle.service") is None:
+ print("WARN no cgroup hierarchy under /sys/fs/cgroup holds systemd's units: the health "
+ "check cannot tell the tunnel's own listener, and the plugin gives up 10 s after "
+ "it connects")
if settings["ipv6"]["auto-route-ext-gw"] != "no":
# Profiles added before IPv6 support lack it; NM then adds a host route
# towards an IPv6 first hop (docs/later/ipv6.md).
diff --git a/nm_sshuttle/service.py b/nm_sshuttle/service.py
index 979e944..3ac4794 100644
--- a/nm_sshuttle/service.py
+++ b/nm_sshuttle/service.py
@@ -583,10 +583,12 @@ def sweep(self):
tunnel.sweep()
def nft_health(self, method="nft"):
- # Only this tunnel's own listeners count, never another tunnel's.
- snap = tunnel.nft_health(method, self.slot.guard_table,
- tunnel.unit_ports(self.tunnel_unit))
+ # Only this tunnel's own listeners count, never another tunnel's or
+ # another user's (design §4.8).
+ ports = tunnel.unit_ports(self.tunnel_unit)
+ snap = tunnel.nft_health(method, self.slot.guard_table, ports or {})
if snap is not None:
+ snap["cgroup"] = ports is not None
snap["ssh"] = tunnel.unit_runs(self.tunnel_unit, "ssh")
return snap
diff --git a/nm_sshuttle/supervisor.py b/nm_sshuttle/supervisor.py
index 964fd0a..f285758 100644
--- a/nm_sshuttle/supervisor.py
+++ b/nm_sshuttle/supervisor.py
@@ -1120,6 +1120,11 @@ def _health(self, hid):
method = self.profile.method
snap = self.fx.nft_health(method)
if snap is not None:
+ if snap.get("cgroup") is False:
+ # It would drop the tunnel every 10 s (design §4.8).
+ self.give_up(FAIL_CONNECT, "health: no cgroup hierarchy under /sys/fs/cgroup "
+ "holds systemd's units, so no listener counts as the tunnel's own")
+ return
if self.profile.fail_closed and not snap["guard"]:
if not self._restore_guard("while up"):
return
diff --git a/nm_sshuttle/tunnel.py b/nm_sshuttle/tunnel.py
index d73f3c2..645050b 100644
--- a/nm_sshuttle/tunnel.py
+++ b/nm_sshuttle/tunnel.py
@@ -11,10 +11,12 @@
import shutil
import socket
import stat
+import struct
import subprocess
import sys
import threading
+from .claims import runs_as_root
from .const import LIBEXEC, SSH_CONFIG, V1_TUNNEL_SPEC, Slot
from .profile import collapse, family
@@ -328,43 +330,145 @@ def write_ssh_config(text, path=SSH_CONFIG):
# ------------------------------------------------------------------ sweep
-def listening_ports(proc_files=("/proc/net/tcp", "/proc/net/tcp6"), inodes=None):
- """Ports with a TCP listener; with inodes, only those of these sockets."""
- ports = set()
- for path in proc_files:
+# Where sshuttle listens: loopback, or the wildcard with an admin's --listen.
+LISTEN_ADDRESSES = {4: {"127.0.0.1", "0.0.0.0"}, 6: {"::1", "::"}}
+
+
+def proc_address(text):
+ """An address from /proc/net/tcp{,6}: 32-bit words in host byte order."""
+ raw = b"".join(struct.pack("=I", int(text[i:i + 8], 16)) for i in range(0, len(text), 8))
+ return socket.inet_ntop(socket.AF_INET if len(raw) == 4 else socket.AF_INET6, raw)
+
+
+def loopback_listeners(proc="/proc"):
+ """The TCP listeners on the address sshuttle listens on, as (family, port,
+ uid, socket inode)."""
+ out = []
+ for version, name in ((4, "net/tcp"), (6, "net/tcp6")):
try:
- with open(path) as f:
+ with open(os.path.join(proc, name)) as f:
next(f, None)
for line in f:
fields = line.split()
- if len(fields) > 3 and fields[3] == "0A" and ( # TCP_LISTEN
- inodes is None or (len(fields) > 9 and fields[9] in inodes)):
- ports.add(int(fields[1].rsplit(":", 1)[1], 16))
+ if len(fields) < 10 or fields[3] != "0A": # TCP_LISTEN
+ continue
+ addr, _, port = fields[1].rpartition(":")
+ try:
+ if proc_address(addr) in LISTEN_ADDRESSES[version]:
+ out.append((version, int(port, 16), int(fields[7]), fields[9]))
+ except (ValueError, OSError, struct.error):
+ continue
except OSError:
pass
+ return out
+
+
+def listening_ports(proc="/proc", inodes=None):
+ """{4: ports, 6: ports}: the ports root listens on for TCP, on the
+ address sshuttle listens on; with inodes, only those of these sockets.
+
+ Another user's listener never counts (design §4.8): one on the port of a
+ leftover table would receive what that table still redirects."""
+ ports = {4: set(), 6: set()}
+ for version, port, uid, inode in loopback_listeners(proc):
+ if uid == 0 and (inodes is None or inode in inodes):
+ ports[version].add(port)
+ return ports
+
+
+def _firewall_helper(pid, proc):
+ """Whether pid is sshuttle's firewall helper, run as root."""
+ try:
+ with open(os.path.join(proc, str(pid), "cmdline"), "rb") as f:
+ args = f.read().split(b"\0")
+ except OSError:
+ return False
+ return (b"--firewall" in args and any(b"sshuttle" in a for a in args)
+ and runs_as_root(pid, proc))
+
+
+def user_sshuttle_ports(listeners, proc="/proc"):
+ """{4: ports, 6: ports}: those of listeners whose process has sshuttle's
+ firewall helper, run as root, among its descendants: an sshuttle a user
+ runs, with its helper through sudo (design §4.8). Only root, or a user
+ whom sudo lets run that helper, can start one: sudo waiting for a
+ password still has the caller's real user ID."""
+ inodes = {inode: (version, port) for version, port, _, inode in listeners}
+ parent, holders, helpers = {}, {}, []
+ try:
+ pids = [int(name) for name in os.listdir(proc) if name.isdigit()]
+ except OSError:
+ pids = []
+ for pid in pids:
+ base = os.path.join(proc, str(pid))
+ try:
+ with open(os.path.join(base, "stat")) as f:
+ text = f.read()
+ parent[pid] = int(text[text.rindex(")") + 2:].split()[1])
+ fds = os.listdir(os.path.join(base, "fd"))
+ except (OSError, ValueError, IndexError):
+ continue
+ for fd in fds:
+ try:
+ target = os.readlink(os.path.join(base, "fd", fd))
+ except OSError:
+ continue
+ if target.startswith("socket:[") and target[8:-1] in inodes:
+ holders.setdefault(pid, set()).add(inodes[target[8:-1]])
+ if _firewall_helper(pid, proc):
+ helpers.append(pid)
+ ancestors = set()
+ for pid in helpers:
+ pid = parent.get(pid)
+ while pid and pid not in ancestors:
+ ancestors.add(pid)
+ pid = parent.get(pid)
+ ports = {4: set(), 6: set()}
+ for pid in ancestors & holders.keys():
+ for version, port in holders[pid]:
+ ports[version].add(port)
return ports
-def unit_cgroup(unit, root="/sys/fs/cgroup"):
+# Where systemd's units are: cgroup v2; the unified hierarchy of a hybrid
+# host; systemd's own name=systemd hierarchy on a legacy (v1) host.
+CGROUP_ROOTS = ("/sys/fs/cgroup", "/sys/fs/cgroup/unified", "/sys/fs/cgroup/systemd")
+
+
+def unit_cgroup(unit, roots=CGROUP_ROOTS):
"""Where systemd puts a system service's processes: a template instance
- sits in its template's slice."""
+ sits in its template's slice. None when no hierarchy holds system.slice."""
+ root = next((r for r in roots if os.path.isdir(os.path.join(r, "system.slice"))), None)
+ if root is None:
+ return None
if "@" in unit:
template = unit.split("@", 1)[0].replace("-", "\\x2d")
return os.path.join(root, "system.slice", f"system-{template}.slice", unit)
return os.path.join(root, "system.slice", unit)
-def unit_runs(unit, comm, root="/sys/fs/cgroup", proc="/proc"):
- """Does a process of this unit have the command name comm? sshuttle 1.3
- can outlive its ssh, listening on with nothing behind it. None when the
- unit's cgroup is not where it is expected."""
+def unit_pids(unit, roots=CGROUP_ROOTS):
+ """The processes of this unit, [] once it has stopped, or None when
+ systemd's cgroups cannot be found."""
+ cgroup = unit_cgroup(unit, roots)
+ if cgroup is None:
+ return None
try:
- with open(os.path.join(unit_cgroup(unit, root), "cgroup.procs")) as f:
- pids = f.read().split()
+ with open(os.path.join(cgroup, "cgroup.procs")) as f:
+ return f.read().split()
except FileNotFoundError:
- return None if not os.path.isdir(os.path.dirname(unit_cgroup(unit, root))) else False
+ return [] # systemd removed the cgroup, and an empty slice's
except OSError:
return None
+
+
+def unit_runs(unit, comm, roots=CGROUP_ROOTS, proc="/proc"):
+ """Does a process of this unit have the command name comm? sshuttle 1.3
+ can outlive its ssh, listening on with nothing behind it. None when
+ systemd's cgroups cannot be found."""
+ pids = unit_pids(unit, roots)
+ if pids is None:
+ return None
for pid in pids:
try:
with open(os.path.join(proc, pid, "comm")) as f:
@@ -375,16 +479,12 @@ def unit_runs(unit, comm, root="/sys/fs/cgroup", proc="/proc"):
return False
-def unit_ports(unit, root="/sys/fs/cgroup", proc="/proc"):
- """The TCP ports processes of this unit listen on: one tunnel's own
- sshuttle, never another's (docs/later/multiple-tunnels.md). None when
- the unit's cgroup is not where it is expected."""
- try:
- with open(os.path.join(unit_cgroup(unit, root), "cgroup.procs")) as f:
- pids = f.read().split()
- except FileNotFoundError:
- return None if not os.path.isdir(os.path.dirname(unit_cgroup(unit, root))) else set()
- except OSError:
+def unit_ports(unit, roots=CGROUP_ROOTS, proc="/proc"):
+ """The ports processes of this unit listen on, as listening_ports: one
+ tunnel's own sshuttle, never another's (docs/later/multiple-tunnels.md).
+ None when systemd's cgroups cannot be found."""
+ pids = unit_pids(unit, roots)
+ if pids is None:
return None
inodes = set()
for pid in pids:
@@ -400,8 +500,7 @@ def unit_ports(unit, root="/sys/fs/cgroup", proc="/proc"):
continue
if target.startswith("socket:["):
inodes.add(target[8:-1])
- return listening_ports((os.path.join(proc, "net/tcp"), os.path.join(proc, "net/tcp6")),
- inodes)
+ return listening_ports(proc, inodes)
def inet_tables(nft_list_tables):
@@ -415,17 +514,18 @@ def inet_tables(nft_list_tables):
def sshuttle_tables(nft_list_tables, ports, live):
- """sshuttle tables whose redirect port has a listener (live) or none (stale)."""
+ """sshuttle tables whose redirect port has a listener of their family
+ (live) or none (stale); ports as listening_ports returns them."""
out = []
for name in inet_tables(nft_list_tables):
m = SSHUTTLE_TABLE_RE.match(name)
- if m and (int(m.group(2)) in ports) == live:
+ if m and (int(m.group(2)) in ports.get(int(m.group(1)), ())) == live:
out.append(name)
return out
def stale_tables(nft_list_tables, ports):
- """sshuttle tables whose redirect port has no listener (lab T7c)."""
+ """sshuttle tables whose redirect port has no root listener (lab T7c)."""
return sshuttle_tables(nft_list_tables, ports, live=False)
@@ -443,8 +543,9 @@ def mangle_chains(iptables_s):
def stale_chain_commands(iptables_s, ports):
"""The iptables arguments that remove the sshuttle chains whose port has no
- listener: the jumps from OUTPUT and PREROUTING first, then flush every
- chain, then delete them (the t-chain jumps to the d-chain)."""
+ listener among ports, those of the listing's family: the jumps from
+ OUTPUT and PREROUTING first, then flush every chain, then delete them
+ (the t-chain jumps to the d-chain)."""
stale = [c for c, port in mangle_chains(iptables_s).items() if port not in ports]
cmds = []
for line in iptables_s.splitlines():
@@ -473,12 +574,13 @@ def _mangle(family):
return p.stdout if p.returncode == 0 else None
-def nft_health(method, guard_table, ports=None):
+def nft_health(method, guard_table, ports):
"""What the health check reads from the firewall (design §4.4, "Health"):
is the guard table there, and for which families (4, 6) does sshuttle have
its rules with a listener on their port? Those are a table in nft, or for
- method=tproxy a mark chain in iptables' mangle table. ports limits it to
- this tunnel's own listeners. None when nft cannot be asked."""
+ method=tproxy a mark chain in iptables' mangle table. ports are this
+ tunnel's own listeners, as unit_ports returns them. None when nft cannot
+ be asked."""
try:
p = subprocess.run(["nft", "list", "tables"], capture_output=True, text=True,
timeout=10)
@@ -486,13 +588,12 @@ def nft_health(method, guard_table, ports=None):
return None
if p.returncode:
return None
- if ports is None:
- ports = listening_ports()
if method == "tproxy":
families = set()
for version in IPTABLES:
chains = mangle_chains(_mangle(version) or "")
- if any(c.startswith("sshuttle-m-") and port in ports for c, port in chains.items()):
+ if any(c.startswith("sshuttle-m-") and port in ports.get(version, ())
+ for c, port in chains.items()):
families.add(version)
else:
live = sshuttle_tables(p.stdout, ports, live=True)
@@ -500,36 +601,73 @@ def nft_health(method, guard_table, ports=None):
return {"guard": guard_table in inet_tables(p.stdout), "sshuttle": families}
-def sweep():
- """Delete sshuttle tables and chains left by a killed tunnel; they only
- black-hole traffic."""
+def sweep(proc="/proc"):
+ """Delete sshuttle tables and chains left by a killed tunnel (lab T7).
+
+ A table or chain is live while root listens on its port, on 127.0.0.1 for
+ IPv4 or ::1 for IPv6 (or the wildcard), whichever tunnel unit holds it: a
+ tunnel's sweep must spare the other tunnels, and an sshuttle run as root
+ outside the plugin. Another user's listener keeps it only while sshuttle's
+ root firewall helper runs below that listener's process, as for an
+ sshuttle the user runs; any other listener would receive the redirected
+ traffic (design §4.8)."""
try:
out = subprocess.run(["nft", "list", "tables"], capture_output=True, text=True,
timeout=10).stdout
except (OSError, subprocess.TimeoutExpired) as e:
log.warning("sweep: cannot list nft tables: %s", e)
out = ""
- ports = listening_ports()
+ # method=tproxy leaves iptables chains; through iptables, so that this also
+ # works with iptables-legacy (docs/later/tproxy.md).
+ listings = {}
+ for version, cmd in IPTABLES.items():
+ if shutil.which(cmd, path=SEARCH_PATH):
+ listing = _mangle(version)
+ if listing is not None:
+ listings[version] = listing
+ listeners = loopback_listeners(proc)
+ ports = {4: set(), 6: set()}
+ users = {}
+ for version, port, uid, _ in listeners:
+ if uid == 0:
+ ports[version].add(port)
+ else:
+ users.setdefault((version, port), set()).add(uid)
+ stale = {(int(m.group(1)), int(m.group(2))) for m in
+ (SSHUTTLE_TABLE_RE.match(t) for t in stale_tables(out, ports)) if m}
+ stale |= {(version, port) for version, listing in listings.items()
+ for port in mangle_chains(listing).values() if port not in ports[version]}
+ held = [x for x in listeners if x[2] != 0 and (x[0], x[1]) in stale]
+ if held:
+ for version, kept in user_sshuttle_ports(held, proc).items():
+ ports[version] |= kept
+
+ def deleted(what, version, port):
+ uids = users.get((version, port))
+ if uids:
+ log.warning("sweep: deleted %s although uid %s listens on its port, without "
+ "sshuttle's root firewall helper below it; an sshuttle run that way "
+ "has lost its rules (design §4.8)", what,
+ ", ".join(str(u) for u in sorted(uids)))
+ else:
+ log.info("sweep: deleted stale %s", what)
+
for table in stale_tables(out, ports):
p = subprocess.run(["nft", "delete", "table", "inet", table], capture_output=True,
text=True, timeout=10)
if p.returncode == 0:
- log.info("sweep: deleted stale table %s", table)
+ m = SSHUTTLE_TABLE_RE.match(table)
+ deleted(f"table {table}", int(m.group(1)), int(m.group(2)))
else:
log.warning("sweep: cannot delete %s: %s", table, p.stderr.strip())
- # method=tproxy leaves iptables chains; through iptables, so that this also
- # works with iptables-legacy (docs/later/tproxy.md).
- for version, cmd in IPTABLES.items():
- if not shutil.which(cmd, path=SEARCH_PATH):
- continue
- listing = _mangle(version)
- if listing is None:
- continue
- for args in stale_chain_commands(listing, ports):
+ for version, listing in listings.items():
+ cmd = IPTABLES[version]
+ chains = mangle_chains(listing)
+ for args in stale_chain_commands(listing, ports[version]):
p = subprocess.run([cmd, "-w", "-t", "mangle", *args], capture_output=True,
text=True, timeout=10)
if p.returncode:
log.warning("sweep: %s -t mangle %s: %s", cmd, " ".join(args),
p.stderr.strip())
elif args[0] == "-X":
- log.info("sweep: deleted stale chain %s (IPv%d)", args[1], version)
+ deleted(f"chain {args[1]} (IPv{version})", version, chains[args[1]])
diff --git a/test-vm/README.md b/test-vm/README.md
index 58552b9..8d13b7a 100644
--- a/test-vm/README.md
+++ b/test-vm/README.md
@@ -34,7 +34,7 @@ slot.
| M2-11 | Connect right after Disconnect: a new instance serves it |
| 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 |
diff --git a/test-vm/run.sh b/test-vm/run.sh
index 1708b59..d8edd19 100755
--- a/test-vm/run.sh
+++ b/test-vm/run.sh
@@ -647,6 +647,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
}
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 2ac66bb..bbd7703 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -125,7 +125,8 @@ 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,
+ 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
@@ -164,6 +165,15 @@ def run(argv, **kw):
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,
+ 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_reads_escaped_fields(dennis, capsys):
data = "remote = corp, local-user = dennis, subnets = 10.0.0.0/8, probe = 10.1.0.22:22"
diff --git a/tests/test_events.py b/tests/test_events.py
index 110b438..aa8b483 100644
--- a/tests/test_events.py
+++ b/tests/test_events.py
@@ -322,6 +322,15 @@ 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_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
diff --git a/tests/test_multi.py b/tests/test_multi.py
index e602b1b..5128a5f 100644
--- a/tests/test_multi.py
+++ b/tests/test_multi.py
@@ -258,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))
@@ -272,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):
@@ -306,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
-
-
-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")
+ assert tunnel.unit_runs(unit, "ssh", (str(tmp_path / "elsewhere"),), proc) is None
+
+
+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
diff --git a/tests/test_service_dbus.py b/tests/test_service_dbus.py
index 05f7f01..6f09173 100644
--- a/tests/test_service_dbus.py
+++ b/tests/test_service_dbus.py
@@ -351,7 +351,7 @@ 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)
@@ -623,3 +623,18 @@ def test_split_dns_needs_resolved_behind_networkmanager(world):
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()}
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 1168be3..9c9eeae 100644
--- a/tests/test_tunnel.py
+++ b/tests/test_tunnel.py
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: MIT
+import os
import socket
import subprocess
import time
@@ -201,35 +202,131 @@ 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}
+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()}
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
def test_resolv_conf_must_point_at_resolveds_stub(tmp_path):
From 98f15500bd5c79100ced4aa8b9457fbaf56d7b9f Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 23 Oct 2026 16:31:58 +0000
Subject: [PATCH 08/16] fix(tunnel): listen on a redirect port that only root
can bind
- sshuttle took the first free port from 12300 down, which any user can
bind; holding all 3300 of them stopped every tunnel from starting
- exec-tunnel passes --listen 127.0.0.1:P with P from 225 to 240, below
ip_unprivileged_port_start: the slot's own two ports first, then the
others, so that TIME_WAIT after quick restarts does not block a slot;
the test bind skips SO_REUSEADDR, as sshuttle does
- sshuttle 1.3.1 and 2.0.0 crash when --listen gives both families a
port, so ::1 gets port 0; the IPv6 and DNS ports stay sshuttle's
choice, and the plugin says when sshuttle found none of them free
- exec-tunnel and check warn when the sysctl lets users bind the ports
- the sshuttle upstream draft gets the crash and a request for an
option for the DNS port
Co-Authored-By: Claude Opus 5.5 (1M context)
---
CHANGELOG.md | 9 ++++
docs/design.md | 47 +++++++++++++++--
docs/later/ipv6.md | 10 ++--
docs/later/multiple-tunnels.md | 5 ++
docs/upstream/README.md | 2 +-
docs/upstream/sshuttle.md | 26 +++++++++-
docs/user-guide.md | 9 ++++
nm_sshuttle/cli.py | 13 +++--
nm_sshuttle/const.py | 14 +++++
nm_sshuttle/supervisor.py | 8 ++-
nm_sshuttle/tunnel.py | 71 +++++++++++++++++++++++--
test-vm/README.md | 4 +-
test-vm/lib.sh | 21 ++++++++
test-vm/run.sh | 16 ++++++
tests/test_cli.py | 12 ++++-
tests/test_events.py | 11 ++++
tests/test_tunnel.py | 95 +++++++++++++++++++++++++++++++++-
17 files changed, 349 insertions(+), 24 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c24111..20f63cc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,15 @@ uses [semantic versioning](https://semver.org/).
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;
diff --git a/docs/design.md b/docs/design.md
index a671bca..f06a2af 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
@@ -1608,7 +1614,8 @@ lets the helper finish and still removes ssh is a lab question.
**Sandboxing** such as `ProtectSystem=strict`, `PrivateTmp`,
`RestrictAddressFamilies` and a capability bounding set (`CAP_NET_ADMIN`,
-`CAP_SETUID`, `CAP_SETGID`) is added and tested one directive at a time.
+`CAP_NET_BIND_SERVICE` for the redirect port of §4.8, `CAP_SETUID`,
+`CAP_SETGID`) is added and tested one directive at a time.
The ssh child inherits the sandbox, and it must still read `~/.ssh` and
write `known_hosts`.
@@ -1642,6 +1649,37 @@ minimal path under it; `ip` and `nft` there are untested.
deny by interface: one without a destination also refuses every message
that has no interface field, to any service on the bus (dbus-daemon(1)).
- **Other local users** must not be able to take sshuttle's traffic:
+ - **The redirect port.** Without `--listen`, sshuttle takes the first free
+ port from 12300 down, which any user may bind first, all 3300 of them.
+ The plugin's tunnels therefore listen on ports 225 to 240, below
+ `net.ipv4.ip_unprivileged_port_start` (1024 by default), so only root
+ may bind them. IANA has not assigned 225 to 241, so no standard service
+ listens there. `exec-tunnel` passes `--listen 127.0.0.1:PORT` with the
+ first port it can bind, in the slot's order: its own two, 225 + 2N and
+ 226 + 2N, then the others from 240 down, which belong to the slots used
+ least. A connection that sshuttle closes first, as when the far end
+ closes it or sshuttle stops with it open, leaves its port in TIME_WAIT
+ for 60 s, and sshuttle binds without `SO_REUSEADDR` (lab T8). So two
+ quick stops of a slot can take both its own ports for a minute.
+ Two slots that start at the same moment can pick the same spare port;
+ one sshuttle then fails with `EADDRINUSE`, as it does when all 16 are
+ taken: a failed start, which fails a `Connect` and is retried in a
+ gap. A lower `ip_unprivileged_port_start` gets a warning in the
+ tunnel's journal and from `check`, and the tunnel still starts.
+ - **Still searched:** the IPv6 redirect port (`[::1]:0`, §2.2) and the
+ DNS port. A user who holds all 3300 ports on `::1`, or all UDP ones,
+ can still stop such a tunnel from starting. It fails closed. A user can
+ also bind either port once sshuttle's socket is gone. If sshuttle's
+ helper then failed to delete its tables, that user receives the
+ redirected IPv6 TCP, or the DNS lookups (and can answer them), until
+ the tunnel unit's `ExecStopPost` sweep removes the tables: up to its
+ 15 s `TimeoutStopSec` after a hung helper. The DNS port has no
+ TIME_WAIT, so a user who waits for it always wins that race. Both
+ ports need upstream changes, which are worth proposing with the
+ `--listen` fix (§6). When sshuttle stops with `EADDRINUSE`, the plugin
+ says which port it found none for, from sshuttle's journal: "no free
+ port for sshuttle's DNS redirector (9001-12300); another user may be
+ holding them", or the same for IPv6.
- **What counts as a listener.** The sweep and the health check count
only TCP listeners of uid 0 on `127.0.0.1` or `::1` (or the wildcard
address, as an admin's `--listen` gives), each for its own family; the
@@ -1845,8 +1883,9 @@ to 2026-10-10).
- GNOME Shell: a VPN plugin without `auth-dialog` leaves secrets requests
unanswered;
- sshuttle: the `connect()` crash in server-side DNS forwarding (lab T9),
- `SO_REUSEADDR` on the listener (lab T6, T8), and automatic exclusion
- ignoring `-e` (lab T2).
+ `SO_REUSEADDR` on the listener (lab T6, T8), automatic exclusion
+ ignoring `-e` (lab T2), the `UnboundLocalError` when `--listen` gives
+ both families a port (§2.2), and no option for the DNS port (§4.8).
Later, also propose a hook for an externally provided firewall helper
(§4.8).
diff --git a/docs/later/ipv6.md b/docs/later/ipv6.md
index bf61f9d..f9258a3 100644
--- a/docs/later/ipv6.md
+++ b/docs/later/ipv6.md
@@ -174,10 +174,12 @@ reached over IPv6.
### Health
`nft_health()` reports whether a sshuttle table with a live listener
-exists. With IPv6 tunnelled, sshuttle has two tables with the same port.
-The check asks for each family it expects: `sshuttle-ipv4-P` when there is
-an IPv4 network, `sshuttle-ipv6-P` when IPv6 is tunnelled. A missing one
-is a drop, as now.
+exists. With IPv6 tunnelled, sshuttle has two tables. The check asks for
+each family it expects: `sshuttle-ipv4-P` when there is an IPv4 network,
+`sshuttle-ipv6-Q` when IPv6 is tunnelled, each with root's listener of that
+family on its port. A missing one is a drop, as now. P and Q differ since
+the plugin passes the IPv4 port: `--listen 127.0.0.1:P,[::1]:0`, because
+sshuttle fails when both families get a port (design §2.2, §4.8).
### Why no IPv6 DNS servers
diff --git a/docs/later/multiple-tunnels.md b/docs/later/multiple-tunnels.md
index 0dea6e5..566def8 100644
--- a/docs/later/multiple-tunnels.md
+++ b/docs/later/multiple-tunnels.md
@@ -382,6 +382,11 @@ The design as above, with these results and details:
hierarchy or systemd's v1 hierarchy. Where none holds systemd's units,
the plugin gives up at the first health check; it never falls back to
every listener (design §4.8).
+- **Each slot has its own redirect ports,** 225 + 2N and 226 + 2N for
+ IPv4, and takes a free one of the other slots' ports, from 240 down,
+ when TIME_WAIT holds both of its own (design §4.8). A table's port
+ therefore does not name its slot; the health check goes by the cgroup.
+ The IPv6 port is still sshuttle's own choice.
- **`list` marks active profiles without their slot:** the claims under
`/run/nm-sshuttle/` are readable by root only.
- **An error while reading or writing the claims fails the activation**,
diff --git a/docs/upstream/README.md b/docs/upstream/README.md
index 5f0f712..c107030 100644
--- a/docs/upstream/README.md
+++ b/docs/upstream/README.md
@@ -11,7 +11,7 @@ in the source, and what was never run.
| [NetworkManager: SIGSEGV when a plugin recreates its tundev](networkmanager-vpn-tundev-crash.md) | NetworkManager, [gitlab.freedesktop.org](https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/issues); also Fedora's NetworkManager-1.56.1-2.fc44 | Never recreate `nmss0` while NM holds the VPN (waiting for NM's device avoided the crash in a later run, but the VPN still lost its DNS) | Search for duplicates (`_check_complete`, `check_device_added_idle_source`, RHEL-125796, MR !2347). Run the held reproducer once on a Fedora 44 VM with the packaged NM; so far it ran only in a sandbox. A third Fedora run re-created the link after waiting for NM's device and did not crash (see the draft's workaround). |
| [NetworkManager: a reconnect with unchanged config stays "activating"](networkmanager-vpn-reconnect-stuck.md) | NetworkManager, [gitlab.freedesktop.org](https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/issues) | The `nbns` sentinel (design §4.4) | Search for duplicates. The draft now has 1.56.1 traces of the early activation (reapply and link deletion) and says that without firewalld the sentinel commit is a race (runs 5 and 6). Optionally run the reproducer on 1.56. |
| [GNOME Shell: VPN secrets request unanswered without an auth dialog](gnome-shell-vpn-auth-dialog.md) | GNOME Shell, [gitlab.gnome.org](https://gitlab.gnome.org/GNOME/gnome-shell/-/issues) | Ship an auth-dialog stub (design §4.1) | Search for duplicates. "Actual result" now has the Fedora 44 user journal from the third spike run (R5f) and the stub control (R5d). |
-| [sshuttle: three bugs](sshuttle.md): the server dies when `connect()` to the remote resolver fails; no `SO_REUSEADDR` on the listener; automatic exclusion ignores `-e` | sshuttle, [GitHub](https://github.com/sshuttle/sshuttle/issues) | Always pass `--to-ns` and `-x FIRST_HOP` (design §2.2, §4.5) | Check #1069, #89 and #275, which may be the same bugs, and comment there instead if they match. |
+| [sshuttle: four bugs and a request](sshuttle.md): the server dies when `connect()` to the remote resolver fails; no `SO_REUSEADDR` on the listener; automatic exclusion ignores `-e`; `--listen` with a port for both families crashes; no option for the DNS port | sshuttle, [GitHub](https://github.com/sshuttle/sshuttle/issues) | Always pass `--to-ns` and `-x FIRST_HOP` (design §2.2, §4.5); pass only the IPv4 port, from 225 to 240, with spares for TIME_WAIT (design §4.8) | Check #1069, #89 and #275, which may be the same bugs, and comment there instead if they match. Run the section 4 reproducer once. |
**Drafted from run 4, confirmed in runs 5 and 6:** [NetworkManager: VPN DNS left behind or lost](networkmanager-vpn-dns.md). A VPN that fails from "connect" keeps its DNS entry; a relinked tundev gets no DNS; `DnsManager.Configuration` is a stale snapshot; and a tundev's external device entry can take resolved's default route. Spike run 5 confirmed issue 1 with a rebuilt configuration, with systemd-resolved still serving the leaked server on the tundev (R4k-k). It added the plugin-kill path (R4m) and post-`Disconnect` evidence for issue 2 (R4f), and showed that an unmanaged tundev avoids issue 4 (R8c). Run 6 repeated these results, showed the kill leak with the tundev unmanaged (R8m), and added a second unmanaged control for issue 4, in which NetworkManager committed the sentinel (R8j). Before filing: search for duplicates, and run the draft's fake-plugin reproducer once (written, not yet run).
diff --git a/docs/upstream/sshuttle.md b/docs/upstream/sshuttle.md
index 4696ba0..f18ba40 100644
--- a/docs/upstream/sshuttle.md
+++ b/docs/upstream/sshuttle.md
@@ -1,4 +1,4 @@
-# sshuttle 2.0.0: three bug reports
+# sshuttle 2.0.0: four bug reports and a request
We found these while building nm-sshuttle. It runs the sshuttle client as root from a systemd unit, and `ssh` runs as the desktop user through an `-e` wrapper. Each section below is a separate issue and can be filed on its own.
@@ -283,6 +283,30 @@ Lab T2 is our own case:
---
+## 4. `--listen` with a port for both families stops with `UnboundLocalError`
+
+**Versions:** 2.0.0, and 1.3.1 *(from source)*, where the same code sits at `client.py`:1011-1060.
+
+**Reproduce** *(from source)*:
+
+```sh
+sshuttle -v --method nft --listen 127.0.0.1:12345,[::1]:12345 -r user@remote 192.0.2.0/24
+```
+
+**Actual.** The client stops before it starts the firewall helper, with `UnboundLocalError: cannot access local variable 'used_ports'` (Python 3.11 and later; older versions word it differently).
+
+**Expected.** sshuttle listens on the two given ports.
+
+**Root cause** (`sshuttle/client.py`, 2.0.0): when both families have a port (line 1037), `ports = [0, ]` and the `else` branch that sets `used_ports = []` (line 1045) is skipped. The first successful bind then runs `used_ports.append(port)` (line 1086). With one port given and the other `0`, the search runs and nothing fails, which is how nm-sshuttle calls it (`--listen 127.0.0.1:P,[::1]:0`).
+
+**Proposed fix:** set `used_ports = []` before the `if`.
+
+## 5. Request: an option for the DNS redirector's port
+
+The DNS redirector always takes the first free UDP port from 12300 down (`client.py`:1105-1143), even when `--listen` fixes the TCP port. On a machine with other users, any of them can bind those ports first: holding all 3300 stops sshuttle from starting, and binding the port while sshuttle restarts receives the lookups that a leftover rule still redirects. nm-sshuttle runs sshuttle as root and passes a TCP port below 1024 for that reason, but cannot do the same for DNS. The same holds for the IPv6 TCP port while section 4 stands. A `--dns-listen` option, or a DNS port in `--listen`, would close both. Together with section 2 (`SO_REUSEADDR`), it would also let a fixed port be reused right after a restart; nm-sshuttle now gives each tunnel two ports and spares to work around TIME_WAIT.
+
+---
+
## Also seen, not drafted: a traceback when the firewall helper relays a signal to a client that has already exited
On Fedora 44 with sshuttle 1.3.2 under a systemd unit, 6 of 29 stops logged `ProcessLookupError: [Errno 3] No such process` from `firewall_exit()` (`firewall.py`, line 95, `os.kill(sshuttle_pid, sig)`). The rules had already been removed. Each time, the exception was raised while the helper was flushing the DNS cache, so the helper logged it under "Error trying to flush systemd dns cache." and skipped the flush. *(from source)* 2.0.0 has the same unguarded `os.kill()` (`firewall.py`:77-95). Catching `ProcessLookupError` there would fix it. Apart from the skipped flush this is cosmetic; it is worth a one-line issue.
diff --git a/docs/user-guide.md b/docs/user-guide.md
index 51ae7b5..0ca1125 100644
--- a/docs/user-guide.md
+++ b/docs/user-guide.md
@@ -250,6 +250,15 @@ Common causes:
Programs then ask those servers directly, and fall back to the local
network's when the tunnel is down. Link it to the stub:
`sudo ln -sf ../run/systemd/resolve/stub-resolv.conf /etc/resolv.conf`.
+- **`check` warns about `ip_unprivileged_port_start`:** the tunnels listen
+ on `127.0.0.1` ports 225 to 240, which only root may bind unless the
+ sysctl `net.ipv4.ip_unprivileged_port_start` was lowered to 240 or
+ below, as some container setups do. Then another user can hold the
+ ports and stop the tunnel from starting. Nothing leaks: the guard stays.
+- **"no free port for sshuttle's DNS redirector (9001-12300)"**, or for
+ its IPv6 redirector: sshuttle still picks those ports itself, and any
+ user can bind them. Find who holds them with `sudo ss -lunp` (DNS) or
+ `sudo ss -ltnp` (IPv6) and stop that program.
- **`check` warns that no cgroup hierarchy holds systemd's units:** the
plugin cannot find the tunnel unit's processes, so it gives up 10 s
after connecting. This happens only with an unusual cgroup setup.
diff --git a/nm_sshuttle/cli.py b/nm_sshuttle/cli.py
index 8bfff30..eae3e77 100644
--- a/nm_sshuttle/cli.py
+++ b/nm_sshuttle/cli.py
@@ -31,8 +31,9 @@
import sys
from . import claims, guard, profile, tunnel
-from .const import (NM_DNS_IFACE, NM_DNS_PATH, NM_NAME, SERVICE_TYPE, SLOTS, V1_GUARD_TABLE,
- V1_PLUGIN_UNIT, V1_TUNNEL_SPEC, V1_TUNNEL_UNIT, Slot, slot_number)
+from .const import (LISTEN_PORTS, NM_DNS_IFACE, NM_DNS_PATH, NM_NAME, SERVICE_TYPE, SLOTS,
+ V1_GUARD_TABLE, V1_PLUGIN_UNIT, V1_TUNNEL_SPEC, V1_TUNNEL_UNIT, Slot,
+ slot_number)
log = logging.getLogger("nm-sshuttle")
@@ -292,7 +293,8 @@ def nm_dns_mode(run=subprocess.run):
def check(args, nmcli=nmcli_run, ssh_g=ssh_g_as_self, run=subprocess.run,
- iptables_available=None, dns_mode=None, resolv_conf=None, cgroup=None):
+ iptables_available=None, dns_mode=None, resolv_conf=None, port_start=None,
+ cgroup=None):
"""Check a profile as the user it belongs to (design §4.2, §4.3).
Returns 0 when everything passes. The test login may prompt for a host key
@@ -325,6 +327,11 @@ def check(args, nmcli=nmcli_run, ssh_g=ssh_g_as_self, run=subprocess.run,
if why:
print(f"FAIL dns={prof.dns} needs every lookup to go to systemd-resolved; {why}")
return 1
+ start = (port_start or tunnel.unprivileged_port_start)()
+ if start is not None and start <= max(LISTEN_PORTS):
+ print(f"WARN net.ipv4.ip_unprivileged_port_start is {start}: any user may bind "
+ f"sshuttle's redirect ports {min(LISTEN_PORTS)}-{max(LISTEN_PORTS)} and stop the "
+ "tunnel from starting")
if (cgroup or tunnel.unit_cgroup)("nm-sshuttle.service") is None:
print("WARN no cgroup hierarchy under /sys/fs/cgroup holds systemd's units: the health "
"check cannot tell the tunnel's own listener, and the plugin gives up 10 s after "
diff --git a/nm_sshuttle/const.py b/nm_sshuttle/const.py
index 4dc718b..fbf892b 100644
--- a/nm_sshuttle/const.py
+++ b/nm_sshuttle/const.py
@@ -43,6 +43,12 @@
TPROXY_MARK = 0x4e530000
TPROXY_TABLE = 0x4e53
TPROXY_PRIORITY = 100
+# sshuttle's redirect ports (design §4.8). Below net.ipv4.ip_unprivileged_port_start
+# only root may bind them, and IANA has not assigned 225 to 241. Each slot tries
+# two of its own first, then the others: a port in TIME_WAIT cannot be bound for
+# 60 s (lab T8), and quick restarts can leave both of a slot's own in it.
+LISTEN_PORTS = range(225, 241)
+LISTEN_PORTS_PER_SLOT = 2
# Overridable for development and tests; packages use the defaults.
LIBEXEC = os.environ.get("NM_SSHUTTLE_LIBEXEC", "/usr/libexec/nm-sshuttle")
@@ -106,6 +112,14 @@ def claim(self):
def tproxy_mark(self):
return TPROXY_MARK + self.n
+ @property
+ def listen_ports(self):
+ """The redirect ports in the order the slot tries them: its own two,
+ then the others from the top down, whose slots are used least."""
+ first = LISTEN_PORTS[0] + LISTEN_PORTS_PER_SLOT * self.n
+ own = list(range(first, first + LISTEN_PORTS_PER_SLOT))
+ return own + [p for p in reversed(LISTEN_PORTS) if p not in own]
+
def slot_number(text):
"""A slot from the command line or a unit's instance name."""
diff --git a/nm_sshuttle/supervisor.py b/nm_sshuttle/supervisor.py
index f285758..4e8df56 100644
--- a/nm_sshuttle/supervisor.py
+++ b/nm_sshuttle/supervisor.py
@@ -33,7 +33,7 @@
AC_NAMES, AC_UNKNOWN, CONN_PORTAL, DEVICE_UNMANAGED, FAIL_CONNECT,
FAIL_LOGIN, LINK_ADDRESS, NBNS_SENTINEL,
ST_INIT, ST_STARTED, ST_STARTING, ST_STOPPED, ST_STOPPING, STATE_NAMES)
-from .tunnel import classify_failure
+from .tunnel import classify_failure, port_failure
log = logging.getLogger("nm-sshuttle")
@@ -558,7 +558,8 @@ def _first_tunnel_result(self, ok, detail):
return
if not ok:
code = FAIL_LOGIN if classify_failure(detail) == "login" else FAIL_CONNECT
- self.give_up(code, f"the tunnel did not start: {detail}")
+ hint = port_failure(detail, self.ipv6)
+ self.give_up(code, f"the tunnel did not start: {hint + ': ' if hint else ''}{detail}")
return
self._wait_device(self._first_device)
@@ -938,6 +939,9 @@ def _retry_result(self, ok, detail):
self.fx.session_locked(self.profile.user, self._callback(
self._lock_answer, self.attempt_id, detail))
return
+ hint = port_failure(detail, self.ipv6)
+ if hint:
+ log.warning("reconnect attempt %d failed: %s", self.attempts, hint)
log.info("reconnect attempt %d failed: %s", self.attempts, detail.strip())
self._schedule_retry()
return
diff --git a/nm_sshuttle/tunnel.py b/nm_sshuttle/tunnel.py
index 645050b..97894fc 100644
--- a/nm_sshuttle/tunnel.py
+++ b/nm_sshuttle/tunnel.py
@@ -17,7 +17,7 @@
import threading
from .claims import runs_as_root
-from .const import LIBEXEC, SSH_CONFIG, V1_TUNNEL_SPEC, Slot
+from .const import LIBEXEC, LISTEN_PORTS, SSH_CONFIG, V1_TUNNEL_SPEC, Slot
from .profile import collapse, family
log = logging.getLogger("nm-sshuttle")
@@ -49,13 +49,17 @@ def first_hops(spec):
return [hops] if isinstance(hops, str) else list(hops)
-def sshuttle_argv(spec, sshuttle, ssh_config=None):
+def sshuttle_argv(spec, sshuttle, ssh_config=None, port=None):
"""sshuttle's command line for a tunnel spec written by the plugin; ssh
reads ssh_config instead of the usual files when it is given.
Without spec["ipv6"] sshuttle runs with --disable-ipv6 and gets no IPv6
network at all, which it would only drop with a warning; the guard still
- covers them."""
+ covers them.
+
+ port is the IPv4 redirect port (design §4.8). sshuttle 1.3.1 and 2.0.0
+ stop with an UnboundLocalError when --listen gives a port for both
+ families, so ::1 gets port 0: sshuttle picks its IPv6 port as before."""
ipv6 = bool(spec.get("ipv6"))
def wanted(nets):
@@ -64,6 +68,8 @@ def wanted(nets):
argv = [sshuttle, "-v", "--method", spec.get("method", "nft")]
if not ipv6:
argv.append("--disable-ipv6")
+ if port:
+ argv += ["--listen", f"127.0.0.1:{port}" + (",[::1]:0" if ipv6 else "")]
if spec.get("tmark"):
argv += ["--tmark", f"{spec['tmark']:#x}"]
argv += ["-r", spec["remote"]]
@@ -107,11 +113,51 @@ def exec_tunnel(slot=None):
ssh_config = write_ssh_config(text, SSH_CONFIG if slot is None else Slot(slot).ssh_config)
print(f"exec-tunnel: the first hop's name does not resolve; ssh gets its address "
f"from connect through {ssh_config}", file=sys.stderr, flush=True)
- argv = sshuttle_argv(spec, sshuttle, ssh_config)
+ port = None if slot is None else listen_port(Slot(slot).listen_ports,
+ udp=spec.get("method") == "tproxy")
+ argv = sshuttle_argv(spec, sshuttle, ssh_config, port)
print("exec-tunnel: exec " + " ".join(argv), file=sys.stderr, flush=True)
os.execv(sshuttle, argv)
+def unprivileged_port_start(path="/proc/sys/net/ipv4/ip_unprivileged_port_start"):
+ """The lowest port any user may bind (it covers IPv6 too), or None."""
+ try:
+ with open(path) as f:
+ return int(f.read())
+ except (OSError, ValueError):
+ return None
+
+
+def bindable(port, kind=socket.SOCK_STREAM):
+ """Whether sshuttle could bind 127.0.0.1:port now. Like sshuttle, without
+ SO_REUSEADDR, so that a port in TIME_WAIT counts as taken (lab T8)."""
+ try:
+ with socket.socket(socket.AF_INET, kind) as s:
+ s.bind(("127.0.0.1", port))
+ except OSError:
+ return False
+ return True
+
+
+def listen_port(ports, udp=False, bindable=bindable, port_start=unprivileged_port_start):
+ """The redirect port: the first of ports, in the slot's order, that is free
+ (design §4.8). method=tproxy also binds UDP on it. When none is free, the
+ first: sshuttle then stops with EADDRINUSE, a failed start like any other
+ (the plugin gives up at Connect, and tries again in a gap)."""
+ start = port_start()
+ if start is not None and start <= max(ports):
+ print(f"exec-tunnel: net.ipv4.ip_unprivileged_port_start is {start}, so any user "
+ f"may bind the redirect ports {min(ports)}-{max(ports)} and stop the tunnel from "
+ f"starting", file=sys.stderr, flush=True)
+ for port in ports:
+ if bindable(port) and (not udp or bindable(port, socket.SOCK_DGRAM)):
+ return port
+ print(f"exec-tunnel: no free redirect port among {min(ports)}-{max(ports)}; trying "
+ f"{ports[0]}", file=sys.stderr, flush=True)
+ return ports[0]
+
+
# systemd-resolved's stub listeners: the full one and the proxy-only one
RESOLVED_STUBS = ("127.0.0.53", "127.0.0.54")
@@ -140,6 +186,23 @@ def classify_failure(journal):
return "login" if any(m in journal for m in AUTH_MARKERS) else "connect"
+def port_failure(journal, ipv6):
+ """What sshuttle found no free port for, from its journal, or None (design
+ §4.8). sshuttle -v logs its TCP redirector once it is bound and then
+ searches the DNS port; the IPv4 TCP port is exec-tunnel's choice, which
+ logs when none of its ports was free."""
+ if "Address already in use" not in journal:
+ return None
+ if "TCP redirector listening" in journal:
+ return ("no free port for sshuttle's DNS redirector (9001-12300); another user may be "
+ "holding them")
+ if ipv6 and "no free redirect port" not in journal:
+ return ("no free port for sshuttle's IPv6 redirector on ::1 (9001-12300); another user "
+ "may be holding them")
+ return (f"sshuttle's redirect port ({LISTEN_PORTS[0]}-{LISTEN_PORTS[-1]}) was taken, by "
+ f"another tunnel or by root")
+
+
# ------------------------------------------------------------- ssh bridge
def user_environment(user, pw):
"""The user's systemd manager environment, read as the user."""
diff --git a/test-vm/README.md b/test-vm/README.md
index 8d13b7a..b417018 100644
--- a/test-vm/README.md
+++ b/test-vm/README.md
@@ -22,7 +22,7 @@ slot.
| id | scenario |
|---|---|
| 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 |
+| 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 |
| 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,7 +31,7 @@ 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; the sweep removes a stale table whose port another user listens on |
diff --git a/test-vm/lib.sh b/test-vm/lib.sh
index c0c26ce..ecc6d8b 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,6 +677,26 @@ 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; }
# 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}'; }
diff --git a/test-vm/run.sh b/test-vm/run.sh
index d8edd19..ec08123 100755
--- a/test-vm/run.sh
+++ b/test-vm/run.sh
@@ -266,6 +266,7 @@ 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
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)"
@@ -546,6 +547,21 @@ 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
}
diff --git a/tests/test_cli.py b/tests/test_cli.py
index bbd7703..0fb096f 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -126,7 +126,7 @@ def run(argv):
ran.append(argv)
return SimpleNamespace(returncode=0)
assert cli.check(argparse.Namespace(name="corp"), Nmcli({"u1": conn()}), ssh_g_ok, run,
- cgroup=lambda unit: "/sys/fs/cgroup/x") == 0
+ 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
@@ -169,11 +169,19 @@ 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,
- cgroup=lambda unit: None) == 0
+ 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"
diff --git a/tests/test_events.py b/tests/test_events.py
index aa8b483..6a33cde 100644
--- a/tests/test_events.py
+++ b/tests/test_events.py
@@ -331,6 +331,17 @@ def test_health_gives_up_once_without_systemds_cgroups(up, caplog):
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
diff --git a/tests/test_tunnel.py b/tests/test_tunnel.py
index 9c9eeae..c0dc4d3 100644
--- a/tests/test_tunnel.py
+++ b/tests/test_tunnel.py
@@ -1,11 +1,13 @@
# SPDX-License-Identifier: MIT
+import json
import os
import socket
import subprocess
import time
from types import SimpleNamespace
-from nm_sshuttle import tunnel
+from nm_sshuttle import const, 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",
@@ -202,6 +204,17 @@ def test_classify_failure():
assert tunnel.classify_failure("ssh: connect to host corp port 22: timed out") == "connect"
+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")
@@ -329,6 +342,79 @@ def test_nft_health(monkeypatch):
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")
@@ -342,3 +428,10 @@ def test_resolv_conf_must_point_at_resolveds_stub(tmp_path):
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
From 2da74549acec352f034357ee334dfa9a687a9a4a Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 23 Oct 2026 17:15:26 +0000
Subject: [PATCH 09/16] fix(tunnel): give sshuttle an address as its remote
- sshuttle 2.0.0 runs ssh -G and a lookup as root on its -r value, on
whatever network the host is on, and excludes every address it gets,
also when gateway is set. A forged DNS answer could take internal
addresses out of the tunnel, outside the plugin's checks.
- Pass -r 127.0.0.1 instead: an address needs no lookup, and sshuttle
already excludes it as its IPv4 listen address.
- The bridge gets the real remote as ssh-as-user USER --remote REMOTE.
It accepts only the tail sshuttle 1.3.1 and 2.0.0 append for the
stand-in ([-F CFG] 127.0.0.1 -- COMMAND), checks the remote again and
gives ssh [-p PORT] [USER@]HOST split as sshuttle's parse_hostport
splits it, so ssh sees the same destination as before.
- profile: _remote() becomes split_remote(), which returns the parts;
the rules are unchanged.
- VM test M2-02m checks sshuttle's and ssh's remotes; document the
lookup and the bridge in the design and upstream notes.
Co-Authored-By: Claude Opus 5.5 (1M context)
---
CHANGELOG.md | 4 ++
docs/design.md | 29 ++++++++++++-
docs/upstream/sshuttle.md | 10 ++++-
gnome/nm-sshuttle-validate.c | 6 +--
nm_sshuttle/cli.py | 13 ++++--
nm_sshuttle/profile.py | 24 ++++++-----
nm_sshuttle/tunnel.py | 41 ++++++++++++++++---
test-vm/README.md | 2 +-
test-vm/lib.sh | 13 ++++++
test-vm/run.sh | 1 +
tests/test_profile.py | 11 ++++-
tests/test_tunnel.py | 79 ++++++++++++++++++++++++++++++++++--
12 files changed, 202 insertions(+), 31 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 20f63cc..3148d0b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -51,6 +51,10 @@ uses [semantic versioning](https://semver.org/).
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.
+- 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.
## [0.1.0] - 2026-10-11
diff --git a/docs/design.md b/docs/design.md
index f06a2af..ca1f04c 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -524,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
@@ -632,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) │
└─────────────────────────────────────────────────────────────────────────┘
@@ -934,6 +939,26 @@ The bridge, `nm-sshuttle ssh-as-user USER`, is sshuttle's `-e` command:
-o ServerAliveInterval=10 -o ServerAliveCountMax=3 REMOTE -- `.
+**sshuttle never sees the remote.** sshuttle 2.0.0 runs `ssh -G` and a
+lookup as root on its `-r` value, and excludes every address it gets
+(§2.2). So `exec-tunnel` passes `-r 127.0.0.1`, an address that needs no
+lookup and that sshuttle already excludes as its IPv4 listen address, and
+the profile's remote goes to the bridge: `ssh-as-user USER --remote
+REMOTE`. sshuttle 1.3.1 and 2.0.0 run the `-e` command with
+`[-p PORT] [USER@]HOST -- COMMAND` appended, split from `-r` by their
+`parse_hostport`; for `127.0.0.1` that is `127.0.0.1 -- COMMAND`. The
+bridge refuses anything else, checks the remote as the profile check
+does (§4.2), and gives ssh `[-p PORT] [USER@]HOST -- COMMAND` split the
+same way from the remote. ssh thus gets the same user, host and port as
+before, and the user's config, `ProxyJump`, an IPv6 first hop and the pin
+below work as they did. The host goes on as written in the profile, as
+`check`'s test login gives it; sshuttle wrote an IPv6 address in its
+short form and, when a port followed, a name in lower case. Only root's
+own ssh config can still make 2.0.0 look something up: a `ProxyJump` (or
+`HostName`) that `/etc/ssh/ssh_config` gives every host, `127.0.0.1`
+included, is looked up as root and excluded. An admin who sets one for
+`Host *` should leave `127.0.0.1` out.
+
**[lab T1]** In the lab, a root sshuttle 2.0.0 tunnelled traffic with ssh
running as the user, a user-only alias, and a passphrase-protected key held
in the user's agent.
diff --git a/docs/upstream/sshuttle.md b/docs/upstream/sshuttle.md
index f18ba40..bbf0e47 100644
--- a/docs/upstream/sshuttle.md
+++ b/docs/upstream/sshuttle.md
@@ -279,7 +279,15 @@ Lab T2 is our own case:
**With the patch**, the reproducer lists `(, '192.0.2.1', 32, 0, 0)` under "Subnets to exclude from forwarding" and no longer prints "Failed to exclude remote IP".
-**Side effect.** The `-e` command now also runs once as ` -G host`. A wrapper that does not pass its arguments on to `ssh` may fail at that point. *(from source)* `parse_hostname()` already runs this with a 2 s timeout inside `except Exception`, so such a failure costs at most 2 s and the exclusion. Our `ssh-as-user` wrapper passes `"$@"` to `ssh`, but we have not run lab T2 with the patch.
+**Not wanted by nm-sshuttle any more.** The lookup also runs on whatever
+network the host is on, so a spoofed answer chooses what gets excluded.
+nm-sshuttle now passes `-r 127.0.0.1` and lets its `-e` command give ssh
+the real remote (design §4.3), so neither the lookup nor this fix applies
+to it. With the patch, its `-e` command would refuse the `-G` call, and
+`parse_hostname()` would fall back to `127.0.0.1`, which needs no lookup
+either.
+
+**Side effect.** The `-e` command now also runs once as ` -G host`. A wrapper that does not pass its arguments on to `ssh` may fail at that point. *(from source)* `parse_hostname()` already runs this with a 2 s timeout inside `except Exception`, so such a failure costs at most 2 s and the exclusion. The lab's `ssh-as-user` wrapper passes `"$@"` to `ssh`, but we have not run lab T2 with the patch. nm-sshuttle's own bridge refuses the `-G` call (above), so with the patch `parse_hostname()` falls back to `127.0.0.1`.
---
diff --git a/gnome/nm-sshuttle-validate.c b/gnome/nm-sshuttle-validate.c
index d982ed6..afedbfe 100644
--- a/gnome/nm-sshuttle-validate.c
+++ b/gnome/nm-sshuttle-validate.c
@@ -204,9 +204,9 @@ check_networks(NmssField field, const char *value, gboolean required, GError **e
}
/* [USER@]HOST[:PORT] as sshuttle's parse_hostport splits it, and as profile.py's
- * _remote() checks it: USER is not empty and has no ":"; HOST is not empty, does
- * not start with "-", and may be an IPv6 address, in brackets when a port
- * follows. */
+ * split_remote() checks it: USER is not empty and has no ":"; HOST is not
+ * empty, does not start with "-", and may be an IPv6 address, in brackets when
+ * a port follows. */
gboolean
nmss_check_remote(const char *value, GError **error)
{
diff --git a/nm_sshuttle/cli.py b/nm_sshuttle/cli.py
index eae3e77..03bf405 100644
--- a/nm_sshuttle/cli.py
+++ b/nm_sshuttle/cli.py
@@ -387,12 +387,17 @@ def remove(args, nmcli=nmcli_run):
def main(argv=None):
argv = sys.argv[1:] if argv is None else argv
if argv[:1] == ["ssh-as-user"]:
- # Everything after the user goes to ssh unchanged; argparse would eat options.
+ # What follows the user goes to ssh, with --remote in place of sshuttle's stand-in
+ # (design §4.3); argparse would eat options.
if len(argv) < 2:
- print("usage: nm-sshuttle ssh-as-user USER [SSH-ARGS...]", file=sys.stderr)
+ print("usage: nm-sshuttle ssh-as-user USER [--remote REMOTE] [SSH-ARGS...]",
+ file=sys.stderr)
return 2
- tunnel.ssh_as_user(argv[1], argv[2:])
- return 255 # not reached: ssh_as_user execs
+ try:
+ tunnel.ssh_as_user(argv[1], argv[2:])
+ except ValueError as e:
+ print(f"ssh-as-user: {e}", file=sys.stderr)
+ return 255 # reached only on an error: ssh_as_user execs
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stderr)
parser = argparse.ArgumentParser(prog="nm-sshuttle")
sub = parser.add_subparsers(dest="cmd", required=True)
diff --git a/nm_sshuttle/profile.py b/nm_sshuttle/profile.py
index 373fb89..df62af2 100644
--- a/nm_sshuttle/profile.py
+++ b/nm_sshuttle/profile.py
@@ -160,12 +160,13 @@ def _is_ipv6(text):
return True
-def _remote(value):
- """Check an ssh destination as sshuttle's parse_hostport splits it:
- [USER@]HOST[:PORT], where HOST may be an IPv6 address, in brackets when a
- port follows. sshuttle starts its server locally, as root and without ssh,
- when HOST is empty, passes a HOST that starts with "-" to ssh as an option,
- and reads USER:PASSWORD@HOST as a password.
+def split_remote(value):
+ """(user, host, port) of an ssh destination as sshuttle's parse_hostport
+ splits it: [USER@]HOST[:PORT], where HOST may be an IPv6 address, in
+ brackets when a port follows; user is "" and port None when not given.
+ sshuttle starts its server locally, as root and without ssh, when HOST is
+ empty, passes a HOST that starts with "-" to ssh as an option, and reads
+ USER:PASSWORD@HOST as a password.
A scope id is fine here, unlike in the address keys: ssh takes it, and the
destination never reaches nft."""
@@ -187,11 +188,13 @@ def _remote(value):
host, _, port = host.partition(":")
elif ":" in host and not _is_ipv6(host):
raise bad
- if port is not None and _port(port) is None:
- raise bad
+ if port is not None:
+ port = _port(port)
+ if port is None:
+ raise bad
if not host or host.startswith("-") or "[" in host or "]" in host:
raise bad
- return value
+ return user, host, port
def _bool(key, value, default):
@@ -211,7 +214,8 @@ def parse(settings, getpwnam=pwd.getpwnam):
s_ip4 = settings.get("ipv4", {})
data = s_vpn.get("data", {})
- remote = _remote(data.get("remote", ""))
+ remote = data.get("remote", "")
+ split_remote(remote)
user = data.get("local-user", "")
if not USER_RE.fullmatch(user):
diff --git a/nm_sshuttle/tunnel.py b/nm_sshuttle/tunnel.py
index 97894fc..80a1376 100644
--- a/nm_sshuttle/tunnel.py
+++ b/nm_sshuttle/tunnel.py
@@ -8,6 +8,7 @@
import os
import pwd
import re
+import shlex
import shutil
import socket
import stat
@@ -18,7 +19,7 @@
from .claims import runs_as_root
from .const import LIBEXEC, LISTEN_PORTS, SSH_CONFIG, V1_TUNNEL_SPEC, Slot
-from .profile import collapse, family
+from .profile import collapse, family, split_remote
log = logging.getLogger("nm-sshuttle")
@@ -37,11 +38,36 @@
IPTABLES = {4: "iptables", 6: "ip6tables"}
-def bridge_command(user, ssh_config=None):
+# sshuttle's -r. sshuttle 2.0.0 excludes its remote by itself, through ssh -G
+# and a lookup as root, on the network the host is on. An address needs no
+# lookup, and sshuttle already excludes this one, its IPv4 listen address. The
+# bridge gives ssh the profile's remote in its place (design §4.3).
+STAND_IN = "127.0.0.1"
+
+
+def bridge_command(user, remote=None, ssh_config=None):
+ """sshuttle's -e: the bridge, which gives ssh remote for the stand-in."""
cmd = f"{os.path.join(LIBEXEC, 'nm-sshuttle')} ssh-as-user {user}"
+ if remote:
+ cmd += f" --remote {shlex.quote(remote)}"
return f"{cmd} -F {ssh_config}" if ssh_config else cmd
+def bridged_args(remote, args):
+ """ssh's arguments for sshuttle's: the profile's remote in place of the
+ stand-in. sshuttle 1.3.1 and 2.0.0 append [-p PORT] [USER@]HOST -- COMMAND
+ to the -e command, as their parse_hostport splits -r; the stand-in has no
+ user and no port. Anything else is refused, so that only the remote the
+ plugin checked reaches ssh, split the same way."""
+ opts = args[:2] if args[:1] == ["-F"] else []
+ rest = args[len(opts):]
+ if len(rest) != 3 or rest[0] != STAND_IN or rest[1] != "--":
+ raise ValueError(f"unexpected arguments from sshuttle: {' '.join(rest[:2])}")
+ user, host, port = split_remote(remote)
+ port_opts = ["-p", str(port)] if port is not None else []
+ return [*opts, *port_opts, f"{user}@{host}" if user else host, "--", rest[2]]
+
+
def first_hops(spec):
"""The first hop's addresses from a tunnel spec. A spec written before IPv6
support holds one address as a string (docs/later/ipv6.md)."""
@@ -72,10 +98,10 @@ def wanted(nets):
argv += ["--listen", f"127.0.0.1:{port}" + (",[::1]:0" if ipv6 else "")]
if spec.get("tmark"):
argv += ["--tmark", f"{spec['tmark']:#x}"]
- argv += ["-r", spec["remote"]]
+ argv += ["-r", STAND_IN]
for net in wanted(first_hops(spec) + list(spec.get("exclude", []))):
argv += ["-x", net]
- argv += ["-e", bridge_command(spec["user"], ssh_config)]
+ argv += ["-e", bridge_command(spec["user"], spec["remote"], ssh_config)]
servers = spec.get("dns_servers") or []
if spec.get("dns", "none") != "none" and servers:
# --to-ns pins the remote resolver and avoids the crash of lab T9.
@@ -227,7 +253,12 @@ def user_environment(user, pw):
def ssh_as_user(user, args):
"""sshuttle's -e command: run ssh as USER with the user's agent and display,
so ~/.ssh/config, known_hosts and agent prompts work as usual. Only ssh runs
- as the user; it never runs as root."""
+ as the user; it never runs as root. With --remote first, ssh gets that
+ remote in place of sshuttle's stand-in."""
+ if args[:1] == ["--remote"]:
+ if len(args) < 2:
+ raise ValueError("--remote needs a value")
+ args = bridged_args(args[1], args[2:])
pw = pwd.getpwnam(user)
rt = f"/run/user/{pw.pw_uid}"
menv = user_environment(user, pw)
diff --git a/test-vm/README.md b/test-vm/README.md
index b417018..b3c3195 100644
--- a/test-vm/README.md
+++ b/test-vm/README.md
@@ -22,7 +22,7 @@ slot.
| id | scenario |
|---|---|
| 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 |
+| 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 |
| 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 |
diff --git a/test-vm/lib.sh b/test-vm/lib.sh
index ecc6d8b..c05cc12 100644
--- a/test-vm/lib.sh
+++ b/test-vm/lib.sh
@@ -698,6 +698,19 @@ 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"
+}
# 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 ec08123..393f019 100755
--- a/test-vm/run.sh
+++ b/test-vm/run.sh
@@ -267,6 +267,7 @@ s_connect() {
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
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)"
diff --git a/tests/test_profile.py b/tests/test_profile.py
index d59f8eb..b488ce9 100644
--- a/tests/test_profile.py
+++ b/tests/test_profile.py
@@ -4,7 +4,7 @@
import pytest
from fakes import fake_getpwnam, settings
-from nm_sshuttle.profile import ProfileError, collapse, parse
+from nm_sshuttle.profile import ProfileError, collapse, parse, split_remote
def p(s):
@@ -141,3 +141,12 @@ 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")
diff --git a/tests/test_tunnel.py b/tests/test_tunnel.py
index c0dc4d3..99a9078 100644
--- a/tests/test_tunnel.py
+++ b/tests/test_tunnel.py
@@ -1,12 +1,15 @@
# SPDX-License-Identifier: MIT
import json
import os
+import shlex
import socket
import subprocess
import time
from types import SimpleNamespace
-from nm_sshuttle import const, 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"],
@@ -17,9 +20,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
@@ -180,7 +183,75 @@ 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"})
+ 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_resolves():
From 78ca6621d657bec34d5fdf356c83e630a5c24242 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 23 Oct 2026 17:15:45 +0000
Subject: [PATCH 10/16] fix(service): refuse first-hop addresses inside the
tunnelled networks
- The first hop's addresses come from a lookup on whatever network the
host is on, and each one is excluded from the tunnel and accepted by
the guard. A forged DNS answer could take any internal address out of
the tunnel while the VPN showed connected.
- Profile.first_hop_addresses() drops a looked-up address that lies in
the subnets or, with DNS, the DNS servers, unless exclude covers it,
and keeps at most 8 (MAX_HOPS). gateway, and a HostName that is an
address (first-hop --kind says which), are never looked up and are
taken as given.
- Connect fails when no address is left; after a network change or
resume the old addresses stay. Refused addresses are logged, and while
there are any, ssh is pinned to a kept address, since its own lookup
could pick one the guard rejects; a failed start or reconnect names
them.
- check applies the same filter, and active_conflict uses it for the
other profiles' first hops.
- A jump host reached by name inside the tunnelled networks, including
any of a 0.0.0.0/0 or ::/0 profile, now needs gateway or exclude.
Document this in the design, user guide, README, IPv6 notes and the
editor's hint.
Co-Authored-By: Claude Opus 5.5 (1M context)
---
CHANGELOG.md | 12 ++++++
README.md | 8 ++++
docs/design.md | 57 ++++++++++++++++++++++---
docs/later/ipv6.md | 9 +++-
docs/user-guide.md | 32 +++++++++++++-
gnome/nm-sshuttle-editor.ui | 2 +-
nm_sshuttle/cli.py | 34 +++++++++++----
nm_sshuttle/profile.py | 42 +++++++++++++++++--
nm_sshuttle/service.py | 11 ++---
nm_sshuttle/supervisor.py | 75 +++++++++++++++++++++++++++------
nm_sshuttle/tunnel.py | 35 ++++++++++++----
tests/test_cli.py | 42 +++++++++++++++++++
tests/test_events.py | 61 +++++++++++++++++++++++++++
tests/test_ipv6.py | 10 +++++
tests/test_multi.py | 2 +-
tests/test_profile.py | 28 ++++++++++++-
tests/test_service_dbus.py | 16 +++++++
tests/test_supervisor.py | 83 +++++++++++++++++++++++++++++++++++++
tests/test_tunnel.py | 34 +++++++++++----
19 files changed, 536 insertions(+), 57 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3148d0b..1a1fd4b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -51,6 +51,18 @@ uses [semantic versioning](https://semver.org/).
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
diff --git a/README.md b/README.md
index 11b6d9c..e700c8b 100644
--- a/README.md
+++ b/README.md
@@ -129,6 +129,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/docs/design.md b/docs/design.md
index ca1f04c..6b22c33 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -872,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`). |
@@ -914,6 +914,38 @@ options**: ssh options belong in the user's `~/.ssh/config`, which only
ever reaches the unprivileged ssh. NetworkManager-ssh removed arbitrary ssh
options for the same reason.
+**The first hop's addresses are untrusted too.** Without `gateway`, and
+when the first hop's `HostName` (from `ssh -G`) is a name, they come from
+a lookup on whatever network the host is on, at `Connect` and after every
+network change or resume, and a spoofed answer can add any address. Each
+one is excluded from the tunnel and accepted by the guard before its
+reject rules, so it would leak. The plugin therefore drops an address that
+lies in the guarded networks (the subnets and, with DNS, the DNS servers)
+unless `exclude` covers it, and logs a warning that names it. It keeps at
+most 8 addresses (`MAX_HOPS`) and logs the rest. A message names at most 8
+addresses, since a forged answer can hold hundreds. With no address left,
+`Connect` fails: "the first hop's name resolves only into the profile's
+networks or DNS servers (…); set 'gateway' or 'exclude' for a first hop
+there". After a network change it keeps the old addresses instead. While
+the last lookup refused an address, ssh gets a kept one through the pin
+of §4.3, since its own lookup could pick the refused one, which the guard
+rejects. A bastion whose name resolves inside the subnets on the office
+network (split-horizon DNS) thus keeps its outside address there, which
+works only if the office network reaches it. A failed start, a reconnect
+attempt and the end of the reconnect timeout then name the refused
+addresses. A first hop inside the subnets that is reached by name, such
+as a bastion in the corporate range or any first hop of a `0.0.0.0/0`
+profile, therefore needs `gateway`, or `exclude` with its address. A first
+hop whose address changes, such as a dynamic DNS name, can be neither, so
+it no longer works with a profile whose subnets cover it, as a
+`0.0.0.0/0` profile's do. A `HostName` that is an address,
+in the profile's `remote` or in the user's `~/.ssh/config`, is taken like
+`gateway`: no lookup took place, and the user could give the same address
+as `gateway` or `exclude` anyway. `nm-sshuttle first-hop --kind` tells the
+plugin which it was. An address outside the guarded networks gains nothing
+from the exclusion, so a spoofed one there does no harm. `nm-sshuttle
+check` reports the same.
+
**[src]** GNOME Settings can break the permissions and method rules without
an editor plugin. The Details tab's "Make available to other users" clears
`connection.permissions`, possibly after an admin prompt, and the IPv4 tab
@@ -998,6 +1030,9 @@ Include /etc/ssh/ssh_config
the name, while the pin is in use.
- When the name resolves, ssh runs as before, with the user's config only.
VM test M2-29 covers it.
+- The plugin also asks for the pin, whatever `dns` is and whether the
+ name resolves, while the first hop's lookup gave addresses it refused
+ (§4.2).
**How a key gets unlocked.** Unlocking happens in the agent: gcr-ssh-agent
prompts in the session when a key is first used. With plain `ssh-agent`,
@@ -1053,7 +1088,8 @@ versions, so it stays as the fallback.
Events and what the supervisor does:
- **Toggle on (`Connect`):**
- 1. Resolve the first hop as the user (`ssh -G` through the bridge).
+ 1. Resolve the first hop as the user (`ssh -G` through the bridge), and
+ keep its usable addresses (§4.2).
2. Sweep stale tables.
3. Create `nmss0` and install the guard.
4. Start the tunnel unit and wait for `READY=1` (timeout 30 s).
@@ -1302,8 +1338,10 @@ Events and what the supervisor does:
but not its addresses, so a new temporary address is no change
([IPv6](later/ipv6.md)); otherwise IPv6 changes do not count.
- After a change or a resume the first hop is resolved again, as the
- user, before the next attempt; if that fails the old address stays.
- A new address also goes into `Config`'s `gateway`.
+ user, before the next attempt; if that fails, or leaves no usable
+ address (§4.2), the old address stays, and with refused addresses
+ ssh is pinned to it. A new address also goes into `Config`'s
+ `gateway`.
- An attempt that started more than 2 s before the change is abandoned.
The at-once attempt waits until the stop of the tunnel it replaces is
confirmed (at most 20 s), so the two start and stop jobs do not race.
@@ -1546,8 +1584,8 @@ table inet nm-sshuttle-guard {
```
The IPv6 sets are always there, empty for an IPv4-only profile
-([IPv6](later/ipv6.md)). The exclude sets hold every address of the first
-hop and the profile's `exclude`. sshuttle's NAT redirect runs earlier, at
+([IPv6](later/ipv6.md)). The exclude sets hold the first hop's usable
+addresses (§4.2), or `gateway`, and the profile's `exclude`. sshuttle's NAT redirect runs earlier, at
priority `dstnat`, so packets it redirected carry conntrack status `dnat`
when they reach the guard. With `method=tproxy` there is no NAT; two rules
ahead of the `dnat` ones accept what sshuttle's mangle chain marked
@@ -1664,6 +1702,13 @@ minimal path under it; `ip` and `nft` there are untested.
which is upstream's privilege model without sudo.
- **The profile is validated** (§4.2) and its permissions are pinned to one
user.
+- **The local network's DNS does not choose what bypasses the tunnel.**
+ The first hop's addresses from a lookup are checked against the guarded
+ networks and capped (§4.2), and sshuttle gets `127.0.0.1` as its remote,
+ so that 2.0.0 looks nothing up as root unless root's own ssh config
+ gives `127.0.0.1` a `ProxyJump` (§4.3). What stays excluded is
+ the checked first hop, `gateway` and `exclude`. With `fail-closed=no`
+ there is no guard, but sshuttle's own exclusions are the same.
- **The bridge never runs anything as root except `setpriv`**, and ssh
never runs as root.
- **D-Bus access:** only root may own or call the plugin's name, and the
diff --git a/docs/later/ipv6.md b/docs/later/ipv6.md
index f9258a3..4494f40 100644
--- a/docs/later/ipv6.md
+++ b/docs/later/ipv6.md
@@ -19,7 +19,8 @@ Goals:
- The guard gets `subnets6` and `exclude6` and refuses IPv6 traffic to the
tunnelled networks while the tunnel is down, as it does for IPv4.
- A first hop that has only an IPv6 address works, and every address of
- the first hop is excluded, whichever family ssh picks.
+ the first hop is excluded, whichever family ssh picks, as long as it
+ lies outside the guarded networks or `exclude` covers it (design §4.2).
- `gateway` and `probe` accept IPv6 addresses.
Not in this step:
@@ -120,7 +121,11 @@ first, which is often IPv6. If that address lies inside a tunnelled IPv6
network, sshuttle would capture ssh's own connection.
- `first_hop()` resolves with `AF_UNSPEC` and returns every address.
-- All of them go into `-x` and the guard's exclude sets.
+- All of them go into `-x` and the guard's exclude sets, except those
+ that lie in the guarded networks without an `exclude` (design §4.2):
+ a first hop inside a tunnelled IPv6 subnet, as in lab T13, needs
+ `gateway`, an `exclude` for its address, or that address as its
+ `HostName`.
- `Config`'s `gateway` gets the first IPv4 address, or the first IPv6
address (as `ay`) if there is none. NM needs only one (above).
- The tunnel spec (`tunnel.json`) carries the list instead of one string.
diff --git a/docs/user-guide.md b/docs/user-guide.md
index 0ca1125..7d0bff9 100644
--- a/docs/user-guide.md
+++ b/docs/user-guide.md
@@ -88,6 +88,24 @@ With `ProxyCommand` instead of `ProxyJump`, ssh cannot tell which address it
connects to first. Give that address to `add` as `--gateway`, so that the
tunnel does not swallow it.
+The plugin looks up the first host ssh connects to (the `ProxyJump` host,
+or else the `HostName`) on the network you are on, and that answer can be
+forged. So it ignores an address of that host that lies in your
+`--subnets` or `--dns-servers`, and uses at most 8 of its addresses.
+If your jump host does lie in the tunnelled networks, for example a
+bastion at `10.0.0.5` with `--subnets 10.0.0.0/8`, or any jump host of a
+profile that tunnels `0.0.0.0/0`, say so in the profile: give its address
+as `--gateway 10.0.0.5`, or `--exclude 10.0.0.5`. A `HostName` (or
+`--remote`) that is already an address, such as `HostName 10.0.0.5`, is
+not looked up and needs neither. A jump host whose address changes, such
+as a home server behind a dynamic DNS name, cannot be named that way, so
+it does not work with a profile that tunnels `0.0.0.0/0` or `::/0`.
+
+If the name has an outside address and also one inside your `--subnets`,
+as with split-horizon DNS on the office network, ssh is pinned to the
+outside one. If the office network cannot reach that, exclude the inside
+address too: `--exclude 10.1.2.3`.
+
## Creating a profile
Run these as yourself, not as root:
@@ -112,11 +130,11 @@ The options of `add`:
|---|---|
| `--remote` | The ssh destination, as you would type it after `ssh`; usually a `Host` alias. `user@host` works too; put a port in the alias (`Port` in `~/.ssh/config`). A password (`user:password@host`) is refused: use a key. Required. |
| `--subnets` | The networks to send through the tunnel, IPv4 or IPv6, separated by commas. Required. A scope id (`fe80::%eth0/64`) is refused, here and in the other address options. |
-| `--exclude` | Networks inside those to leave out. |
+| `--exclude` | Networks inside those to leave out. A jump host inside the subnets must be excluded here, or given as `--gateway`. |
| `--dns` | `none` (the default) leaves DNS alone. `split` sends lookups for `--dns-domains` to `--dns-servers` through the tunnel, and everything else as before. `all` sends every lookup through the tunnel. |
| `--dns-servers` | The DNS servers on the far side, IPv4 only. Required for `split` and `all`. |
| `--dns-domains` | The domains `split` sends there, subdomains included. `~corp.example` only routes lookups. A plain `corp.example` also completes short names, so `git` becomes `git.corp.example`. Quote a leading `~` in the shell. |
-| `--gateway` | The address ssh connects to first, when the plugin cannot work it out (`ProxyCommand`). |
+| `--gateway` | The address ssh connects to first, when the plugin cannot work it out (`ProxyCommand`), or when it lies inside the subnets. Nothing is looked up then. |
| `--probe` | `ADDRESS:PORT` (or `[IPV6]:PORT`) of a server on the far side that speaks first, such as an ssh server. The plugin connects to it every 10 s and restarts the tunnel after two failures in a row. Without it, a tunnel that is up but stuck is noticed only when sshuttle exits. |
| `--method` | `nft` (the default) or `nat`. `tproxy` also sends UDP through the tunnel, such as QUIC or a DNS server you query directly; it needs `iptables` installed. |
| `--fail-closed` | `yes` (the default) blocks traffic to the tunnelled networks while the tunnel is down. `no` lets it go out on the local network. |
@@ -265,6 +283,16 @@ Common causes:
- **`check` warns about `ipv6.auto-route-ext-gw`:** the profile was made
before IPv6 support. Run the `nmcli connection modify` command it
prints.
+- **"the first hop's name resolves only into the profile's networks or DNS
+ servers":** your jump host's address lies in `--subnets` or
+ `--dns-servers`. If that is right, set `--gateway` to it, exclude it, or
+ give it as the `HostName` (see [Setting up SSH](#setting-up-ssh)). If not, the network you are on
+ may be answering for the name; the journal names the addresses.
+- **"… the first hop's name also resolves to …, inside the profile's
+ networks or DNS servers":** the tunnel did not start, and the plugin
+ had kept only some of the jump host's addresses, for example only its
+ IPv6 one on an IPv4-only network, or its outside one on the office
+ network. Exclude the address it names if that is your jump host.
- **"subnets overlap with the active profile …", "… also uses dns=all",
"… also has the DNS domain …" or "the first hops would run in a
loop":** another active VPN claims the same traffic or DNS. See
diff --git a/gnome/nm-sshuttle-editor.ui b/gnome/nm-sshuttle-editor.ui
index 19fc3e0..0d5ae44 100644
--- a/gnome/nm-sshuttle-editor.ui
+++ b/gnome/nm-sshuttle-editor.ui
@@ -330,7 +330,7 @@
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.
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 b67d015..1d78541 100755
--- a/scripts/signing-key.sh
+++ b/scripts/signing-key.sh
@@ -33,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)
@@ -155,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.
@@ -194,9 +198,10 @@ MSG
mv "$pubkey.new" "$pubkey"
cat <
Date: Fri, 23 Oct 2026 18:33:05 +0000
Subject: [PATCH 16/16] fix(ci): pin the image of the signing job by digest
- The publish job, which holds the signing key, ran in whatever image
the fedora:44 tag named at the time. A changed image under that tag
would run next to the key and could sign anything
- publish now runs in quay.io/fedora/fedora:44 pinned by digest, and so
do srpm and release-rpm, whose output it signs as built, and dry-run,
so that a pull request with a new digest tries it without the key
- The rpm and smoke-test matrix jobs keep following the current Fedora
releases
- packaging/README.md explains which jobs are pinned and why, that
Dependabot does not update a job's container image, and how and how
often to refresh the digest; update the changelog
Co-Authored-By: Claude Opus 5.5 (1M context)
---
.github/workflows/packages.yaml | 13 +++++++++----
CHANGELOG.md | 3 +++
packaging/README.md | 27 +++++++++++++++++++++++++++
3 files changed, 39 insertions(+), 4 deletions(-)
diff --git a/.github/workflows/packages.yaml b/.github/workflows/packages.yaml
index 2fb87a5..beb52a3 100644
--- a/.github/workflows/packages.yaml
+++ b/.github/workflows/packages.yaml
@@ -91,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
@@ -171,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
@@ -202,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
@@ -260,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/CHANGELOG.md b/CHANGELOG.md
index 6589a60..070268f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,9 @@ uses [semantic versioning](https://semver.org/).
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
diff --git a/packaging/README.md b/packaging/README.md
index 8c2d1b4..d215435 100644
--- a/packaging/README.md
+++ b/packaging/README.md
@@ -98,3 +98,30 @@ pushes to `main`. Delete such a tag to unblock them:
```console
$ git push origin :refs/tags/v0.1.1
```
+
+### Container images
+
+`publish` holds the signing key, so its image is pinned by digest, as
+`quay.io/fedora/fedora:44@sha256:...`: a new image under the tag cannot run
+next to the key. Fedora publishes its images on quay.io/fedora as well.
+`srpm` and `release-rpm` run in the same image, since their output is
+signed as built, and so does `dry-run`, so that a pull request with a new
+digest tries it without the key.
+The `rpm` and `smoke-test` matrix jobs keep
+`registry.fedoraproject.org/fedora:`, so that they build and test
+against current Fedora releases; `rpm`'s packages are signed as built, so
+the pinned `publish` image does not cover them. Dependabot's
+`github-actions` updates cover the `uses:` lines only, not a job's
+`container:` image, and this repository has no Dependabot or Renovate
+configuration. Refresh the digest by hand, after a
+Fedora update you want in the signing job and at least once a month:
+
+```console
+$ curl -fsSI -H 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json' \
+ https://quay.io/v2/fedora/fedora/manifests/44 |
+ grep -i '^docker-content-digest:'
+```
+
+That is the digest of the multi-architecture index. Put it after the tag in
+the `image:` of `srpm`, `release-rpm`, `publish` and `dry-run`, and merge it
+to `main` through a pull request.