From 0fba5942230701ec166841862a377669270b2686 Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:29:42 +0100 Subject: [PATCH 01/16] Exempt root from the Tor redirect too under --allow-root The flag exempted root only in filter_out, so root's TCP and DNS still went through Tor while its UDP left in cleartext. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- CHANGELOG.md | 6 ++++++ tests/test_firewall.py | 15 ++++++++++++++- ttp/firewall/builder.py | 6 ++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a532f02..f41e2ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- `--allow-root` exempted root only in the `filter_out` chain, not in the NAT + chain that redirects to Tor. Root's TCP and DNS were still sent through Tor, + while its UDP and ICMP left in cleartext: the flag gave neither the direct + path for system updates that the documentation promises, nor full Tor + routing. Root is now exempt in both chains, like a `--bypass-user`. Its DNS + to the local resolver still goes to Tor. - With no default route, as on an IPv6-only host, `ttp start` recorded the interface `eth0` in the session and printed "DNS set via overlay on interface eth0", even where no `eth0` exists. The interface is only a label: the DNS diff --git a/tests/test_firewall.py b/tests/test_firewall.py index c710b36..7816c0d 100644 --- a/tests/test_firewall.py +++ b/tests/test_firewall.py @@ -237,13 +237,26 @@ def test_filter_out_rejects_dns_that_nat_output_did_not_redirect(ipv6: bool) -> @patch("ttp.firewall.runner._run_nft") @patch("ttp.tor_detect.is_ipv6_supported", return_value=False) def test_ruleset_allow_root(mock_ipv6, mock_run_nft, mock_run_string, mock_pwd): - """Verify that allow_root=True injects meta skuid 0 accept in filter_out.""" + """--allow-root exempts root in both chains: in filter_out alone its TCP was still redirected.""" mock_pwd.return_value = MagicMock(pw_uid=110) apply_rules(tor_user="debian-tor", allow_root=True) ruleset = mock_run_string.call_args[0][0] + nat_block = ruleset.split("chain output")[1].split("chain filter_out")[0] filter_block = ruleset.split("chain filter_out")[1] assert "meta skuid 0 accept" in filter_block + root_exemption = nat_block.index("meta skuid 0 ip daddr != 127.0.0.1 accept") + assert root_exemption < nat_block.index("udp dport 53") < nat_block.index("ip protocol tcp counter") + + +@patch("ttp.firewall.runner.pwd.getpwnam") +@patch("ttp.firewall.runner._run_nft_string") +@patch("ttp.firewall.runner._run_nft") +@patch("ttp.tor_detect.is_ipv6_supported", return_value=False) +def test_root_is_redirected_without_allow_root(mock_ipv6, mock_run_nft, mock_run_string, mock_pwd): + mock_pwd.return_value = MagicMock(pw_uid=110) + apply_rules(tor_user="debian-tor") + assert "skuid 0" not in mock_run_string.call_args[0][0] @patch("ttp.firewall.runner.pwd.getpwnam") diff --git a/ttp/firewall/builder.py b/ttp/firewall/builder.py index fb60ae0..fc7a0b2 100644 --- a/ttp/firewall/builder.py +++ b/ttp/firewall/builder.py @@ -99,6 +99,12 @@ def _build_ruleset( # Bypass rules for nat output and filter_out chains bypass_rules_nat: list[str] = [] bypass_rules_filter: list[str] = [] + if allow_root: + # Root must skip the redirect too: exempt in filter_out alone, its TCP still went to Tor + # while its UDP left in cleartext. Its loopback DNS stays on Tor, as for bypass users. + bypass_rules_nat.append("meta skuid 0 ip daddr != 127.0.0.1 accept") + if ipv6_avail: + bypass_rules_nat.append("meta skuid 0 ip6 daddr != ::1 accept") if cgroup_bypass: bypass_rules_nat.append('socket cgroupv2 level 1 "ttp-bypass.slice" accept') bypass_rules_filter.append('socket cgroupv2 level 1 "ttp-bypass.slice" accept') From cea45a6056c05d190e559a482d631c92f89ecf05 Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:36:14 +0100 Subject: [PATCH 02/16] Fail closed when the session has no table fingerprint A start that could not read its table back recorded None, and the watchdog then skipped the #80 comparison for the whole session, so a flushed table passed. Start now rolls back; the watchdog treats a missing fingerprint or an unreadable table as a firewall failure. The chain-name and bypass-rule checks, which the fingerprint covers, are gone. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- CHANGELOG.md | 10 ++ docs/web/explanation/watchdog-fsm.md | 2 +- tests/test_cli_start.py | 16 ++ tests/test_watchdog.py | 260 ++++----------------------- ttp/commands/start.py | 10 +- ttp/watchdog/integrity.py | 54 +----- 6 files changed, 76 insertions(+), 276 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f41e2ab..18fe54e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- The watchdog compares the live `inet ttp` table with the fingerprint that + `ttp start` records (#80). If `nft` could not list the table at that moment, + for example after a 10-second timeout, `start` recorded no fingerprint and the + watchdog skipped the comparison for the whole session. A flushed table keeps + its chain names, so it then passed the remaining checks: no rules, everything + in cleartext, watchdog healthy. `ttp start` now rolls back when it cannot + read back its table, and the watchdog treats a missing fingerprint, or a + table it cannot read, as a firewall failure. This replaces the chain-name and + bypass-rule checks, which the fingerprint already covers. A bypass user + deleted during a session no longer cuts off the whole host's network. - `--allow-root` exempted root only in the `filter_out` chain, not in the NAT chain that redirects to Tor. Root's TCP and DNS were still sent through Tor, while its UDP and ICMP left in cleartext: the flag gave neither the direct diff --git a/docs/web/explanation/watchdog-fsm.md b/docs/web/explanation/watchdog-fsm.md index 31aa634..f484cb5 100644 --- a/docs/web/explanation/watchdog-fsm.md +++ b/docs/web/explanation/watchdog-fsm.md @@ -93,7 +93,7 @@ evaluation and names the component. | `vpn` | In a required-VPN session, the WireGuard profile, its device and TTP's VPN guard still match the frozen policy ([VPN before Tor](../how-to/vpn.md)). | | `dns` | `/etc/resolv.conf` (or its symlink target) is still a mount point, and every `nameserver` in it is `127.0.0.1` or `::1`. | | `dns` | If `systemd-resolved` was active at start: TTP's drop-in `/run/systemd/resolved.conf.d/ttp.conf` still exists and the service is still active. | -| `firewall` | The `inet ttp` table exists and matches, rule for rule, the fingerprint `ttp start` recorded in the lock. A chain-name check would pass a flushed table, which leaks everything. | +| `firewall` | The `inet ttp` table exists and matches, rule for rule, the fingerprint `ttp start` recorded in the lock. A chain-name check would pass a flushed table, which leaks everything. A lock without a fingerprint fails the check: `ttp start` refuses to record one it cannot read. | | `firewall` | Each bypass user and group recorded in the lock still resolves. | | `firewall` | The DoT, DoH and un-redirected-DNS reject counters have not moved since the previous check. Those rules are only reachable when the NAT redirect has failed, so a new packet on any of them is an alarm about TTP itself ([ADR 0012](https://github.com/onyks-os/TransparentTorProxy/blob/main/docs/decisions/0012-doh-dot-and-browser-leaks-are-out-of-scope.md)). | | `tor` | Tor's control socket answers a `GETINFO`; if the socket is unavailable, `ttp-tor.service` is active. | diff --git a/tests/test_cli_start.py b/tests/test_cli_start.py index a7852a0..315ef9d 100644 --- a/tests/test_cli_start.py +++ b/tests/test_cli_start.py @@ -1599,3 +1599,19 @@ def test_an_interrupted_start_with_latched_emergency_keeps_it( assert result.exit_code == 8, result.output stop.assert_not_called() assert undo_mocks.destroy.call_count == 0 + + +@patch("ttp.firewall.table_fingerprint", return_value=None) +@patch("ttp.firewall.destroy_rules") +@patch("ttp.firewall.runner._run_nft_string") +@patch("ttp.firewall.runner._run_nft") +@patch("ttp.firewall.runner.pwd.getpwnam", return_value=types.SimpleNamespace(pw_uid=110)) +@patch("ttp.state.write_lock") +def test_start_rolls_back_when_it_cannot_read_back_its_table( + mock_write, mock_pwd, mock_run_nft, mock_nft_str, mock_destroy, mock_fp, mock_base_start +): + """Recording no fingerprint would leave the watchdog nothing to compare (#80).""" + result = runner.invoke(app, ["start"]) + assert result.exit_code == 1, result.output + mock_write.assert_not_called() + mock_destroy.assert_called() diff --git a/tests/test_watchdog.py b/tests/test_watchdog.py index 3dcd20e..f3410e0 100644 --- a/tests/test_watchdog.py +++ b/tests/test_watchdog.py @@ -19,6 +19,16 @@ from ttp.settings import Settings from ttp.watchdog import service +FP = "f" * 64 +SESSION = {"table_fingerprint": FP} + + +@pytest.fixture(autouse=True) +def _the_applied_table_is_live(): + """The live table is the recorded one unless a test says otherwise (#80).""" + with patch("ttp.firewall.table_fingerprint", return_value=FP): + yield + @pytest.fixture def temp_watchdog_path(tmp_path: Path): @@ -147,7 +157,8 @@ def test_stop_watchdog(mock_update, mock_run, temp_watchdog_path): @patch("ttp.dns._is_mount_point", return_value=True) @patch("subprocess.run") @patch("ttp.tor_control.get_controller") -def test_check_system_integrity_healthy(mock_get_ctrl, mock_run, mock_is_mount): +@patch("ttp.state.read_lock", return_value=SESSION) +def test_check_system_integrity_healthy(_lock, mock_get_ctrl, mock_run, mock_is_mount): """check_system_integrity returns (None, None) when all systems are healthy.""" # Mock nftables ruleset to contain filter_out mock_run.return_value = MagicMock(stdout="table inet ttp {\n chain filter_out {}\n}\n", returncode=0) @@ -176,35 +187,12 @@ def test_check_system_integrity_dns_failure(mock_is_mount): assert "resolv.conf overlay mount has been unmounted" in err -@patch("ttp.dns.RESOLV_CONF", new="/etc/resolv.conf") -@patch("ttp.dns._is_mount_point", return_value=True) -@patch("subprocess.run") -def test_check_system_integrity_firewall_missing_table(mock_run, mock_is_mount): - """check_system_integrity detects when the nftables 'inet ttp' table is entirely missing.""" - mock_run.return_value = MagicMock(stdout="", returncode=1) - - comp, err = wd.check_system_integrity() - assert comp == "firewall" - assert "table is missing" in err - - -@patch("ttp.dns.RESOLV_CONF", new="/etc/resolv.conf") -@patch("ttp.dns._is_mount_point", return_value=True) -@patch("subprocess.run") -def test_check_system_integrity_firewall_incomplete_table(mock_run, mock_is_mount): - """check_system_integrity detects when 'inet ttp' table is present but incomplete.""" - mock_run.return_value = MagicMock(stdout="table inet ttp {\n chain something_else {}\n}\n", returncode=0) - - comp, err = wd.check_system_integrity() - assert comp == "firewall" - assert "table is incomplete" in err - - @patch("ttp.dns.RESOLV_CONF", new="/etc/resolv.conf") @patch("ttp.dns._is_mount_point", return_value=True) @patch("subprocess.run") @patch("ttp.tor_control.get_controller", return_value=None) -def test_check_system_integrity_tor_socket_inactive_service(mock_get_ctrl, mock_run, mock_is_mount): +@patch("ttp.state.read_lock", return_value=SESSION) +def test_check_system_integrity_tor_socket_inactive_service(_lock, mock_get_ctrl, mock_run, mock_is_mount): """check_system_integrity detects when Tor socket is closed and systemd service is inactive.""" # nftables: OK @@ -227,7 +215,8 @@ def run_side_effect(args, **kwargs): @patch("ttp.dns._is_mount_point", return_value=True) @patch("subprocess.run") @patch("ttp.tor_control.get_controller") -def test_check_system_integrity_tor_unresponsive(mock_get_ctrl, mock_run, mock_is_mount): +@patch("ttp.state.read_lock", return_value=SESSION) +def test_check_system_integrity_tor_unresponsive(_lock, mock_get_ctrl, mock_run, mock_is_mount): """check_system_integrity detects when Tor socket exists but get_info fails (stale/dead Tor).""" mock_run.return_value = MagicMock(stdout="table inet ttp {\n chain filter_out {}\n}\n", returncode=0) @@ -334,7 +323,7 @@ def test_check_system_integrity_systemd_resolved_healthy( mock_exists, mock_run, mock_read_lock, mock_get_ctrl, mock_is_mount ): """check_system_integrity returns (None, None) when systemd-resolved is active, config exists, and service is active.""" - mock_read_lock.return_value = {"dns_backup": {"systemd_resolved": True}} + mock_read_lock.return_value = {"dns_backup": {"systemd_resolved": True}, **SESSION} # Path.exists needs to return True for /run/systemd/resolved.conf.d/ttp.conf mock_exists.return_value = True @@ -414,198 +403,6 @@ def test_trigger_emergency_killswitch_sanitization(caplog): assert "\x1b" not in caplog.text -# --------------------------------------------------------------------------- -# Bypass rule tampering -# --------------------------------------------------------------------------- -# -# `check_system_integrity` already checks that the `inet ttp` table exists and -# carries a `filter_out` chain. That is enough to catch a table that was flushed -# or deleted, and nothing finer. -# -# The bypass rules are the finer case, and they are the one part of the ruleset -# a session *depends on being there* rather than being absent. The lock records -# which users and groups were exempted at `start`; this block re-derives their -# UIDs and GIDs and looks for the matching `accept` in the live ruleset. A -# missing one means the ruleset in the kernel is not the ruleset the lock -# describes - someone edited it, or a reload rebuilt it from different inputs - -# and the watchdog treats that as tampering and fails closed rather than -# healing. -# -# Worth stating what this does *not* detect, since the tests below would -# otherwise imply it: an *extra* `accept` that the lock never asked for is -# invisible here. The check is one-directional by construction. That is a -# narrower guarantee than "the ruleset is unmodified", and the difference -# matters because an added bypass is the version an attacker would want. -# -# One more property of the loops, established by mutating them rather than by -# reading them: because each `except KeyError` *returns*, the first bypass entry -# that cannot be resolved ends the check, and every entry after it goes -# unexamined. Moving the `try` outside the loop is therefore indistinguishable -# from leaving it inside - both stop at the first failure. That is defensible -# (an unverifiable bypass is reported, and the watchdog fails closed on it) but -# it is not what the per-entry `try` looks like it is for, and it differs from -# `label_ports_selinux`, where the equivalent handler only warns and the loop -# genuinely continues. - - -def _healthy_nft(*extra_rules: str) -> str: - """A minimal `inet ttp` listing that passes the table and chain checks.""" - rules = "\n".join(f" {r}" for r in extra_rules) - return f"table inet ttp {{\n chain filter_out {{\n{rules}\n }}\n}}\n" - - -def _integrity_env(nft_stdout: str, lock: dict): - """Everything `check_system_integrity` touches before the bypass block.""" - from contextlib import ExitStack - - stack = ExitStack() - stack.enter_context(patch("ttp.dns.RESOLV_CONF", new="/etc/resolv.conf")) - stack.enter_context(patch("ttp.dns._is_mount_point", return_value=True)) - stack.enter_context(patch("ttp.state.read_lock", return_value=lock)) - stack.enter_context(patch("subprocess.run", return_value=MagicMock(stdout=nft_stdout, returncode=0))) - # A healthy controller, so a bypass verdict cannot be confused with a Tor one. - mock_ctrl = MagicMock() - mock_ctrl.__enter__ = lambda s: s - mock_ctrl.__exit__ = MagicMock(return_value=False) - stack.enter_context(patch("ttp.tor_control.get_controller", return_value=mock_ctrl)) - return stack - - -def test_integrity_accepts_a_ruleset_whose_bypass_rules_are_all_present(): - """The negative control for everything below. - - Without this, a bug that made the bypass block return a violation - unconditionally would still satisfy every "detects a missing rule" test - here, and the watchdog would killswitch a healthy session on every tick. - """ - nft = _healthy_nft("meta skuid 1000 accept", "meta skgid 1000 accept") - lock = {"bypass_users": ["alice"], "bypass_groups": ["devs"]} - - with ( - _integrity_env(nft, lock), - patch("pwd.getpwnam", return_value=MagicMock(pw_uid=1000)), - patch("grp.getgrnam", return_value=MagicMock(gr_gid=1000)), - ): - comp, err = wd.check_system_integrity() - - assert comp is None - assert err is None - - -def test_integrity_detects_a_missing_user_bypass_rule(): - """A bypassed user whose `accept` is gone means the ruleset was rebuilt or edited.""" - nft = _healthy_nft("meta skgid 1000 accept") - lock = {"bypass_users": ["alice"], "bypass_groups": []} - - with _integrity_env(nft, lock), patch("pwd.getpwnam", return_value=MagicMock(pw_uid=1000)): - comp, err = wd.check_system_integrity() - - assert comp == "firewall" - assert "bypass rule for user 'alice' (UID 1000) is missing" in err - - -def test_integrity_detects_a_missing_group_bypass_rule(): - nft = _healthy_nft("meta skuid 1000 accept") - lock = {"bypass_users": [], "bypass_groups": ["devs"]} - - with _integrity_env(nft, lock), patch("grp.getgrnam", return_value=MagicMock(gr_gid=1000)): - comp, err = wd.check_system_integrity() - - assert comp == "firewall" - assert "bypass rule for group 'devs' (GID 1000) is missing" in err - - -def test_integrity_accepts_a_numeric_bypass_id_without_a_name_lookup(): - """A lock may record a bare UID, which must not be sent through `pwd`. - - `ttp start --bypass-user 1000` stores "1000". Resolving that as a *name* - would raise KeyError and be reported as tampering - a healthy session - killswitched because of how the operator spelled the flag. - """ - nft = _healthy_nft("meta skuid 1000 accept", "meta skgid 1000 accept") - lock = {"bypass_users": ["1000"], "bypass_groups": ["1000"]} - - with ( - _integrity_env(nft, lock), - patch("pwd.getpwnam", side_effect=AssertionError("must not be called for a numeric id")), - patch("grp.getgrnam", side_effect=AssertionError("must not be called for a numeric id")), - ): - comp, _ = wd.check_system_integrity() - - assert comp is None - - -def test_integrity_reports_a_bypass_user_that_no_longer_resolves(): - """A deleted account is a violation, not a crash. - - The UID cannot be re-derived, so the check cannot say whether the rule is - correct - and an unverifiable bypass is reported rather than assumed good. - Letting the KeyError escape would instead kill the watchdog thread, which is - strictly worse: the session would then be unmonitored *and* nothing would - say so. - """ - nft = _healthy_nft("meta skuid 1000 accept") - lock = {"bypass_users": ["ghost"], "bypass_groups": []} - - with _integrity_env(nft, lock), patch("pwd.getpwnam", side_effect=KeyError("no such user")): - comp, err = wd.check_system_integrity() - - assert comp == "firewall" - assert "bypass user 'ghost' cannot be resolved on system" in err - - -def test_integrity_reports_a_bypass_group_that_no_longer_resolves(): - nft = _healthy_nft() - lock = {"bypass_users": [], "bypass_groups": ["ghosts"]} - - with _integrity_env(nft, lock), patch("grp.getgrnam", side_effect=KeyError("no such group")): - comp, err = wd.check_system_integrity() - - assert comp == "firewall" - assert "bypass group 'ghosts' cannot be resolved on system" in err - - -def test_integrity_checks_every_bypass_entry_not_just_the_first(): - """The loop examines every entry, not only the first. - - The first user resolves and its rule is present, so a check that stopped - after one entry would return a clean verdict. The violation has to come - from the *second* user, which is what makes this distinguishable from - checking `bypass_users[0]` and returning. - """ - nft = _healthy_nft("meta skuid 1000 accept") - lock = {"bypass_users": ["alice", "bob"], "bypass_groups": []} - - def getpwnam(name): - return MagicMock(pw_uid={"alice": 1000, "bob": 1001}[name]) - - with _integrity_env(nft, lock), patch("pwd.getpwnam", side_effect=getpwnam): - comp, err = wd.check_system_integrity() - - assert comp == "firewall" - assert "'bob' (UID 1001)" in err - - -def test_integrity_checks_groups_even_when_every_user_rule_is_present(): - """The group loop runs after the user loop, so it needs its own evidence. - - A `return` misplaced at the end of the user loop would make this pass for - the wrong reason, and no other test in this file would notice. - """ - nft = _healthy_nft("meta skuid 1000 accept") - lock = {"bypass_users": ["alice"], "bypass_groups": ["devs"]} - - with ( - _integrity_env(nft, lock), - patch("pwd.getpwnam", return_value=MagicMock(pw_uid=1000)), - patch("grp.getgrnam", return_value=MagicMock(gr_gid=1000)), - ): - comp, err = wd.check_system_integrity() - - assert comp == "firewall" - assert "bypass rule for group 'devs'" in err - - # --------------------------------------------------------------------------- # resolv.conf content: the DNS leak the mount check cannot see # --------------------------------------------------------------------------- @@ -658,7 +455,7 @@ def test_integrity_accepts_both_loopback_families(): """ with ( _dns_content_env("nameserver 127.0.0.1\nnameserver ::1\n"), - patch("subprocess.run", return_value=MagicMock(stdout=_healthy_nft(), returncode=0)), + patch("subprocess.run", return_value=MagicMock(stdout="", returncode=0)), patch("ttp.tor_control.get_controller", return_value=None), ): comp, _ = wd.check_system_integrity() @@ -995,7 +792,7 @@ def test_a_fired_leak_reject_is_an_integrity_failure(counter: str, expected: str with ( patch("ttp.watchdog.integrity.dns._is_mount_point", return_value=True), patch.object(Path, "read_text", return_value="nameserver 127.0.0.1\n"), - patch("ttp.watchdog.integrity.state.read_lock", return_value=None), + patch("ttp.watchdog.integrity.state.read_lock", return_value=SESSION), patch("ttp.watchdog.integrity.subprocess.run") as run, patch("ttp.watchdog.integrity.firewall.read_counters", return_value={counter: 3}), ): @@ -1014,7 +811,7 @@ def _check_with_counters(counters: dict[str, int]) -> tuple[str | None, str | No with ( patch("ttp.watchdog.integrity.dns._is_mount_point", return_value=True), patch.object(Path, "read_text", return_value="nameserver 127.0.0.1\n"), - patch("ttp.watchdog.integrity.state.read_lock", return_value=None), + patch("ttp.watchdog.integrity.state.read_lock", return_value=SESSION), patch("ttp.watchdog.integrity.subprocess.run") as run, patch("ttp.watchdog.integrity.firewall.read_counters", return_value=counters), patch("ttp.watchdog.integrity.tor_control.get_controller", return_value=None), @@ -1072,7 +869,7 @@ def test_counters_that_cannot_be_read_are_not_an_integrity_failure() -> None: with ( patch("ttp.watchdog.integrity.dns._is_mount_point", return_value=True), patch.object(Path, "read_text", return_value="nameserver 127.0.0.1\n"), - patch("ttp.watchdog.integrity.state.read_lock", return_value=None), + patch("ttp.watchdog.integrity.state.read_lock", return_value=SESSION), patch("ttp.watchdog.integrity.subprocess.run") as run, patch("ttp.watchdog.integrity.firewall.read_counters", return_value={}), patch("ttp.watchdog.integrity.tor_control.get_controller", return_value=None), @@ -1120,6 +917,15 @@ def test_the_table_the_session_applied_passes() -> None: assert _check_with_fingerprint("a" * 64, "a" * 64)[0] != "firewall" -def test_a_session_from_before_fingerprints_is_not_failed_for_lacking_one() -> None: - """A lock written by an older TTP has no fingerprint: nothing to compare, not a mismatch.""" - assert _check_with_fingerprint(None, "b" * 64)[0] != "firewall" +def test_a_session_without_a_recorded_table_is_a_firewall_failure() -> None: + """Passing it would let a start that could not read its table back turn this check off.""" + component, message = _check_with_fingerprint(None, "b" * 64) + assert component == "firewall" + assert "records no nftables table" in message + + +def test_a_table_that_cannot_be_read_is_a_firewall_failure() -> None: + """A deleted table, or an nft that fails, is not "nothing changed".""" + component, message = _check_with_fingerprint("a" * 64, None) + assert component == "firewall" + assert "missing or unreadable" in message diff --git a/ttp/commands/start.py b/ttp/commands/start.py index 27c3fb1..3aab1d6 100644 --- a/ttp/commands/start.py +++ b/ttp/commands/start.py @@ -384,6 +384,12 @@ def protect_vpn(tor_user: str) -> None: if info.get("apparmor") is not None: kwargs_lock["apparmor"] = info["apparmor"] + # Taken now, with the rules and the DNS overlay in place: the table the + # watchdog must find for the rest of the session (#80). Without one it + # has nothing to compare against, so the session does not start. + fingerprint = firewall.table_fingerprint() + if fingerprint is None: + raise StateError("Cannot read back the nftables table just applied") state.write_lock( dns_backup=dns_backup, transport_port=transport_port, @@ -394,9 +400,7 @@ def protect_vpn(tor_user: str) -> None: external_daemon=external_daemon, no_ipv6=no_ipv6, tor_uid=tor_uid_val, - # Taken now, with the rules and the DNS overlay in place: the table - # the watchdog must find for the rest of the session (#80). - table_fingerprint=firewall.table_fingerprint(), + table_fingerprint=fingerprint, watchdog_requested=watchdog, settings=selected.settings.snapshot(), settings_origins=selected.origins, diff --git a/ttp/watchdog/integrity.py b/ttp/watchdog/integrity.py index 80459d2..015aec1 100644 --- a/ttp/watchdog/integrity.py +++ b/ttp/watchdog/integrity.py @@ -116,56 +116,20 @@ def check_system_integrity() -> tuple[Optional[str], Optional[str]]: if res_resolved.stdout.strip() != "active": return "dns", "systemd-resolved systemd service is inactive/stopped" - # 2. Firewall Ruleset check - res = subprocess.run( - [resolve("nft"), "list", "table", "inet", "ttp"], - capture_output=True, - text=True, - check=False, - timeout=10, - ) - if res.returncode != 0: - return "firewall", "nftables 'inet ttp' table is missing" - if "chain filter_out" not in res.stdout: - return ( - "firewall", - "nftables 'inet ttp' table is incomplete (missing filter_out)", - ) - - # The table must be the one this session applied, rule for rule (#80). + # 2. The table must be the one this session applied, rule for rule (#80). # Chain names alone let a flushed table through - no rules, everything in # cleartext - and any single rule deleted or `accept` inserted likewise. + # Nothing recorded to compare against is a failure, not a pass: otherwise a + # start that could not read the table back would turn this check off. recorded = lock.get("table_fingerprint") if lock else None - if recorded and firewall.table_fingerprint() != recorded: + if not recorded: + return "firewall", "the session records no nftables table to compare against" + current = firewall.table_fingerprint() + if current is None: + return "firewall", "nftables 'inet ttp' table is missing or unreadable" + if current != recorded: return "firewall", "nftables 'inet ttp' table differs from the one this session applied" - # Verify bypass rules if configured in state lock - if lock: - import grp - import pwd - - for u in lock.get("bypass_users", []): - try: - uid = int(u) if u.isdigit() else pwd.getpwnam(u).pw_uid - if f"meta skuid {uid} accept" not in res.stdout: - return ( - "firewall", - f"bypass rule for user '{u}' (UID {uid}) is missing", - ) - except KeyError: - return "firewall", f"bypass user '{u}' cannot be resolved on system" - - for g in lock.get("bypass_groups", []): - try: - gid = int(g) if g.isdigit() else grp.getgrnam(g).gr_gid - if f"meta skgid {gid} accept" not in res.stdout: - return ( - "firewall", - f"bypass rule for group '{g}' (GID {gid}) is missing", - ) - except KeyError: - return "firewall", f"bypass group '{g}' cannot be resolved on system" - # 2b. The DoH/DoT rejects must be unreachable, so a non-zero count is an alarm # about TTP itself rather than about the user's DNS habits. Per ADR 0012, # `nat output` has already rewritten a non-bypassed process's destination to From caee55437c15783c9bb947aa48e50e83e7e77e3e Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:41:23 +0100 Subject: [PATCH 03/16] Keep the session when stop cannot remove its table do_stop deleted the lock in a finally even when destroy_rules failed, so status and stop lost a session whose table was still loaded. It now keeps the lock and exits 8. A failed DNS restore exits 1 instead of 0, and a conntrack flush timeout no longer aborts the teardown. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- CHANGELOG.md | 9 +++++++ tests/test_cli_stop.py | 51 ++++++++++++++++++++++++++++++++++++++- tests/test_dns.py | 4 ++- ttp/commands/lifecycle.py | 29 ++++++++++++++++------ ttp/dns.py | 13 +++++++--- 5 files changed, 93 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18fe54e..49f4a60 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- `ttp stop` deleted the session lock even when it could not remove the + `inet ttp` table. The table stayed (no network, or an empty table and no + protection), while `ttp status` reported no session and a second `ttp stop` + answered "No active session found". The lock now stays, and `stop` exits + with `8` and points to `ttp stop --restore-only`. When the DNS overlay could + not be removed, `stop` printed "Session terminated" and exited `0`; it now + says so and exits `1`. A `conntrack -F` that timed out aborted the teardown + with a traceback before the rules were removed; it is now a warning, like a + failed flush. - The watchdog compares the live `inet ttp` table with the fingerprint that `ttp start` records (#80). If `nft` could not list the table at that moment, for example after a 10-second timeout, `start` recorded no fingerprint and the diff --git a/tests/test_cli_stop.py b/tests/test_cli_stop.py index 4b9a880..ce784d0 100644 --- a/tests/test_cli_stop.py +++ b/tests/test_cli_stop.py @@ -389,7 +389,7 @@ def test_stop_graceful_teardown_sequence( mock_sleep.side_effect = lambda *args, **kwargs: call_order.append("sleep") mock_run.side_effect = lambda *args, **kwargs: call_order.append("run") mock_destroy.side_effect = lambda *args, **kwargs: call_order.append("destroy") - mock_restore.side_effect = lambda *args, **kwargs: call_order.append("restore") + mock_restore.side_effect = lambda *args, **kwargs: call_order.append("restore") or True mock_delete.side_effect = lambda *args, **kwargs: call_order.append("delete") def close_sockets(port): @@ -485,10 +485,59 @@ def test_do_stop_clears_the_lock_even_when_dns_restore_fails(): patch("ttp.commands.lifecycle.dns.restore_dns", side_effect=RuntimeError("umount timed out")), patch("ttp.commands.lifecycle.resolve_optional", return_value=None), patch("ttp.state.delete_lock") as delete_lock, + pytest.raises(typer.Exit) as exc, ): lifecycle.do_stop() delete_lock.assert_called_once() + # The session is over, but DNS may still point at Tor: not a success. + assert exc.value.exit_code == 1 + + +def test_do_stop_keeps_the_lock_when_the_table_cannot_be_removed(): + """The table may still hold the host: `status` and `stop` must still see the session.""" + from ttp.exceptions import FirewallError + + with ( + patch("ttp.state.read_lock", return_value={"pid": 1, "tor_uid": 107}), + patch("ttp.commands.lifecycle.firewall.destroy_rules", side_effect=FirewallError("nft: busy")), + patch("ttp.commands.lifecycle.firewall.apply_teardown_lockdown"), + patch("ttp.commands.lifecycle.firewall.apply_active_socket_slaughter"), + patch("ttp.commands.lifecycle.close_redirected_or_retain"), + patch("ttp.commands.lifecycle.tor_install"), + patch("ttp.tor_control.graceful_shutdown"), + patch("ttp.commands.lifecycle.time.sleep"), + patch("ttp.commands.lifecycle.dns.restore_dns") as restore_dns, + patch("ttp.commands.lifecycle.resolve_optional", return_value=None), + patch("ttp.state.delete_lock") as delete_lock, + pytest.raises(typer.Exit) as exc, + ): + lifecycle.do_stop() + + assert exc.value.exit_code == 8 + delete_lock.assert_not_called() + restore_dns.assert_not_called() + + +def test_a_conntrack_flush_that_times_out_does_not_abort_the_teardown(): + import subprocess + + with ( + patch("ttp.state.read_lock", return_value={"pid": 1, "tor_uid": 107}), + patch("ttp.commands.lifecycle.firewall") as firewall, + patch("ttp.commands.lifecycle.close_redirected_or_retain"), + patch("ttp.commands.lifecycle.tor_install"), + patch("ttp.tor_control.graceful_shutdown"), + patch("ttp.commands.lifecycle.time.sleep"), + patch("ttp.commands.lifecycle.dns.restore_dns", return_value=True), + patch("ttp.commands.lifecycle.resolve_optional", return_value="/usr/sbin/conntrack"), + patch("ttp.commands.lifecycle.subprocess.run", side_effect=subprocess.TimeoutExpired("conntrack", 10)), + patch("ttp.state.delete_lock") as delete_lock, + ): + lifecycle.do_stop() + + firewall.destroy_rules.assert_called_once() + delete_lock.assert_called_once() def test_do_stop_is_a_no_op_without_a_lock(): diff --git a/tests/test_dns.py b/tests/test_dns.py index 6a862b1..b27f4a5 100644 --- a/tests/test_dns.py +++ b/tests/test_dns.py @@ -284,8 +284,10 @@ def test_restore_dns_continues_after_a_failed_unmount(_mock_resolv_conf, caplog) patch("ttp.dns_resolved.restore_resolved") as mock_restore, caplog.at_level(logging.WARNING, logger="ttp"), ): - dns.restore_dns({"mount_target": str(fake_resolv), "systemd_resolved": True}) + restored = dns.restore_dns({"mount_target": str(fake_resolv), "systemd_resolved": True}) + # Reported, so `ttp stop` does not call it a clean teardown. + assert restored is False # Steps 2 and 3 ran regardless. assert mock_restore.call_count == 1 assert not fake_runtime.exists() diff --git a/ttp/commands/lifecycle.py b/ttp/commands/lifecycle.py index 942cd13..5b67f24 100644 --- a/ttp/commands/lifecycle.py +++ b/ttp/commands/lifecycle.py @@ -19,6 +19,7 @@ get_uid_from_port, logger, ) +from ttp.exceptions import FirewallError from ttp.paths import resolve_optional @@ -133,10 +134,10 @@ def do_stop() -> None: check=True, timeout=10, ) - except subprocess.CalledProcessError as e: + except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e: logger.warning( "Failed to flush conntrack table: %s", - e.stderr.strip() if e.stderr else str(e), + e.stderr.strip() if isinstance(e.stderr, str) and e.stderr else str(e), ) else: logger.debug("conntrack binary not found, skipping flush.") @@ -144,12 +145,23 @@ def do_stop() -> None: console.print(f"{_PREFIX} Removing nftables rules...") try: firewall.destroy_rules() + except FirewallError as exc: + import typer + + from ttp.commands._common import print_error + # The table may still hold the host, or be flushed and empty: either way + # the session is not over, so its lock stays for `status` and `stop`. + print_error("Teardown Retained", f"{exc}. Retry with: sudo ttp stop --restore-only") + raise typer.Exit(code=8) + dns_restored = True + try: console.print(f"{_PREFIX} Restoring DNS...") try: - dns.restore_dns(lock.get("dns_backup")) + dns_restored = dns.restore_dns(lock.get("dns_backup")) except Exception as e: logger.error("DNS restoration failed, continuing teardown: %s", e) + dns_restored = False if lock.get("vpn"): from ttp.vpn import VPNError from ttp.vpn_guard import release_after_stop @@ -175,12 +187,15 @@ def do_stop() -> None: from ttp.notifications.service import finish_notifications result = finish_notifications(lock) - if result.exit_code: + for diagnostic in result.diagnostics if result.exit_code else (): + print_error(diagnostic.reason, diagnostic.message) + if not dns_restored: + print_error("DNS Not Restored", "The DNS overlay may still be in place. Run: sudo ttp stop --restore-only") + if result.exit_code or not dns_restored: import typer - for diagnostic in result.diagnostics: - print_error(diagnostic.reason, diagnostic.message) - raise typer.Exit(code=int(result.exit_code)) + # 1 (error) takes precedence over 9 (notification failure). + raise typer.Exit(code=1 if not dns_restored else int(result.exit_code)) def restore_without_session() -> dict | None: diff --git a/ttp/dns.py b/ttp/dns.py index 8da8c1a..73217a4 100644 --- a/ttp/dns.py +++ b/ttp/dns.py @@ -198,12 +198,14 @@ def apply_dns(disable_ipv6: bool = False, dns_port: int = 9054) -> dict[str, Any raise DNSError(f"Failed to apply DNS configuration: {e}") from e -def restore_dns(backup: dict[str, Any] | None) -> None: +def restore_dns(backup: dict[str, Any] | None) -> bool: """Restore original system DNS settings by unmounting the overlay. If systemd-resolved was active on startup, also removes the volatile - drop-in configuration and restarts it. + drop-in configuration and restarts it. Returns False when a step failed, + so ``ttp stop`` does not report a teardown that left DNS broken. """ + restored = True # The backup comes from the session lock, which is state rather than a # trusted structure. A wrong type here used to raise out of do_stop after # the firewall was already destroyed, leaving the overlay mounted with no @@ -232,9 +234,10 @@ def restore_dns(backup: dict[str, Any] | None) -> None: timeout=10, ) logger.info("Successfully unmounted DNS overlay on %s", mount_target) - except subprocess.CalledProcessError as e: - err_msg = e.stderr.strip() if e.stderr else str(e) + except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e: + err_msg = e.stderr.strip() if isinstance(e.stderr, str) and e.stderr else str(e) logger.warning("Failed to unmount DNS overlay on %s: %s", mount_target, err_msg) + restored = False else: logger.debug("DNS target %s is not mounted, skipping unmount", mount_target) @@ -246,6 +249,7 @@ def restore_dns(backup: dict[str, Any] | None) -> None: dns_resolved.restore_resolved() except Exception as e: logger.warning("Failed to restore systemd-resolved: %s", e) + restored = False # 3. Cleanup the ephemeral file to free tmpfs space try: @@ -253,3 +257,4 @@ def restore_dns(backup: dict[str, Any] | None) -> None: RUNTIME_RESOLV.unlink() except OSError as e: logger.debug("Failed to remove runtime resolv.conf: %s", e) + return restored From a2d7ecc33edc7c79de85aaed5d26aba7832c95b5 Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:42:38 +0100 Subject: [PATCH 04/16] Test that both tables get the same VPN transport exceptions transport_expressions (the guard's JSON) and transport_rules (TTP's nft text) are written apart, and nothing compared them. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- tests/test_vpn.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/test_vpn.py b/tests/test_vpn.py index 9304053..b6edd77 100644 --- a/tests/test_vpn.py +++ b/tests/test_vpn.py @@ -586,3 +586,30 @@ def forbidden_probe(): assert len(scripts) == 1 assert "meta mark 51820 ip daddr 192.0.2.1 udp dport 51820 accept" in scripts[0] assert "ttp-bypass.slice" not in scripts[0] + + +def _nft_text(expression: list[dict]) -> str: + """Render the guard's JSON matches the way `nft` prints them, for comparison.""" + words = [] + for item in expression: + match = item["match"] + left, right = match["left"], match["right"] + if "meta" in left: + key = left["meta"]["key"] + right = {2: "ipv4", 10: "ipv6"}[right] if key == "nfproto" else right + words.append(f"meta {key}") + else: + words.append(f"{left['payload']['protocol']} {left['payload']['field']}") + if isinstance(right, dict): + right = "{ " + ", ".join(map(str, right["set"])) + " }" + words.append(str(right)) + return " ".join(words) + " accept" + + +@pytest.mark.parametrize("address", ["192.0.2.1", "2001:db8::1"]) +def test_both_tables_get_the_same_transport_exceptions(address: str) -> None: + """The VPN guard (JSON) and TTP's filter (text) are written apart; editing one alone + would let them disagree on what may leave the physical interface.""" + vpn_policy = vpn.VPNPolicy(UUID, ACTIVE, "wg0", 7, "eth0", 2, PEER, address, 51820, 51820, False) + rendered = [_nft_text(expression) for expression in vpn_guard.transport_expressions(vpn_policy)] + assert rendered == vpn_guard.transport_rules(vpn_policy).splitlines() From 69f0274ab429cc2d1ddc341b72b6ca7daed7c17e Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:45:44 +0100 Subject: [PATCH 05/16] Stop writing watchdog_active and watchdog_pid to the lock Nothing reads them since watchdog status asks the live unit; they only cost a lock rewrite on every watchdog start and stop. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- tests/test_watchdog.py | 9 ++++----- tests/test_watchdog_settled.py | 2 +- ttp/state.py | 8 -------- ttp/watchdog/service.py | 7 ------- 4 files changed, 5 insertions(+), 21 deletions(-) diff --git a/tests/test_watchdog.py b/tests/test_watchdog.py index f3410e0..77601d9 100644 --- a/tests/test_watchdog.py +++ b/tests/test_watchdog.py @@ -100,15 +100,14 @@ def test_write_watchdog_service_unit(temp_watchdog_path): @patch("subprocess.run") @patch("ttp.state.update_lock_keys") def test_start_watchdog_success(mock_update, mock_run, temp_watchdog_path): - """start_watchdog writes the unit, starts it, confirms it is up, records it.""" + """start_watchdog writes the unit, starts it and confirms it is up.""" mock_run.return_value = MagicMock(stdout="ActiveState=active\nMainPID=12345\n", returncode=0) with patch("ttp.watchdog.service.watchdog_observation", return_value={"value": "healthy", "pid": 12345}): wd.start_watchdog() assert temp_watchdog_path.exists() - mock_update.assert_any_call(watchdog_requested=True) - mock_update.assert_any_call(watchdog_active=True, watchdog_pid=12345) + mock_update.assert_called_once_with(watchdog_requested=True) @patch("subprocess.run") @@ -139,7 +138,7 @@ def test_start_watchdog_failure(mock_run, temp_watchdog_path): @patch("subprocess.run") @patch("ttp.state.update_lock_keys") def test_stop_watchdog(mock_update, mock_run, temp_watchdog_path): - """stop_watchdog stops service, unlinks unit file, reloads systemd daemon, and updates state.""" + """stop_watchdog stops the service, unlinks the unit file and reloads systemd.""" # Write a dummy unit first temp_watchdog_path.parent.mkdir(parents=True, exist_ok=True) temp_watchdog_path.write_text("dummy", encoding="utf-8") @@ -149,7 +148,7 @@ def test_stop_watchdog(mock_update, mock_run, temp_watchdog_path): assert not temp_watchdog_path.exists() assert mock_run.call_count == 2 - mock_update.assert_called_once_with(watchdog_active=False, watchdog_pid=None) + mock_update.assert_not_called() # 4. check_system_integrity diff --git a/tests/test_watchdog_settled.py b/tests/test_watchdog_settled.py index 637485f..02695f0 100644 --- a/tests/test_watchdog_settled.py +++ b/tests/test_watchdog_settled.py @@ -138,4 +138,4 @@ def test_watchdog_start_tolerates_an_event_right_after_readiness(monkeypatch, cl monkeypatch.setattr("ttp.session_safety.emergency_latched", lambda *a, **k: False) observations(monkeypatch, INVALIDATED, HEALTHY) service.start_watchdog() - state.update_lock_keys.assert_called_with(watchdog_active=True, watchdog_pid=7) + state.update_lock_keys.assert_called_once_with(watchdog_requested=True) diff --git a/ttp/state.py b/ttp/state.py index 706615a..49d299c 100644 --- a/ttp/state.py +++ b/ttp/state.py @@ -145,8 +145,6 @@ def write_lock( dns_port: int = 9054, allow_root: bool = False, lan_bypass: bool = True, - watchdog_active: bool = False, - watchdog_pid: int | None = None, interface: str | None = None, bypass_users: list[str] | None = None, bypass_groups: list[str] | None = None, @@ -181,10 +179,6 @@ def write_lock( True to allow root processes to bypass Tor. lan_bypass: True to exempt LAN subnet traffic from Tor routing. - watchdog_active: - True if the watchdog background daemon is active. - watchdog_pid: - PID of the active watchdog daemon if running. interface: The name of the primary active interface being proxyed. bypass_users: @@ -220,8 +214,6 @@ def write_lock( "dns_port": dns_port, "allow_root": allow_root, "lan_bypass": lan_bypass, - "watchdog_active": watchdog_active, - "watchdog_pid": watchdog_pid, "interface": interface, "bypass_users": bypass_users if bypass_users is not None else [], "bypass_groups": bypass_groups if bypass_groups is not None else [], diff --git a/ttp/watchdog/service.py b/ttp/watchdog/service.py index 4d82ea2..07a8468 100644 --- a/ttp/watchdog/service.py +++ b/ttp/watchdog/service.py @@ -273,7 +273,6 @@ def start_watchdog() -> None: observed = settled_watchdog_observation(settings.watchdog) if observed["value"] != "healthy" or emergency_latched(lock): raise TorError(f"Required supervisor is not ready and healthy ({observed['reason']})") - state.update_lock_keys(watchdog_active=True, watchdog_pid=observed["pid"]) logger.info("TTP watchdog ready (PID: %s).", observed["pid"]) except Exception as exc: logger.error("Required watchdog unavailable: %s", exc) @@ -297,10 +296,4 @@ def stop_watchdog() -> None: check=False, timeout=10, ) - - try: - state.update_lock_keys(watchdog_active=False, watchdog_pid=None) - except Exception: - # Lock might be already removed or corrupt; ignore. - pass logger.info("TTP watchdog service stopped and cleaned up.") From b56c12ae25954d1e275af3f0694d087bf5d0790e Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:48:53 +0100 Subject: [PATCH 06/16] Drop the pre-0.5 orphan recovery from start Only a lock without session_id reached it, i.e. one written by 0.4.x and still in /run after an upgrade mid-session. Every 0.5 session was already refused with 'Session Already Present' and ended by 'ttp stop', which also handles an old lock. The docs promising auto-recovery after kill -9 were wrong for 0.5 and are corrected. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- README.md | 2 +- docs/architecture.md | 7 +- docs/security-assessment.md | 3 +- docs/web/explanation/startup.md | 2 +- docs/web/how-to/dnssec.md | 2 +- docs/web/tutorials/diagnosing-failures.md | 4 +- tests/test_cli_misc.py | 12 +- tests/test_cli_start.py | 44 +---- tests/test_state.py | 187 +--------------------- ttp/commands/_preflight.py | 34 ++-- ttp/commands/lifecycle.py | 7 +- ttp/state.py | 82 ---------- 12 files changed, 32 insertions(+), 354 deletions(-) diff --git a/README.md b/README.md index 051e6e0..5eca6a6 100644 --- a/README.md +++ b/README.md @@ -298,7 +298,7 @@ TTP is designed to always restore your network, even in edge cases: | :----------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ttp stop` | **Zero-leak cleanup**: stops the watchdog, applies the teardown lockdown, shuts Tor down gracefully, closes every redirected connection's socket and verifies it is gone (otherwise exits 8 and keeps protection), flushes connection tracking, removes the `inet ttp` table, restores DNS, and deletes the lock file - the lock last, even if a step before it fails | | Ctrl+C / `kill` | Signal handler catches `SIGINT`/`SIGTERM` and runs normal cleanup before exit | -| `kill -9` / Power Outage | Next `ttp start` detects the orphaned lock file, clears any stale mount stacks, and auto-restores | +| `kill -9` / Power Outage | A power cut clears the session with `tmpfs`. After a `kill -9`, the session (rules and DNS overlay) stays fail-closed until `sudo ttp stop` | | Manual emergency | Run `sudo ./scripts/restore-network.sh` to flush all nftables rules, reset DNS, and delete the lock file | ## Known Behavior & Limitations diff --git a/docs/architecture.md b/docs/architecture.md index 69a0a78..36f19dc 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -70,7 +70,7 @@ The project is divided into independent Python modules. Each module has a single ### 2.1 Execution Flow - `start` 1. **cli**: Verifies root execution. -2. **state**: Checks for existing/orphaned locks and verifies `tmpfs` free space (**pre-flight check**). +2. **state**: Refuses to start over any recorded session and verifies `tmpfs` free space (**pre-flight check**). 3. **detect**: Verifies Tor installation and config. 4. **install**: Checks Tor readiness via `tor_install.py`. Enforces strict **No Auto-Install policy** (if Tor or required Pluggable Transports are missing, displays distro package guidance and official doc URLs, then exits with code 1 before any network change). Performs **SELinux optimization** on Fedora. 5. **firewall**: Generates and atomically applies rules in isolated `inet ttp` table via `ttp/firewall/`. @@ -108,7 +108,7 @@ When started in Bring Your Own Daemon (BYOD) mode, TTP delegates Tor lifecycle m > **Crash (SIGTERM/SIGINT):** Signal handler ensures restoration before shutdown. > > [!IMPORTANT] -> **Worst-case (kill -9):** Next `ttp start` detects orphaned lock and auto-restores. +> **Worst-case (kill -9):** The rules and DNS overlay stay, fail-closed; `sudo ttp stop` (or `--restore-only`) removes them. ### 2.3 Flow - `refresh` @@ -182,7 +182,6 @@ Manages `/run/ttp/ttp.lock` (JSON) on a volatile `tmpfs` mount. This ensures tha * **Directory Permissions**: `/run/ttp` is always root-owned: `0750` with group `ttp-watchdog`, so the watchdog can read the lock, or `0700` when that account does not exist. The watchdog writes only to its own `/run/ttp/watchdog`. Handing the directory itself to the watchdog account would let it swap root's lock, log, `resolv.conf` or ruleset for a symlink (audit 2026-09). * **Lock File Permissions**: `ttp.lock` is `0640` root:`ttp-watchdog` (read-only for the watchdog), or `0600`, securing bridge lines and configuration from other local users. -* **PID Recycling Protection**: When checking for orphaned processes, `state.py` reads `/proc/{pid}/cmdline` and matches whole argv tokens, not a substring, to verify that the PID still belongs to a `ttp` process (`"http"` contains `"ttp"`). Also handles the **tmpfs pre-flight check** (`check_tmpfs_space`) to ensure at least 5MB of RAM is free before starting, preventing `ENOSPC` crashes mid-setup. Persistent configurations (like UX flags) are delegated to `ux.py`. @@ -515,7 +514,7 @@ suites. * **`test_tor_detect.py`**: Verifies dictionary output across varying torrc and process states. * **`test_firewall.py`**: Asserts DNS redirect appears BEFORE LAN bypass (critical - gateway DNS leak prevention), BEFORE loopback accept, BEFORE TCP redirect. Verifies IPv6 drop (when unsupported) or redirection (when supported), DoT rejection, DoH IP-level blocking, bypass user/group (split tunneling) rule injection, emergency killswitch table application, and teardown lockdown rule construction/execution. * **`test_dns.py`**: Asserts correct mount --bind overlay, stale mount cleanup, and lazy umount. -* **`test_state.py`**: Asserts lock creation, reading, and orphan detection. +* **`test_state.py`**: Asserts lock creation and reading. * **`test_fsm.py`**: Verifies WatchdogFSM state machine transitions, triggers, and callback handlers under mock conditions. * **`test_cli_*.py`** (`start`, `stop`, `bypass`, `misc`): Verify command orchestration, option injection, UI flow, non-root OSError safety, stop command execution order (lockdown -> shutdown -> conntrack flush -> destroy), and conntrack handling when utility is missing. * **`test_tor_control.py`**: Verifies Tor daemon interaction, IP checking logic, and circuit bootstrap/rotation. diff --git a/docs/security-assessment.md b/docs/security-assessment.md index 5940e04..b9198b6 100644 --- a/docs/security-assessment.md +++ b/docs/security-assessment.md @@ -180,7 +180,6 @@ TTP is designed to achieve the following security properties, in order of priori | Threat | STRIDE Category | Description | Mitigation | Residual Risk | | :--------------------------------------- | :--------------------- | :------------------------------------------------------------------- | :------------------------------------------------------------------- | :---------------------------- | | Lock file tampering by unprivileged user | Tampering | An attacker modifies `/run/ttp/ttp.lock` to spoof session state | Lock file is owned by root (`chmod 600`); tmpfs path is root-managed | **Low.** Requires root. | -| TOCTOU race on orphan detection | Elevation of Privilege | Between orphan detection and cleanup, a new session could be started | Atomic lock write + PID validation; only root can run `ttp start` | **Low.** Root-only execution. | ### 3.5 `watchdog/` — Session Watchdog Package @@ -414,7 +413,7 @@ Dependency CVE scanning, Dependabot configuration, and the remediation SLA are d | Cookie-authenticated Tor control socket | Preventive | ✅ Implemented | | Session watchdog with auto-healing | Detective + Corrective | ✅ Implemented (optional) | | Emergency killswitch (two-strike policy) | Corrective | ✅ Implemented | -| Crash recovery (orphaned lock detection) | Corrective | ✅ Implemented | +| Crash recovery (`ttp stop`, `--restore-only`) | Corrective | ✅ Implemented | | Sigstore artifact signing | Preventive | ✅ Implemented | | Dependabot CVE monitoring | Detective | ✅ Enabled | | `pip-audit` scoped to project | Detective | ✅ Documented | diff --git a/docs/web/explanation/startup.md b/docs/web/explanation/startup.md index baef9cb..5b03500 100644 --- a/docs/web/explanation/startup.md +++ b/docs/web/explanation/startup.md @@ -36,7 +36,7 @@ No outcome that leaves the host unprotected exits `0`. | Phase | What changes | Traffic of an ordinary process | On failure | On SIGINT / SIGTERM | | :--- | :--- | :--- | :--- | :--- | -| 0. Preflight | Nothing on the network. Settings, options, root and systemd, ports, DNSSEC, the session state (an orphan left by a crashed session is recovered here), a retained VPN guard, the record store | Cleartext | Exit `1`, `2`, `4` or `10`; nothing changed | Exit `1`; an orphan recovery in progress is completed by stopping what it found | +| 0. Preflight | Nothing on the network. Settings, options, root and systemd, ports, DNSSEC, the session state (any recorded session, even a crashed one, must be stopped first), a retained VPN guard, the record store | Cleartext | Exit `1`, `2`, `4` or `10`; nothing changed | Exit `1`; nothing changed | | 1. Tor | Managed mode: Tor is installed if needed and `ttp-tor` starts. Required-VPN mode: the VPN guard is installed **before** Tor starts, and is the first barrier. External daemon: only its UID is resolved | Cleartext (required-VPN: confined to the tunnel by the guard) | Exit `1` (Tor or a pluggable transport missing: exit `1` since 0.5.1) | Undone like `stop --restore-only`, exit `1`; a VPN guard is retained, exit `10` | | 2. Rules | The `inet ttp` table, in **one** `nft` transaction: the first barrier outside required-VPN mode | Redirected to Tor or rejected from the commit on, DNS included (redirected to the DNSPort) | Own Tor stopped, table destroyed: cleartext, exit `1` | As phase 1 | | 3. DNS | The resolver overlay on `/etc/resolv.conf`, and the systemd-resolved drop-in | As phase 2 | `apply_dns` undoes its own partial change; own Tor stopped, table destroyed: cleartext, exit `1` | As phase 1; the overlay is found on the host, so a half-applied one is removed too | diff --git a/docs/web/how-to/dnssec.md b/docs/web/how-to/dnssec.md index 314fc7f..e8aa31c 100644 --- a/docs/web/how-to/dnssec.md +++ b/docs/web/how-to/dnssec.md @@ -28,7 +28,7 @@ the unprivileged verification process, without granting write access to others. If any current non-loopback interface explicitly requires `DNSSEC=yes`, TTP prints an error naming that interface and exits with **code 4**. The check runs -before Tor setup, orphan recovery, firewall changes or DNS changes. `ttp restart` +before Tor setup, firewall changes or DNS changes. `ttp restart` also checks before stopping the existing session; a refusal leaves that session in place. This is a configuration refusal, not a session with degraded DNS. diff --git a/docs/web/tutorials/diagnosing-failures.md b/docs/web/tutorials/diagnosing-failures.md index 99782c0..23a4376 100644 --- a/docs/web/tutorials/diagnosing-failures.md +++ b/docs/web/tutorials/diagnosing-failures.md @@ -86,8 +86,8 @@ same with plain `nft` and `umount`: sudo ./scripts/restore-network.sh ``` -A `kill -9` or a power cut needs neither: the lock lives in `tmpfs`, and the next -`ttp start` detects an orphaned one and recovers before starting. +A power cut needs neither: the lock, the rules and the DNS overlay all live in +memory. After a `kill -9` they stay, fail-closed, and `sudo ttp stop` removes them. To remove TTP from the system entirely - stopping any session, unloading the SELinux module and removing its markers - use `sudo ttp uninstall`, then remove the diff --git a/tests/test_cli_misc.py b/tests/test_cli_misc.py index afdbbcb..326eb4d 100644 --- a/tests/test_cli_misc.py +++ b/tests/test_cli_misc.py @@ -63,7 +63,6 @@ def isolated_session(tmp_path, monkeypatch): @patch("ttp.tor_control.get_exit_ip", return_value="5.6.7.8") -@patch("ttp.state.is_orphan", return_value=False) @patch( "ttp.state.read_lock", return_value={ @@ -71,7 +70,7 @@ def isolated_session(tmp_path, monkeypatch): "pid": 12345, }, ) -def test_status_active(mock_read, mock_orphan, mock_ip): +def test_status_active(mock_read, mock_ip): """status with active session -> shows IP and timestamp.""" result = runner.invoke(app, ["status"]) assert result.exit_code == 0 @@ -264,7 +263,6 @@ def test_watchdog_status_never_reports_an_unreadable_session_as_not_running(monk @patch("ttp.tor_control.get_exit_ip", return_value="5.6.7.8") -@patch("ttp.state.is_orphan", return_value=False) @patch( "ttp.state.read_lock", return_value={ @@ -274,7 +272,7 @@ def test_watchdog_status_never_reports_an_unreadable_session_as_not_running(monk "dns_port": 9090, }, ) -def test_status_shows_custom_ports(mock_read, mock_orphan, mock_ip): +def test_status_shows_custom_ports(mock_read, mock_ip): """status displays custom ports from the active lock file.""" result = runner.invoke(app, ["status"]) assert result.exit_code == 0 @@ -608,10 +606,9 @@ def test_status_reports_an_unknown_ip_rather_than_guessing(mock_urlopen, mock_re @patch("ttp.tor_control.get_exit_ip", return_value="5.6.7.8") -@patch("ttp.state.is_orphan", return_value=False) @patch("ttp.state.read_lock", return_value={"pid": 1, "no_ipv6": True}) @patch("ttp.tor_detect.is_ipv6_supported", return_value=True) -def test_status_distinguishes_ipv6_dropped_by_us_from_unsupported(mock_v6, mock_read, mock_orphan, mock_ip): +def test_status_distinguishes_ipv6_dropped_by_us_from_unsupported(mock_v6, mock_read, mock_ip): """`--no-ipv6` and "the host has no IPv6" produce the same packets and very different diagnoses, so status must not collapse them into one message.""" result = runner.invoke(app, ["status"]) @@ -619,10 +616,9 @@ def test_status_distinguishes_ipv6_dropped_by_us_from_unsupported(mock_v6, mock_ @patch("ttp.tor_control.get_exit_ip", return_value="5.6.7.8") -@patch("ttp.state.is_orphan", return_value=False) @patch("ttp.state.read_lock", return_value={"pid": 1}) @patch("ttp.tor_detect.is_ipv6_supported", return_value=False) -def test_status_reports_ipv6_unsupported_by_the_host(mock_v6, mock_read, mock_orphan, mock_ip): +def test_status_reports_ipv6_unsupported_by_the_host(mock_v6, mock_read, mock_ip): result = runner.invoke(app, ["status"]) assert "Not supported by host" in result.output diff --git a/tests/test_cli_start.py b/tests/test_cli_start.py index 315ef9d..7b79417 100644 --- a/tests/test_cli_start.py +++ b/tests/test_cli_start.py @@ -100,7 +100,6 @@ def recorded(*args, **kwargs): ), patch("ttp.tor_install.setup_selinux_if_needed"), patch("ttp.state.read_lock", side_effect=recorded), - patch("ttp.state.is_orphan", return_value=False), ): yield @@ -206,47 +205,14 @@ def test_start_requires_root(mock_euid): assert "root" in result.output -@patch("ttp.firewall.runner._run_nft_string") -@patch("ttp.firewall.runner._run_nft") -@patch("ttp.firewall.runner.pwd.getpwnam", return_value=types.SimpleNamespace(pw_uid=110)) -@patch("ttp.tor_install.setup_selinux_if_needed") -@patch("ttp.state.write_lock") -@patch("ttp.state.attempt_recovery") -@patch("ttp.state.read_lock", return_value={"pid": 1234}) -@patch("ttp.state.is_orphan", return_value=True) -def test_start_orphan_recovery( - mock_orphan, - mock_read, - mock_recovery, - mock_write, - mock_selinux, - mock_pwd, - mock_run_nft, - mock_nft_str, - mock_base_start, -): - """start with orphaned session (PID dead) -> auto-recovers and continues.""" - mock_read.side_effect = lambda **kwargs: ( - {"session_id": "test-session", "phase": "running", **mock_write.call_args.kwargs} - if mock_write.called - else {"pid": 1234} - ) - result = runner.invoke(app, ["start"]) - assert result.exit_code == 0, result.output - assert "recovering" in result.output.lower() - assert mock_recovery.call_count == 1 - assert mock_nft_str.call_count == 1 - assert "127.0.0.1:9041" in mock_nft_str.call_args[0][0] - - +@patch("ttp.firewall.apply_rules") @patch("ttp.state.read_lock", return_value={"pid": 1234}) -@patch("ttp.state.is_orphan", return_value=False) -def test_start_concurrency_error(mock_orphan, mock_read): - """start with another TTP instance running (PID alive) -> error.""" +def test_start_refuses_a_lock_left_by_an_older_ttp(mock_read, mock_apply): + """A pre-0.5 lock has no session_id; its table and overlay are `ttp stop`'s to remove.""" result = runner.invoke(app, ["start"]) assert result.exit_code == 1 - assert "concurrency error" in result.output.lower() - assert mock_read.call_count == 1 + assert "sudo ttp stop" in result.output + mock_apply.assert_not_called() # stop diff --git a/tests/test_state.py b/tests/test_state.py index dbfd782..c406237 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -11,7 +11,7 @@ import json from pathlib import Path -from unittest.mock import MagicMock, mock_open, patch +from unittest.mock import MagicMock, patch import pytest @@ -152,39 +152,6 @@ def test_read_lock_missing(): assert result is None -# is_orphan with dead PID returns True - - -def test_is_orphan_dead_pid(_use_tmp_lock): - """is_orphan with PID not running -> returns True.""" - state.write_lock(pid=999999) - - with patch("ttp.state.os.kill", side_effect=OSError("No such process")): - assert state.is_orphan() is True - - -def test_is_orphan_alive_pid(_use_tmp_lock): - """is_orphan with PID still running -> returns False.""" - state.write_lock(pid=1) - - with ( - patch("ttp.state.os.kill"), - patch("ttp.state._is_pid_ttp", return_value=True), - ): # No exception -> process alive - assert state.is_orphan() is False - - -def test_is_orphan_recycled_pid(_use_tmp_lock): - """is_orphan with PID still running but recycled -> returns True.""" - state.write_lock(pid=1) - - with ( - patch("ttp.state.os.kill"), - patch("ttp.state._is_pid_ttp", return_value=False), - ): # PID is alive but not TTP - assert state.is_orphan() is True - - # delete_lock removes the file @@ -357,120 +324,6 @@ def test_write_lock_file_closes_the_descriptor_on_failure(_use_tmp_lock): state._write_lock_file({"pid": 1}) -# --------------------------------------------------------------------------- -# _is_pid_ttp — the guard against PID recycling -# --------------------------------------------------------------------------- - - -def test_is_pid_ttp_recognises_a_ttp_process(tmp_path: Path): - cmdline = tmp_path / "cmdline" - cmdline.write_bytes(b"/usr/bin/python3\x00/usr/local/bin/ttp\x00start\x00") - real_open = open - with patch("builtins.open", lambda p, *a, **k: real_open(cmdline, *a, **k)): - assert state._is_pid_ttp(4242) is True - - -def test_is_pid_ttp_rejects_an_unrelated_process(tmp_path: Path): - cmdline = tmp_path / "cmdline" - cmdline.write_bytes(b"/usr/bin/nginx\x00-g\x00daemon off;\x00") - real_open = open - with patch("builtins.open", lambda p, *a, **k: real_open(cmdline, *a, **k)): - assert state._is_pid_ttp(4242) is False - - -def test_is_pid_ttp_is_false_for_a_dead_pid(): - with patch("builtins.open", side_effect=FileNotFoundError): - assert state._is_pid_ttp(999999) is False - - -def test_is_pid_ttp_is_false_when_proc_is_unreadable(): - with patch("builtins.open", side_effect=PermissionError): - assert state._is_pid_ttp(1) is False - - -# --------------------------------------------------------------------------- -# is_orphan -# --------------------------------------------------------------------------- - - -def test_is_orphan_false_without_a_lock(_use_tmp_lock): - assert state.is_orphan() is False - - -def test_is_orphan_true_for_a_lock_without_a_pid(_use_tmp_lock): - """A corrupt lock is an orphan: leaving it would block every future session.""" - state.LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) - state.LOCK_PATH.write_text(json.dumps({"transport_port": 9041}), encoding="utf-8") - assert state.is_orphan() is True - - -# --------------------------------------------------------------------------- -# attempt_recovery — the path that runs after a crash, on a machine that may -# still be routing traffic through a half-torn-down firewall -# --------------------------------------------------------------------------- - - -def test_attempt_recovery_restores_and_clears_the_lock(_use_tmp_lock): - state.write_lock(pid=1, dns_backup={"mounted": True}) - destroy_firewall = MagicMock() - restore_dns = MagicMock() - - assert state.attempt_recovery(destroy_firewall, restore_dns) is True - - destroy_firewall.assert_called_once_with() - restore_dns.assert_called_once_with({"mounted": True}) - assert state.read_lock() is None - - -def test_attempt_recovery_without_a_lock_does_nothing(_use_tmp_lock): - destroy_firewall = MagicMock() - restore_dns = MagicMock() - - assert state.attempt_recovery(destroy_firewall, restore_dns) is False - - destroy_firewall.assert_not_called() - restore_dns.assert_not_called() - - -def test_attempt_recovery_deletes_the_lock_even_when_teardown_fails(_use_tmp_lock): - """ - The lock must go even if the firewall teardown raises. Leaving it behind - makes every subsequent `ttp start` refuse to run, on a machine whose network - is already in an unknown state. - """ - state.write_lock(pid=1, dns_backup=None) - destroy_firewall = MagicMock(side_effect=RuntimeError("nft is gone")) - restore_dns = MagicMock() - - with pytest.raises(RuntimeError): - state.attempt_recovery(destroy_firewall, restore_dns) - - assert state.read_lock() is None - restore_dns.assert_not_called() - - -def test_attempt_recovery_deletes_the_lock_when_dns_restore_fails(_use_tmp_lock): - state.write_lock(pid=1, dns_backup={"mounted": True}) - destroy_firewall = MagicMock() - restore_dns = MagicMock(side_effect=OSError("resolv.conf is busy")) - - with pytest.raises(OSError): - state.attempt_recovery(destroy_firewall, restore_dns) - - destroy_firewall.assert_called_once() - assert state.read_lock() is None - - -def test_attempt_recovery_passes_a_missing_dns_backup_as_none(_use_tmp_lock): - state.LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) - state.LOCK_PATH.write_text(json.dumps({"pid": 1}), encoding="utf-8") - restore_dns = MagicMock() - - state.attempt_recovery(MagicMock(), restore_dns) - - restore_dns.assert_called_once_with(None) - - # --------------------------------------------------------------------------- # delete_lock # --------------------------------------------------------------------------- @@ -481,44 +334,6 @@ def test_delete_lock_is_idempotent(_use_tmp_lock): state.delete_lock() # must not raise on a lock that is already gone -# --------------------------------------------------------------------------- -# _is_pid_ttp authenticates a process by /proc//cmdline, which the owner -# of that process chooses. It must match argv tokens, never a substring. -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "cmdline", - [ - pytest.param(b"/usr/bin/curl\x00http://example.invalid/\x00", id="curl-http-url"), - pytest.param(b"/usr/sbin/httpd\x00-DFOREGROUND\x00", id="httpd"), - pytest.param(b"/usr/bin/python3\x00-m\x00http.server\x00", id="python-http-server"), - pytest.param(b"http\x00", id="attacker-chosen-argv0"), - pytest.param(b"/usr/sbin/nginx\x00-g\x00daemon off;\x00", id="unrelated"), - ], -) -def test_is_pid_ttp_rejects_a_process_that_is_not_ttp(cmdline: bytes) -> None: - """ "http" contains "ttp", so a substring test claimed these as ours.""" - with patch("builtins.open", mock_open(read_data=cmdline)): - assert state._is_pid_ttp(4242) is False - - -@pytest.mark.parametrize( - "cmdline", - [ - pytest.param(b"/usr/bin/ttp\x00start\x00", id="console-script"), - pytest.param(b"/usr/bin/sudo\x00ttp\x00start\x00", id="sudo-console-script"), - pytest.param(b"/opt/venv/bin/python3\x00/opt/venv/bin/ttp\x00start\x00", id="venv-script"), - pytest.param(b"/usr/bin/python3\x00-m\x00ttp.cli\x00start\x00", id="module-form"), - ], -) -def test_is_pid_ttp_still_recognises_every_real_invocation(cmdline: bytes) -> None: - """The inverse error is worse: a live session reported as an orphan would - have attempt_recovery() tear down a working session's firewall and DNS.""" - with patch("builtins.open", mock_open(read_data=cmdline)): - assert state._is_pid_ttp(4242) is True - - def test_write_lock_records_the_table_fingerprint(_use_tmp_lock): """#80: the watchdog compares against what the session applied, even after a restart.""" state.write_lock(table_fingerprint="ab" * 32) diff --git a/ttp/commands/_preflight.py b/ttp/commands/_preflight.py index ea3de48..b328f56 100644 --- a/ttp/commands/_preflight.py +++ b/ttp/commands/_preflight.py @@ -85,30 +85,16 @@ def validate_ports(transport_port: int, dns_port: int, external_daemon: bool) -> raise typer.Exit(code=1) -def check_session_state() -> dict | None: - """Check for active or orphaned TTP sessions. Handles auto-recovery for orphans.""" - from ttp import dns, firewall - from ttp.commands._common import _PREFIX, console - - lock = state.read_lock() - if lock: - if lock.get("session_id"): - _print_error( - "Session Already Present", - "A recorded session must be terminated with 'sudo ttp stop' before starting another.", - ) - raise typer.Exit(code=1) - if state.is_orphan(): - console.print(f"{_PREFIX} [yellow]Orphaned session detected (PID {lock.get('pid')}). Auto-recovering...[/]") - state.attempt_recovery(firewall.destroy_rules, dns.restore_dns) - console.print(f"{_PREFIX} Recovery complete. Starting new session...") - else: - _print_error( - "Concurrency Error", - f"Another TTP process (PID {lock['pid']}) is currently running.", - ) - raise typer.Exit(code=1) - return lock +def check_session_state() -> None: + """Refuse to start over any recorded session, live or left behind by a crash.""" + if state.read_lock(): + # A crashed session still holds its table and DNS overlay: `ttp stop` + # removes them, whichever TTP version recorded it. + _print_error( + "Session Already Present", + "A recorded session must be terminated with 'sudo ttp stop' before starting another.", + ) + raise typer.Exit(code=1) def preflight_checks() -> None: diff --git a/ttp/commands/lifecycle.py b/ttp/commands/lifecycle.py index 5b67f24..fab04ea 100644 --- a/ttp/commands/lifecycle.py +++ b/ttp/commands/lifecycle.py @@ -177,10 +177,9 @@ def do_stop() -> None: raise typer.Exit(code=8) finally: # The lock must not outlive the nftables table. A lock whose session is - # already torn down blocks the next `ttp start` behind a concurrency - # error while the host routes in cleartext, and makes `ttp status` - # report a session that no longer exists. attempt_recovery() has used - # this same try/finally shape all along. + # already torn down blocks the next `ttp start` ("Session Already Present") + # while the host routes in cleartext, and makes `ttp status` + # report a session that no longer exists. state.delete_lock() console.print(f"{_PREFIX} [bold red]Session terminated. Traffic in cleartext.[/]") from ttp.commands._common import print_error diff --git a/ttp/state.py b/ttp/state.py index 49d299c..76b63ff 100644 --- a/ttp/state.py +++ b/ttp/state.py @@ -24,7 +24,6 @@ import shutil import tempfile import uuid -from collections.abc import Callable from datetime import UTC, datetime from pathlib import Path from typing import Any @@ -317,84 +316,3 @@ def stop_was_requested(session_id: str) -> bool: return False except (OSError, ValueError) as exc: raise StateError("Explicit-stop intent is unreadable") from exc - - -# argv tokens that identify a genuine ttp process. The installed console -# script is /usr/bin/ttp; `python -m ttp.cli` is the module form. -_TTP_ARGV_TOKENS = (b"ttp", b"ttp.cli") - - -def _is_pid_ttp(pid: int) -> bool: - """Check if the PID actually belongs to a TTP process (prevents PID recycling). - - /proc//cmdline is chosen by the owner of the target process, so it is - matched as NUL-separated argv tokens and never as a substring: the literal - "http" contains "ttp", so a substring test treated any curl, wget, browser - or httpd process as ours. That made a recycled PID look alive, which in - turn made is_orphan() report a dead session as running and suppressed the - recovery path. - """ - try: - with open(f"/proc/{pid}/cmdline", "rb") as f: - argv = [token for token in f.read().split(b"\x00") if token] - except (FileNotFoundError, OSError): - return False - - for index, token in enumerate(argv): - if token.rsplit(b"/", 1)[-1] in _TTP_ARGV_TOKENS: - return True - if token == b"-m" and index + 1 < len(argv) and argv[index + 1] in _TTP_ARGV_TOKENS: - return True - return False - - -def is_orphan() -> bool: - """Return ``True`` if the lock file exists but its PID is dead or recycled. - - Uses ``os.kill(pid, 0)`` which sends no signal but raises - ``OSError`` when the target process does not exist. - """ - data = read_lock() - if data is None: - return False - - pid = data.get("pid") - if pid is None: - return True # corrupt lock -> treat as orphan - - try: - os.kill(pid, 0) - if not _is_pid_ttp(pid): - return True # PID is alive but not TTP -> recycled (orphan) - except OSError: - return True # process not running -> orphan - return False - - -def attempt_recovery( - destroy_firewall: Callable[[], Any], - restore_dns: Callable[[Any], Any], -) -> bool: - """Attempt automatic recovery from an orphaned lock. - - Reads the lock, invokes the firewall and DNS restoration - callbacks, then deletes the lock. Returns ``True`` on success. - - Parameters - ---------- - destroy_firewall: - ``firewall.destroy_rules()`` - restore_dns: - ``dns.restore_dns(backup)`` - """ - data = read_lock() - if data is None: - return False - - try: - destroy_firewall() - restore_dns(data.get("dns_backup")) - finally: - delete_lock() - - return True From 00d9cba27202d899f08521fe8af01fd044039e0f Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:51:23 +0100 Subject: [PATCH 07/16] Record the removals in the changelog and sync the docs site Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- CHANGELOG.md | 7 +++++++ docs/web/release-notes/changelog.md | 32 +++++++++++++++++++++++++++++ tests/test_state.py | 10 ++++----- 3 files changed, 44 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b6c381..7af95d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `/usr/lib/transparent-tor-proxy/vendor` or depend on `six` for it, and the AUR package can drop `python-transitions`. `ttp start --watchdog` and `ttp watchdog start` no longer check for it before starting. +- `ttp start` no longer recovers an "orphaned" session by itself. Only a lock + written by 0.4.x reached that path: every 0.5 session was already refused + with "Session Already Present". A lock left by a crash, of any version, is + now refused the same way and ended with `sudo ttp stop`. The documentation + that promised auto-recovery after a `kill -9` is corrected. The lock also no + longer records `watchdog_active` and `watchdog_pid`, which nothing read: + `ttp watchdog status` asks systemd. ### Fixed diff --git a/docs/web/release-notes/changelog.md b/docs/web/release-notes/changelog.md index 90af21d..69dc482 100644 --- a/docs/web/release-notes/changelog.md +++ b/docs/web/release-notes/changelog.md @@ -19,9 +19,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `/usr/lib/transparent-tor-proxy/vendor` or depend on `six` for it, and the AUR package can drop `python-transitions`. `ttp start --watchdog` and `ttp watchdog start` no longer check for it before starting. +- `ttp start` no longer recovers an "orphaned" session by itself. Only a lock + written by 0.4.x reached that path: every 0.5 session was already refused + with "Session Already Present". A lock left by a crash, of any version, is + now refused the same way and ended with `sudo ttp stop`. The documentation + that promised auto-recovery after a `kill -9` is corrected. The lock also no + longer records `watchdog_active` and `watchdog_pid`, which nothing read: + `ttp watchdog status` asks systemd. ### Fixed +- `ttp stop` deleted the session lock even when it could not remove the + `inet ttp` table. The table stayed (no network, or an empty table and no + protection), while `ttp status` reported no session and a second `ttp stop` + answered "No active session found". The lock now stays, and `stop` exits + with `8` and points to `ttp stop --restore-only`. When the DNS overlay could + not be removed, `stop` printed "Session terminated" and exited `0`; it now + says so and exits `1`. A `conntrack -F` that timed out aborted the teardown + with a traceback before the rules were removed; it is now a warning, like a + failed flush. +- The watchdog compares the live `inet ttp` table with the fingerprint that + `ttp start` records (#80). If `nft` could not list the table at that moment, + for example after a 10-second timeout, `start` recorded no fingerprint and the + watchdog skipped the comparison for the whole session. A flushed table keeps + its chain names, so it then passed the remaining checks: no rules, everything + in cleartext, watchdog healthy. `ttp start` now rolls back when it cannot + read back its table, and the watchdog treats a missing fingerprint, or a + table it cannot read, as a firewall failure. This replaces the chain-name and + bypass-rule checks, which the fingerprint already covers. A bypass user + deleted during a session no longer cuts off the whole host's network. +- `--allow-root` exempted root only in the `filter_out` chain, not in the NAT + chain that redirects to Tor. Root's TCP and DNS were still sent through Tor, + while its UDP and ICMP left in cleartext: the flag gave neither the direct + path for system updates that the documentation promises, nor full Tor + routing. Root is now exempt in both chains, like a `--bypass-user`. Its DNS + to the local resolver still goes to Tor. - With no default route, as on an IPv6-only host, `ttp start` recorded the interface `eth0` in the session and printed "DNS set via overlay on interface eth0", even where no `eth0` exists. The interface is only a label: the DNS diff --git a/tests/test_state.py b/tests/test_state.py index c406237..83f265c 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -219,11 +219,11 @@ def test_write_lock_with_bridges(_use_tmp_lock): def test_update_lock_keys_preserves_untouched_fields(_use_tmp_lock): """A partial update must not silently drop the rest of the session state.""" state.write_lock(pid=4242, transport_port=9041, dns_port=9054, bypass_users=["alice"]) - state.update_lock_keys(watchdog_active=True, watchdog_pid=777) + state.update_lock_keys(phase="stopping", interface="wg0") data = state.read_lock() - assert data["watchdog_active"] is True - assert data["watchdog_pid"] == 777 + assert data["phase"] == "stopping" + assert data["interface"] == "wg0" # Everything the caller did not mention survives. assert data["pid"] == 4242 assert data["transport_port"] == 9041 @@ -239,7 +239,7 @@ def test_update_lock_keys_can_add_new_fields(_use_tmp_lock): def test_update_lock_keys_without_a_session_raises(_use_tmp_lock): """Updating a session that does not exist must fail loudly, not create one.""" with pytest.raises(state.StateError, match="No active TTP session"): - state.update_lock_keys(watchdog_active=True) + state.update_lock_keys(phase="stopping") assert state.read_lock() is None @@ -249,7 +249,7 @@ def test_update_lock_keys_reports_a_write_failure(_use_tmp_lock): patch.object(state, "_write_lock_file", side_effect=OSError("read-only fs")), pytest.raises(state.StateError, match="Failed to update session lock file"), ): - state.update_lock_keys(watchdog_active=True) + state.update_lock_keys(phase="stopping") # --------------------------------------------------------------------------- From ac416033a8fe5c5aee121415b1d50fd81c9d8127 Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:53:31 +0100 Subject: [PATCH 08/16] Call ttp.ux directly instead of through state's re-exports state.py re-exported the star-message helpers and PERSISTENT_DIR 'for backward compatibility'; only start, uninstall and one test used them. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- tests/test_cli_misc.py | 2 +- tests/test_state.py | 3 --- ttp/commands/admin.py | 4 ++-- ttp/commands/start.py | 6 +++--- ttp/state.py | 14 -------------- 5 files changed, 6 insertions(+), 23 deletions(-) diff --git a/tests/test_cli_misc.py b/tests/test_cli_misc.py index 326eb4d..276a05a 100644 --- a/tests/test_cli_misc.py +++ b/tests/test_cli_misc.py @@ -155,7 +155,7 @@ def test_status_as_a_normal_user_after_a_session_asks_for_sudo(monkeypatch): @patch("ttp.commands.admin.tor_install.remove_selinux_module") @patch("ttp.tor_detect.is_selinux_module_installed", return_value=True) @patch("ttp.state.read_lock", return_value={"pid": 1234}) -@patch("ttp.state.delete_star_sentinel") +@patch("ttp.ux.delete_star_sentinel") @patch("os.geteuid", return_value=0) def test_uninstall_calls_cleanup(mock_euid, mock_del_star, mock_read, mock_is_sel, mock_rem_sel, mock_stop): """uninstall -> stops session, removes SELinux.""" diff --git a/tests/test_state.py b/tests/test_state.py index 83f265c..231576d 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -22,14 +22,11 @@ def _use_tmp_lock(tmp_path: Path): """Redirect the lock file and runtime/persistent dirs to a temp directory.""" runtime_dir = tmp_path / "run" - persistent_dir = tmp_path / "lib" lock = runtime_dir / "ttp.lock" with ( patch.object(state, "LOCK_DIR", runtime_dir), patch.object(state, "LOCK_PATH", lock), - patch.object(state, "PERSISTENT_DIR", persistent_dir), - patch.object(state, "STAR_NOTIFIED_PATH", persistent_dir / ".starred_notified"), patch("ttp.state.os.chown"), patch("ttp.state.os.chmod"), patch("ttp.state.os.fchown"), diff --git a/ttp/commands/admin.py b/ttp/commands/admin.py index 8f88d09..cbbfefa 100644 --- a/ttp/commands/admin.py +++ b/ttp/commands/admin.py @@ -7,7 +7,7 @@ from rich.panel import Panel from rich.text import Text -from ttp import state, tor_install +from ttp import state, tor_install, ux from ttp.commands._common import ( _LOG_PATH, _PREFIX, @@ -105,7 +105,7 @@ def uninstall_command() -> None: # (Log file and runtime state are in tmpfs /run/ttp and evaporate on reboot/stop) # 3. Clean up the star notification sentinel. - state.delete_star_sentinel() + ux.delete_star_sentinel() console.print(f"{_PREFIX} [bold green]Uninstallation complete.[/]") console.print(f"{_PREFIX} Note: To remove application files, run the provided 'scripts/uninstall.sh'.") diff --git a/ttp/commands/start.py b/ttp/commands/start.py index 56ca322..2dc702e 100644 --- a/ttp/commands/start.py +++ b/ttp/commands/start.py @@ -6,7 +6,7 @@ import typer -from ttp import dns, firewall, state, tor_install +from ttp import dns, firewall, state, tor_install, ux from ttp.commands._common import ( _PREFIX, cli_state, @@ -526,6 +526,6 @@ def protect_vpn(tor_user: str) -> None: if not watchdog: console.print(f"{_PREFIX} Watchdog not selected: no continuous fault detection or asynchronous fault alerts.") console.print(f"{_PREFIX} Use 'ttp stop' to terminate. 'ttp refresh' to change IP.") - if state.should_show_star_message(): + if ux.should_show_star_message(): console.print("\n[dim]Thanks for using TTP! Starring the repo on GitHub helps the project grow.[/]") - state.mark_star_message_shown() + ux.mark_star_message_shown() diff --git a/ttp/state.py b/ttp/state.py index 76b63ff..6a4c380 100644 --- a/ttp/state.py +++ b/ttp/state.py @@ -39,20 +39,6 @@ # Minimum required free space on /run (tmpfs): 5 MB. MIN_TMPFS_BYTES = 5 * 1024 * 1024 -# Persistent directory - kept for backward compatibility (managed by ttp.ux). -PERSISTENT_DIR = Path("/var/lib/ttp") - -# --------------------------------------------------------------------------- -# Backward-compatible re-exports from ttp.ux -# --------------------------------------------------------------------------- - -from ttp.ux import ( # noqa: E402, F401 - STAR_NOTIFIED_PATH, - delete_star_sentinel, - mark_star_message_shown, - should_show_star_message, -) - def _watchdog_gid() -> int | None: """Return the ttp-watchdog GID, or ``None`` when the account is absent.""" From 8a5c45819897328621081eb1b493e7b0d744d8d7 Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:05:46 +0100 Subject: [PATCH 09/16] Give restart start's options instead of a copy of them restart redeclared all 17 of start's options and forwarded each by name; nothing kept the two lists equal. It now takes start's signature minus --require-vpn and forwards what it gets. `ttp restart --help` is unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- ttp/commands/stop_restart.py | 129 ++++------------------------------- 1 file changed, 13 insertions(+), 116 deletions(-) diff --git a/ttp/commands/stop_restart.py b/ttp/commands/stop_restart.py index ca30d2a..fd18f15 100644 --- a/ttp/commands/stop_restart.py +++ b/ttp/commands/stop_restart.py @@ -1,8 +1,8 @@ from __future__ import annotations +import inspect import time -from pathlib import Path -from typing import Optional +from typing import Any import typer @@ -58,95 +58,7 @@ def stop_command( _do_stop() -def restart_command( - interface: Optional[str] = typer.Option( - None, - "--interface", - "-i", - help="Interface to record in the session, for diagnostics only (default: the default route's). TTP applies to every interface.", - ), - bootstrap_timeout: int = typer.Option( - 180, - "--bootstrap-timeout", - help="Timeout in seconds to wait for Tor to bootstrap.", - ), - transport_port: int = typer.Option( - 9041, - "--transport-port", - "-t", - help="Port for Tor's TransPort redirect.", - ), - dns_port: int = typer.Option( - 9054, - "--dns-port", - "-d", - help="Port for Tor's DNSPort redirect.", - ), - allow_root: bool = typer.Option( - False, - "--allow-root", - help="Allow root processes to bypass Tor routing (not recommended, increases leak risk).", - ), - no_lan_bypass: bool = typer.Option( - False, - "--no-lan-bypass", - help="Do not bypass Tor routing for local subnets (RFC 1918 & Link-Local).", - ), - watchdog: Optional[bool] = typer.Option( - None, - "--watchdog/--no-watchdog", - "-w", - help="Start the background watchdog daemon to monitor session integrity.", - ), - bypass_user: Optional[list[str]] = typer.Option( - None, - "--bypass-user", - help="System user(s) to bypass Tor routing.", - ), - bypass_group: Optional[list[str]] = typer.Option( - None, - "--bypass-group", - help="System group(s) to bypass Tor routing.", - ), - use_bridges: bool = typer.Option( - False, - "--use-bridges", - help="Globally enable Tor bridges support.", - ), - bridge_file: Optional[Path] = typer.Option( - None, - "--bridge-file", - help="Path to a file containing Tor bridge lines.", - ), - bridge: Optional[list[str]] = typer.Option( - None, - "--bridge", - help="Individual Tor bridge line. Can be specified multiple times.", - ), - external_daemon: bool = typer.Option( - False, - "--external-daemon", - help="Run TTP in BYOD mode, delegating Tor lifecycle management to the host.", - ), - tor_uid: Optional[str] = typer.Option( - None, - "--tor-uid", - help="Specify the numeric UID or username of the Tor process manually in BYOD mode.", - ), - no_ipv6: bool = typer.Option( - False, - "--no-ipv6", - help="Force disable all IPv6 traffic (drops outgoing IPv6 to prevent leaks).", - ), - notifications: Optional[bool] = typer.Option( - None, - "--notifications/--no-notifications", - help="Enable optional desktop notifications for the initiating user.", - ), - notification_user: Optional[str] = typer.Option( - None, "--notification-user", help="Explicit non-root desktop recipient (required for direct root invocation)." - ), -) -> None: +def restart_command(**options: Any) -> None: """Restart the transparent Tor proxy session.""" _require_root() @@ -160,7 +72,7 @@ def restart_command( from ttp.settings import SettingsError, load_settings try: - load_settings().select(watchdog=watchdog, notifications=notifications) + load_settings().select(watchdog=options["watchdog"], notifications=options["notifications"]) lock = state.read_lock(strict=True) if lock and lock.get("vpn"): print_error( @@ -182,27 +94,12 @@ def restart_command( else: console.print(f"{_PREFIX} No active session found, starting a new one...") - # Every parameter is forwarded explicitly: omitting one would leave - # start_command with its ``typer.Option(...)`` default, which is an - # OptionInfo sentinel (truthy, not a real value) when the function is - # called directly instead of through the CLI parser. - start_command( - interface=interface, - bootstrap_timeout=bootstrap_timeout, - transport_port=transport_port, - dns_port=dns_port, - allow_root=allow_root, - no_lan_bypass=no_lan_bypass, - watchdog=watchdog, - bypass_user=bypass_user, - bypass_group=bypass_group, - use_bridges=use_bridges, - bridge_file=bridge_file, - bridge=bridge, - external_daemon=external_daemon, - tor_uid=tor_uid, - no_ipv6=no_ipv6, - notifications=notifications, - notification_user=notification_user, - require_vpn=None, - ) + start_command(**options, require_vpn=None) + + +# Restart takes start's options, except --require-vpn: VPN sessions must stop +# and start explicitly. Copying the signature keeps the two lists from drifting. +_start = inspect.signature(start_command, eval_str=True) +restart_command.__signature__ = _start.replace( # type: ignore[attr-defined] + parameters=[p for p in _start.parameters.values() if p.name != "require_vpn"] +) From 13f805bc298e7eaa6cd844f4b62ddcc7f940c97d Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:06:40 +0100 Subject: [PATCH 10/16] Remove tor_control.verify_tor, which nothing called start verifies through ttp.probe.verify_session; verify_tor had only its own tests. get_exit_ip now reads netprobe.ENDPOINTS, so the endpoint list exists once instead of twice plus a test keeping the copies equal. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- tests/leak/test_ip_leak.py | 4 +- tests/test_leak_retry.py | 2 +- tests/test_netprobe.py | 6 +- tests/test_tor_control.py | 149 ------------------------------------- ttp/netprobe.py | 5 +- ttp/tor_control.py | 62 +-------------- 6 files changed, 9 insertions(+), 219 deletions(-) diff --git a/tests/leak/test_ip_leak.py b/tests/leak/test_ip_leak.py index 10beac7..f9d322c 100644 --- a/tests/leak/test_ip_leak.py +++ b/tests/leak/test_ip_leak.py @@ -17,7 +17,7 @@ import pytest -# The production verifier, `ttp.tor_control.verify_tor`, makes five attempts +# The production verifier, `ttp.probe.verify_session`, makes five attempts # across several endpoints with a three-second backoff. These tests used to make # a single request to a single endpoint, which left them strictly less resilient # than the code they exist to verify: one TLS handshake dropped by an exit node @@ -26,7 +26,7 @@ # on `check.torproject.org`, on a commit whose identical tree had passed the same # job eleven minutes earlier. # -# The retry budget below deliberately mirrors verify_tor's. The endpoint list does +# The retry budget below deliberately mirrors verify_session's. The endpoint list does # not: a leak test must not ask the code under test whether the code under test # works. _ATTEMPTS = 5 diff --git a/tests/test_leak_retry.py b/tests/test_leak_retry.py index 10435c9..05e47e9 100644 --- a/tests/test_leak_retry.py +++ b/tests/test_leak_retry.py @@ -90,7 +90,7 @@ def test_the_retry_budget_is_not_silently_disarmed(): The two tests above would still pass with a budget of one if their fixtures were adjusted to match, so the budget itself is asserted here: it exists to - mirror `ttp.tor_control.verify_tor`, which makes five attempts. + mirror `ttp.probe.verify_session`, which makes five attempts. """ assert leak_ip._ATTEMPTS >= 5 assert leak_ip._BACKOFF_SECONDS >= 1 diff --git a/tests/test_netprobe.py b/tests/test_netprobe.py index c4a4867..0dbf99e 100644 --- a/tests/test_netprobe.py +++ b/tests/test_netprobe.py @@ -22,7 +22,7 @@ from ttp import netprobe, tor_control -URL = tor_control.VERIFY_ENDPOINTS[0] +URL = netprobe.ENDPOINTS[0] # The child: what it may hand back ------------------------------------------- @@ -133,10 +133,6 @@ def test_without_root_the_fetch_stays_in_process(): run.assert_not_called() -def test_the_child_and_the_parent_agree_on_the_endpoints(): - assert tuple(tor_control.VERIFY_ENDPOINTS) == netprobe.ENDPOINTS - - def test_the_child_reads_a_bounded_body_and_parses_it(): response = MagicMock() response.__enter__.return_value = response diff --git a/tests/test_tor_control.py b/tests/test_tor_control.py index 8a70cdc..0838439 100644 --- a/tests/test_tor_control.py +++ b/tests/test_tor_control.py @@ -139,56 +139,6 @@ def test_wait_for_bootstrap_timeout(mock_get_ctrl, mock_sleep): tor_control.wait_for_bootstrap() -# verify_tor - - -@patch("ttp.tor_control.time.sleep") -@patch("ttp.tor_control.urllib.request.urlopen") -def test_verify_tor_success(mock_urlopen, mock_sleep): - """verify_tor returns (True, IP) when the primary endpoint responds.""" - mock_resp = MagicMock() - mock_resp.read.return_value = b'{"IsTor": true, "IP": "8.8.8.8"}' - mock_urlopen.return_value.__enter__.return_value = mock_resp - - is_tor, ip = tor_control.verify_tor() - assert is_tor is True - assert ip == "8.8.8.8" - - -@patch("ttp.tor_control.time.sleep") -@patch("ttp.tor_control.urllib.request.urlopen") -def test_verify_tor_retries(mock_urlopen, mock_sleep): - """verify_tor retries all endpoints across all attempts before giving up.""" - mock_urlopen.side_effect = urllib.error.URLError("Timeout") - - is_tor, ip = tor_control.verify_tor() - - assert is_tor is False - assert ip == "unknown" - # 5 attempts x 3 endpoints = 15 calls - assert mock_urlopen.call_count == 15 - - -@patch("ttp.tor_control.time.sleep") -@patch("ttp.tor_control.urllib.request.urlopen") -def test_verify_tor_fallback_endpoint(mock_urlopen, mock_sleep): - """With the primary down for every attempt, the fallback's IP is reported, is_tor=False.""" - mock_resp = MagicMock() - mock_resp.read.return_value = b'{"ip": "9.9.9.9"}' - - def _urlopen(req, timeout): - host = urllib.parse.urlparse(req.full_url).hostname - if host == "check.torproject.org": - raise urllib.error.URLError("Primary down") - return MagicMock(__enter__=MagicMock(return_value=mock_resp)) - - mock_urlopen.side_effect = _urlopen - - is_tor, ip = tor_control.verify_tor() - assert is_tor is False - assert ip == "9.9.9.9" - - # request_new_circuit @@ -272,92 +222,6 @@ def test_graceful_shutdown_signal_exception(mock_get_ctrl, mock_sleep): # --------------------------------------------------------------------------- -@pytest.mark.parametrize("index", [1, 2], ids=["ipify", "ifconfig-me"]) -def test_a_fallback_reflector_cannot_assert_is_tor(index: int) -> None: - """A fallback that answers with an IsTor field must not raise the verdict. - - The fallbacks are ordinary IP echo services with no Tor knowledge. Making - check.torproject.org unreachable is free for anyone on the path -- it is - also routinely rate-limited for Tor clients -- so field presence alone - must never decide this. - """ - responses = [None] * len(tor_control.VERIFY_ENDPOINTS) - responses[index] = {"IsTor": True, "IP": "203.0.113.66"} - - def _fetch(endpoint: str): - return responses[tor_control.VERIFY_ENDPOINTS.index(endpoint)] - - with ( - patch.object(tor_control, "_fetch_endpoint", side_effect=_fetch), - patch("time.sleep"), - ): - is_tor, ip = tor_control.verify_tor() - - assert is_tor is False - assert ip != "203.0.113.66" - - -def test_the_authoritative_endpoint_is_still_believed() -> None: - with ( - patch.object(tor_control, "_fetch_endpoint", return_value={"IsTor": True, "IP": "185.220.101.7"}), - patch("time.sleep"), - ): - assert tor_control.verify_tor() == (True, "185.220.101.7") - - -def test_a_censored_network_is_unchanged() -> None: - """With the authoritative endpoint down, an honest fallback still reports.""" - responses = [None, {"ip": "198.51.100.9"}, None] - - def _fetch(endpoint: str): - return responses[tor_control.VERIFY_ENDPOINTS.index(endpoint)] - - with ( - patch.object(tor_control, "_fetch_endpoint", side_effect=_fetch), - patch("time.sleep"), - ): - assert tor_control.verify_tor() == (False, "198.51.100.9") - - -def test_one_slow_answer_from_the_authority_does_not_decide_the_verdict() -> None: - """A fallback that answers first must not end the attempts. - - check.torproject.org is routinely slow or rate-limited for Tor clients, and - the first request over a freshly built circuit is the slowest of all. If it - misses once, the reflector's answer was returned at once as "not Tor" and - the four remaining attempts never asked the authority again - so `ttp start` - reported "Traffic is NOT reaching Tor" through a running Tor exit. - """ - authority = iter([None, {"IsTor": True, "IP": "185.220.101.7"}]) - - def _fetch(endpoint: str): - if endpoint == tor_control.VERIFY_ENDPOINTS[0]: - return next(authority) - return {"ip": "185.220.101.7"} - - with ( - patch.object(tor_control, "_fetch_endpoint", side_effect=_fetch), - patch("time.sleep"), - ): - assert tor_control.verify_tor() == (True, "185.220.101.7") - - -def test_a_later_valid_fallback_answer_replaces_an_earlier_malformed_one() -> None: - """With the authority down throughout, report the address we did get, not "malformed".""" - fallback = iter([{"ip": "not-an-ip"}] + [{"ip": "198.51.100.9"}] * 4) - - def _fetch(endpoint: str): - if endpoint == tor_control.VERIFY_ENDPOINTS[0]: - return None - return next(fallback) - - with ( - patch.object(tor_control, "_fetch_endpoint", side_effect=_fetch), - patch("time.sleep"), - ): - assert tor_control.verify_tor() == (False, "198.51.100.9") - - @pytest.mark.parametrize( "hostile", [ @@ -446,16 +310,3 @@ def test_request_new_circuit_wraps_a_controller_error() -> None: ): with pytest.raises(TorError, match="Failed to request new circuit"): tor_control.request_new_circuit() - - -def test_the_authoritative_endpoint_answering_without_istor_is_not_an_upgrade() -> None: - """A trusted origin with an unexpected shape must not fall through. - - Letting the loop continue would hand the verdict to a fallback reflector, - which is exactly what the origin binding exists to prevent. - """ - with ( - patch.object(tor_control, "_fetch_endpoint", return_value={"IP": "185.220.101.7"}), - patch("time.sleep"), - ): - assert tor_control.verify_tor() == (False, "185.220.101.7") diff --git a/ttp/netprobe.py b/ttp/netprobe.py index e9a607d..6b182aa 100644 --- a/ttp/netprobe.py +++ b/ttp/netprobe.py @@ -25,8 +25,9 @@ import urllib.error import urllib.request -#: The only URLs this probe fetches. Mirrors ttp.tor_control.VERIFY_ENDPOINTS; -#: tests/test_netprobe.py keeps them equal. +#: The only URLs this probe fetches, by priority: the Tor Project's API is +#: authoritative (it returns IsTor); the others are IP reflectors that can +#: report an address, never assert Tor routing. ENDPOINTS = ( "https://check.torproject.org/api/ip", "https://api.ipify.org?format=json", diff --git a/ttp/tor_control.py b/ttp/tor_control.py index 79461e6..0156d72 100644 --- a/ttp/tor_control.py +++ b/ttp/tor_control.py @@ -32,21 +32,13 @@ from typing import Optional from ttp.exceptions import TorError +from ttp.netprobe import ENDPOINTS logger = logging.getLogger("ttp") -# Verification endpoints ordered by priority. -# The Tor Project's API is authoritative (returns IsTor), the others are -# generic IP reflectors used as fallbacks when the primary is unreachable. NO_ANSWER = "unknown" # no endpoint replied at all MALFORMED_ANSWER = "malformed" # an endpoint replied, but not with an IP address -VERIFY_ENDPOINTS = [ - "https://check.torproject.org/api/ip", - "https://api.ipify.org?format=json", - "https://ifconfig.me/all.json", -] - try: from stem import Signal from stem.control import Controller @@ -177,7 +169,7 @@ def get_exit_ip() -> str: ``requests`` as a dependency. """ saw_reply = False - for endpoint in VERIFY_ENDPOINTS: + for endpoint in ENDPOINTS: data = _fetch_endpoint(endpoint) if data is not None: saw_reply = True @@ -267,56 +259,6 @@ def wait_for_bootstrap(progress_callback: Optional[Callable[[int], None]] = None raise TorError(f"Tor control socket communication failed during bootstrap: {e}") from e -def verify_tor() -> tuple[bool, str]: - """Verify that traffic is actually routed through Tor. - - Tries multiple endpoints for resilience. The Tor Project's API is - authoritative (it returns ``IsTor``); the fallback endpoints only - confirm we can reach the internet through *some* exit node. - - Returns - ------- - tuple[bool, str] - ``(is_tor, exit_ip)`` - whether we confirmed Tor routing, - and the exit IP address. - """ - # What a fallback reported, kept rather than returned: a fallback cannot - # decide the verdict, so answering first must not end the attempts either. - # Returning it at once meant one slow answer from check.torproject.org - - # routine for Tor clients, and likeliest on a freshly built circuit - was - # final, and the remaining attempts never asked the authority again. - fallback_ip: str | None = None - for _attempt in range(1, 6): # 5 attempts - for endpoint in VERIFY_ENDPOINTS: - data = _fetch_endpoint(endpoint) - if data is None: - continue - - # Only the Tor Project API is authoritative for IsTor, and only - # because of which URL answered -- not because a field of that - # name is present. The fallbacks are ordinary IP echo services: - # whatever keys they put in their body, they may report an - # address, never assert Tor routing. - if endpoint == VERIFY_ENDPOINTS[0]: - if "IsTor" in data: - return bool(data.get("IsTor", False)), _canonical_ip(data.get("IP")) or MALFORMED_ANSWER - # Trusted origin, unexpected shape: do not upgrade the verdict, - # and do not let a fallback speak for it either. - return False, _canonical_ip(data.get("IP")) or MALFORMED_ANSWER - - # Fallback endpoints: we got a response, so traffic is routed - # through *something*. We can't confirm it's Tor, but we have an IP. - ip = _canonical_ip(data.get("ip") or data.get("ip_addr")) - fallback_ip = ip if ip is not None else fallback_ip or MALFORMED_ANSWER - break # one reflector per attempt is enough; ask the authority again next time - time.sleep(3) - - if fallback_ip is not None: - logger.warning("check.torproject.org did not answer in 5 attempts; exit IP from a fallback only.") - return False, fallback_ip - return False, NO_ANSWER - - def request_new_circuit() -> tuple[bool, str]: """Request a new Tor circuit (new exit IP) and wait for it to change. From 7114520af54f27e07935d8ef44f581d51afa904f Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:07:33 +0100 Subject: [PATCH 11/16] Delete _unit_state, DeliveryState and EXIT_UNVERIFIED _unit_state was called only by its tests, DeliveryState by nothing, and EXIT_UNVERIFIED duplicated ExitCode.UNVERIFIED for two test modules. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- tests/test_cli_start.py | 11 +++++------ tests/test_cli_stop.py | 6 +++--- tests/test_watchdog.py | 15 +-------------- ttp/commands/_common.py | 8 -------- ttp/evidence.py | 8 -------- ttp/watchdog/service.py | 21 --------------------- 6 files changed, 9 insertions(+), 60 deletions(-) diff --git a/tests/test_cli_start.py b/tests/test_cli_start.py index 7b79417..5860afe 100644 --- a/tests/test_cli_start.py +++ b/tests/test_cli_start.py @@ -24,8 +24,7 @@ from ttp import state from ttp.cli import app -from ttp.commands._common import EXIT_UNVERIFIED -from ttp.evidence import Verification, VerificationState +from ttp.evidence import ExitCode, Verification, VerificationState from ttp.exceptions import DNSError, FirewallError, StateError, TorError from ttp.runtime_records import RecordStore @@ -294,7 +293,7 @@ def test_start_tor_verification_fails( `ttp restart && ...` walk onto a blocked network believing it had succeeded. """ result = runner.invoke(app, ["start"]) - assert result.exit_code == EXIT_UNVERIFIED + assert result.exit_code == ExitCode.UNVERIFIED assert "Tor Verification Inconclusive" in result.output assert "does not prove" in result.output assert "held fail-closed" not in result.output @@ -329,7 +328,7 @@ def test_start_unverified_still_starts_the_watchdog( as verification failed would have silently dropped `--watchdog`. """ result = runner.invoke(app, ["start", "--watchdog"]) - assert result.exit_code == EXIT_UNVERIFIED + assert result.exit_code == ExitCode.UNVERIFIED assert mock_watchdog.call_count == 1 @@ -353,7 +352,7 @@ def test_start_tor_unit_failure_leaves_the_host_in_cleartext( """ result = runner.invoke(app, ["start"]) assert result.exit_code == 1 - assert result.exit_code != EXIT_UNVERIFIED + assert result.exit_code != ExitCode.UNVERIFIED assert mock_nft_str.call_count == 0 assert mock_write.call_count == 0 @@ -415,7 +414,7 @@ def test_start_rolls_back_a_firewall_failure( result = runner.invoke(app, ["start"]) assert result.exit_code == 1 - assert result.exit_code != EXIT_UNVERIFIED + assert result.exit_code != ExitCode.UNVERIFIED assert "Firewall Setup Failed" in result.output assert mock_stop_tor.call_count == 1 diff --git a/tests/test_cli_stop.py b/tests/test_cli_stop.py index ce784d0..abec76a 100644 --- a/tests/test_cli_stop.py +++ b/tests/test_cli_stop.py @@ -17,7 +17,7 @@ from ttp.cli import app from ttp.commands import lifecycle -from ttp.commands._common import EXIT_UNVERIFIED +from ttp.evidence import ExitCode runner = CliRunner() @@ -257,7 +257,7 @@ def test_restart_active_session(mock_read, mock_stop, mock_sleep, mock_start): assert kwargs["no_ipv6"] is False -@patch("ttp.commands.stop_restart.start_command", side_effect=typer.Exit(code=EXIT_UNVERIFIED)) +@patch("ttp.commands.stop_restart.start_command", side_effect=typer.Exit(code=ExitCode.UNVERIFIED)) @patch("time.sleep") @patch("ttp.commands.stop_restart._do_stop") @patch("ttp.state.read_lock", return_value={"pid": 1234}) @@ -272,7 +272,7 @@ def test_restart_propagates_the_unverified_exit_code(mock_read, mock_stop, mock_ code has to survive the wrapper rather than collapsing into 0 or 1. """ result = runner.invoke(app, ["restart"]) - assert result.exit_code == EXIT_UNVERIFIED + assert result.exit_code == ExitCode.UNVERIFIED assert mock_stop.call_count == 1 diff --git a/tests/test_watchdog.py b/tests/test_watchdog.py index 77601d9..a8c9132 100644 --- a/tests/test_watchdog.py +++ b/tests/test_watchdog.py @@ -693,23 +693,10 @@ def test_stopping_tor_does_not_stop_the_watchdog_that_should_restart_it(has_user # --------------------------------------------------------------------------- -# _unit_state / watchdog_liveness: the probe must fail safe. +# watchdog_liveness: the probe must fail safe. # --------------------------------------------------------------------------- -def test_unit_state_reports_unknown_when_systemctl_cannot_be_run() -> None: - """A probe that cannot run must not look like a healthy unit.""" - with patch("ttp.watchdog.service.subprocess.run", side_effect=OSError("no systemctl")): - assert service._unit_state() == ("unknown", None) - - -def test_unit_state_treats_mainpid_zero_as_no_pid() -> None: - """systemd reports MainPID=0 for a unit with no running process.""" - with patch("ttp.watchdog.service.subprocess.run") as run: - run.return_value = MagicMock(stdout="ActiveState=failed\nMainPID=0\n", returncode=0) - assert service._unit_state() == ("failed", None) - - def test_watchdog_liveness_never_upgrades_a_recorded_value_when_it_cannot_probe() -> None: """An unprobeable unit is reported inactive, not "whatever the lock said".""" with ( diff --git a/ttp/commands/_common.py b/ttp/commands/_common.py index 8c897a1..f5b8475 100644 --- a/ttp/commands/_common.py +++ b/ttp/commands/_common.py @@ -31,14 +31,6 @@ _LOG_PATH = Path("/run/ttp/ttp.log") logger = logging.getLogger("ttp") -# Exit code for "the session was established, but Tor could not be verified". -# -# Failed verification alone does not prove that Tor carries no traffic or that -# isolation was verified. Code 1 is a generic failure (including preflight), -# while Click reserves 2 for usage errors. The broader degraded-state contract -# remains pending; see docs/interfaces.md and the 0.5.0 roadmap. -EXIT_UNVERIFIED = 3 - # Refused before network changes: an explicit per-link DNSSEC requirement. EXIT_DNSSEC_CONFLICT = 4 diff --git a/ttp/evidence.py b/ttp/evidence.py index 7df5e8a..55d9509 100644 --- a/ttp/evidence.py +++ b/ttp/evidence.py @@ -54,14 +54,6 @@ class VerificationState(str, Enum): INCONCLUSIVE = "inconclusive" -class DeliveryState(str, Enum): - DISABLED = "disabled" - PENDING = "pending" - ACCEPTED = "accepted" - UNCONFIRMED = "unconfirmed" - FAILED = "failed" - - @dataclass(frozen=True) class Diagnostic: code: ExitCode diff --git a/ttp/watchdog/service.py b/ttp/watchdog/service.py index 07a8468..c3328e3 100644 --- a/ttp/watchdog/service.py +++ b/ttp/watchdog/service.py @@ -126,27 +126,6 @@ def _write_watchdog_service_unit(settings: Settings | None = None, session_id: s logger.debug("Wrote volatile watchdog service unit to %s", WATCHDOG_SERVICE_PATH) -def _unit_state() -> tuple[str, int | None]: - """Return ``(ActiveState, MainPID)`` for the watchdog unit. - - ``("unknown", None)`` when the unit cannot be probed at all. - """ - try: - res = subprocess.run( - [resolve("systemctl"), "show", WATCHDOG_SERVICE_NAME, "-p", "ActiveState", "-p", "MainPID"], - capture_output=True, - text=True, - check=True, - timeout=10, - ) - except Exception: - return "unknown", None - fields = dict(line.split("=", 1) for line in res.stdout.strip().splitlines() if "=" in line) - raw_pid = fields.get("MainPID", "0").strip() - pid = int(raw_pid) if raw_pid.isdigit() and int(raw_pid) > 0 else None - return fields.get("ActiveState", "unknown").strip(), pid - - def watchdog_observation() -> dict[str, Any]: """Fresh useful progress from the current systemd invocation, or unknown. From b41facfb17b90f86d6c10b8f577900b0b0e08723 Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:08:26 +0100 Subject: [PATCH 12/16] Drop re-exports and aliases that nothing uses ttp.cli kept eleven `_name = name` aliases no test or script refers to; only _setup_logging is patched. ttp.watchdog re-exposed stdlib and ttp modules "for test mocks" that no test patches through it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- ttp/cli.py | 23 +---------------------- ttp/watchdog/__init__.py | 37 ++----------------------------------- 2 files changed, 3 insertions(+), 57 deletions(-) diff --git a/ttp/cli.py b/ttp/cli.py index 553d598..a7b1902 100644 --- a/ttp/cli.py +++ b/ttp/cli.py @@ -24,16 +24,7 @@ from ttp.commands._common import ( cli_state, console, - get_uid_from_port, - is_port_in_use, - is_port_listening_tcp, - is_port_listening_udp, - parse_txt_dig_ipv4, - print_error, - require_root, setup_logging, - validate_bridge_line, - verify_tor, ) from ttp.commands.admin import ( bypass_command, @@ -42,7 +33,6 @@ uninstall_command, ) from ttp.commands.config import config_command -from ttp.commands.lifecycle import do_stop, signal_handler from ttp.commands.monitor import monitor_command from ttp.commands.session import ( check_command, @@ -54,19 +44,8 @@ from ttp.commands.stop_restart import restart_command, stop_command from ttp.commands.watchdog import watchdog_app -# Backward-compatible aliases for tests and external callers +# Tests patch this name to keep logging off the real log path. _setup_logging = setup_logging -_print_error = print_error -_require_root = require_root -_validate_bridge_line = validate_bridge_line -_get_uid_from_port = get_uid_from_port -_is_port_in_use = is_port_in_use -_is_port_listening_tcp = is_port_listening_tcp -_is_port_listening_udp = is_port_listening_udp -_verify_tor = verify_tor -_do_stop = do_stop -_signal_handler = signal_handler -_parse_txt_dig_ipv4 = parse_txt_dig_ipv4 app = typer.Typer( name="ttp", diff --git a/ttp/watchdog/__init__.py b/ttp/watchdog/__init__.py index 484468c..ffa5baa 100644 --- a/ttp/watchdog/__init__.py +++ b/ttp/watchdog/__init__.py @@ -3,39 +3,8 @@ """Watchdog & Killswitch Module - Proactive Session Integrity & Auto-Healing.""" -# Re-expose standard modules and libraries for test mock compatibility -import select as select -import shutil as shutil -import subprocess as subprocess -import time as time -from pathlib import Path as Path - -from ttp import ( - dns as dns, -) -from ttp import ( - firewall as firewall, -) -from ttp import ( - state as state, -) -from ttp import ( - tor_control as tor_control, -) -from ttp.watchdog import ( - alerts as alerts, -) -from ttp.watchdog import ( - inotify as inotify, -) -from ttp.watchdog import ( - integrity as integrity, -) - -# Expose internal submodules so they are accessible as attributes on ttp.watchdog -from ttp.watchdog import ( - service as service, -) +# The submodules (alerts, integrity, service, ...) are reachable as attributes +# once imported below; tests patch them by their own path. from ttp.watchdog.alerts import ( _sanitize_alert_text, trigger_emergency_killswitch, @@ -44,8 +13,6 @@ attempt_auto_healing, check_system_integrity, ) - -# Re-export the public API from ttp.watchdog.service import ( WATCHDOG_SERVICE_NAME, WATCHDOG_SERVICE_PATH, From 747fb8a6431c0b1105684b6a2c4bd468e53f4bae Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:13:26 +0100 Subject: [PATCH 13/16] Always map the DoH resolvers away instead of passing block_doh block_doh went through four functions and their docstrings, but nothing in TTP ever set it to False; only tests did. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- tests/test_edge_paths.py | 1 - tests/test_tor_install.py | 21 +++------------------ tests/test_unit_hardening.py | 1 - ttp/tor_config.py | 27 +++++++++++---------------- ttp/tor_install.py | 3 --- ttp/tor_service.py | 3 --- 6 files changed, 14 insertions(+), 42 deletions(-) diff --git a/tests/test_edge_paths.py b/tests/test_edge_paths.py index bdee3db..1e0188d 100644 --- a/tests/test_edge_paths.py +++ b/tests/test_edge_paths.py @@ -190,7 +190,6 @@ def test_a_missing_transport_binary_is_named_by_its_standard_path(): tor_user="toranon", transport_port=9041, dns_port=9054, - block_doh=False, use_bridges=True, bridges=["obfs4 192.0.2.1:443 AAAA cert=x iat-mode=0"], ipv6_avail=False, diff --git a/tests/test_tor_install.py b/tests/test_tor_install.py index 5c7cbc9..e125894 100644 --- a/tests/test_tor_install.py +++ b/tests/test_tor_install.py @@ -125,7 +125,6 @@ def test_start_tor_service(mock_generate, mock_write_unit, mock_label, mock_run) "tor", transport_port=9041, dns_port=9054, - block_doh=True, use_bridges=False, bridges=None, disable_ipv6=False, @@ -151,7 +150,7 @@ def test_start_tor_service(mock_generate, mock_write_unit, mock_label, mock_run) @patch("ttp.tor_config.shutil.chown") @patch("ttp.tor_config.os.chmod") def test_generate_torrc_doh_mitigation(mock_chmod, mock_chown, mock_makedirs, tmp_path: Path): - """generate_torrc writes MapAddress use-application-dns.net 0.0.0.0 if block_doh is True.""" + """generate_torrc maps the DoH canary and resolvers to 0.0.0.0.""" runtime_dir = tmp_path / "run/tor" cache_dir = tmp_path / "lib/cache" torrc_path = runtime_dir / "torrc" @@ -160,19 +159,13 @@ def test_generate_torrc_doh_mitigation(mock_chmod, mock_chown, mock_makedirs, tm patch.object(tor_config, "TOR_RUNTIME_DIR", runtime_dir), patch.object(tor_config, "TOR_CACHE_DIR", cache_dir), ): - # Genera con block_doh=True (default) - generate_torrc("debian-tor", block_doh=True) + generate_torrc("debian-tor") assert torrc_path.exists() content = torrc_path.read_text() assert "MapAddress use-application-dns.net 0.0.0.0" in content assert "MapAddress cloudflare-dns.com 0.0.0.0" in content assert "MapAddress dns.google 0.0.0.0" in content - # Genera con block_doh=False - generate_torrc("debian-tor", block_doh=False) - content_no_doh = torrc_path.read_text() - assert "MapAddress use-application-dns.net 0.0.0.0" not in content_no_doh - @patch("ttp.tor_config.os.makedirs") @patch("ttp.tor_config.shutil.chown") @@ -560,7 +553,6 @@ def test_build_torrc_content_ipv4_only(): tor_user="debian-tor", transport_port=9041, dns_port=9054, - block_doh=False, use_bridges=False, bridges=None, ipv6_avail=False, @@ -571,7 +563,6 @@ def test_build_torrc_content_ipv4_only(): assert "DNSPort 9054" in content assert "ClientUseIPv6 0" in content assert "[::1]" not in content - assert "MapAddress" not in content assert "UseBridges" not in content @@ -580,7 +571,6 @@ def test_build_torrc_content_ipv6_enabled(): tor_user="debian-tor", transport_port=9041, dns_port=9054, - block_doh=False, use_bridges=False, bridges=None, ipv6_avail=True, @@ -595,7 +585,6 @@ def test_build_torrc_content_block_doh(): tor_user="debian-tor", transport_port=9041, dns_port=9054, - block_doh=True, use_bridges=False, bridges=None, ipv6_avail=False, @@ -611,7 +600,6 @@ def test_build_torrc_content_with_bridges(mock_resolve): tor_user="debian-tor", transport_port=9041, dns_port=9054, - block_doh=False, use_bridges=True, bridges=[ "obfs4 192.0.2.1:1234 FINGERPRINT", @@ -631,7 +619,6 @@ def test_build_torrc_content_root_user_excludes_user_directive(): tor_user="root", transport_port=9041, dns_port=9054, - block_doh=False, use_bridges=False, bridges=None, ipv6_avail=False, @@ -898,8 +885,7 @@ def test_ensure_tor_ready_forwards_every_tor_option() -> None: patch("ttp.tor_install.detect_tor", return_value={"is_installed": True}), patch("ttp.tor_install.start_tor_service") as start, ): - ensure_tor_ready(block_doh=False, disable_ipv6=True, use_bridges=False) - assert start.call_args.kwargs["block_doh"] is False + ensure_tor_ready(disable_ipv6=True, use_bridges=False) assert start.call_args.kwargs["disable_ipv6"] is True @@ -992,7 +978,6 @@ def test_build_torrc_refuses_a_bridge_value_that_spans_lines() -> None: tor_user="debian-tor", transport_port=9041, dns_port=9054, - block_doh=False, use_bridges=True, bridges=["obfs4 192.0.2.10:9001 cert=AAAA\nControlPort 9051"], ipv6_avail=False, diff --git a/tests/test_unit_hardening.py b/tests/test_unit_hardening.py index cdf8b03..676d649 100644 --- a/tests/test_unit_hardening.py +++ b/tests/test_unit_hardening.py @@ -94,7 +94,6 @@ def test_the_torrc_no_longer_asks_tor_to_switch_user(): tor_user="debian-tor", transport_port=9041, dns_port=9054, - block_doh=False, use_bridges=False, bridges=None, ipv6_avail=False, diff --git a/ttp/tor_config.py b/ttp/tor_config.py index 71347c4..6f1bb89 100644 --- a/ttp/tor_config.py +++ b/ttp/tor_config.py @@ -77,7 +77,6 @@ def _build_torrc_content( tor_user: str, transport_port: int, dns_port: int, - block_doh: bool, use_bridges: bool, bridges: list[str] | None, ipv6_avail: bool, @@ -91,7 +90,6 @@ def _build_torrc_content( tor_user: System user running the Tor daemon. transport_port: Local TCP port for Tor TransPort redirection. dns_port: Local UDP/TCP port for Tor DNSPort redirection. - block_doh: If True, maps canary DoH domains to 0.0.0.0. use_bridges: If True, enables Tor bridges. bridges: Optional list of bridge configuration strings. ipv6_avail: Whether IPv6 is enabled and supported on loopback. @@ -131,17 +129,17 @@ def _build_torrc_content( f"DataDirectory {TOR_CACHE_DIR}", ] ) - if block_doh: - doh_domains = [ - "use-application-dns.net", # Firefox canary - "cloudflare-dns.com", - "dns.google", - "dns.quad9.net", - "doh.opendns.com", - "dns.adguard.com", - ] - for domain in doh_domains: - lines.append(f"MapAddress {domain} 0.0.0.0") + # Keep DNS on Tor's DNSPort: the canary turns Firefox's default DoH off, + # and the common DoH resolvers map to nowhere. + for domain in ( + "use-application-dns.net", # Firefox canary + "cloudflare-dns.com", + "dns.google", + "dns.quad9.net", + "doh.opendns.com", + "dns.adguard.com", + ): + lines.append(f"MapAddress {domain} 0.0.0.0") if use_bridges and bridges: lines.append("UseBridges 1") @@ -184,7 +182,6 @@ def generate_torrc( tor_user: str, transport_port: int = 9041, dns_port: int = 9054, - block_doh: bool = True, use_bridges: bool = False, bridges: Optional[list[str]] = None, disable_ipv6: bool = False, @@ -198,7 +195,6 @@ def generate_torrc( tor_user: Username running the Tor process. transport_port: Local TCP port for Tor TransPort redirection. dns_port: Local UDP/TCP port for Tor DNSPort redirection. - block_doh: If True, maps well-known DoH resolver domains to 0.0.0.0. use_bridges: If True, configures Tor to route via Pluggable Transports. bridges: Optional list of bridge lines (e.g. ``["obfs4 ...", "snowflake ..."]``). disable_ipv6: If True, forces IPv6 client routing off. @@ -246,7 +242,6 @@ def generate_torrc( tor_user=tor_user, transport_port=transport_port, dns_port=dns_port, - block_doh=block_doh, use_bridges=use_bridges, bridges=bridges, ipv6_avail=ipv6_avail, diff --git a/ttp/tor_install.py b/ttp/tor_install.py index 2a22428..d27e802 100644 --- a/ttp/tor_install.py +++ b/ttp/tor_install.py @@ -172,7 +172,6 @@ def _assert_is_tor_system_account(tor_user: str) -> None: def ensure_tor_ready( transport_port: int = 9041, dns_port: int = 9054, - block_doh: bool = True, use_bridges: bool = False, bridges: Optional[list[str]] = None, disable_ipv6: bool = False, @@ -186,7 +185,6 @@ def ensure_tor_ready( Args: transport_port: Local TCP port for Tor TransPort redirection. dns_port: Local UDP/TCP port for Tor DNSPort redirection. - block_doh: If True, blocks known DoH resolvers in firewall and torrc. use_bridges: If True, enables Pluggable Transport bridges. bridges: Optional list of bridge configuration strings. disable_ipv6: If True, forces IPv6 client routing off. @@ -238,7 +236,6 @@ def ensure_tor_ready( tor_user, transport_port=transport_port, dns_port=dns_port, - block_doh=block_doh, use_bridges=use_bridges, bridges=bridges, disable_ipv6=disable_ipv6, diff --git a/ttp/tor_service.py b/ttp/tor_service.py index 191baf2..ce248aa 100644 --- a/ttp/tor_service.py +++ b/ttp/tor_service.py @@ -162,7 +162,6 @@ def start_tor_service( tor_user: str, transport_port: int = 9041, dns_port: int = 9054, - block_doh: bool = True, use_bridges: bool = False, bridges: Optional[list[str]] = None, disable_ipv6: bool = False, @@ -179,7 +178,6 @@ def start_tor_service( tor_user: System user designated to run Tor. transport_port: Local TCP port for Tor TransPort redirection. dns_port: Local UDP/TCP port for Tor DNSPort redirection. - block_doh: If True, maps canary DoH domains to 0.0.0.0. use_bridges: If True, configures Tor to route via Pluggable Transports. bridges: Optional list of bridge configuration strings. disable_ipv6: If True, forces IPv6 client routing off. @@ -191,7 +189,6 @@ def start_tor_service( tor_user, transport_port=transport_port, dns_port=dns_port, - block_doh=block_doh, use_bridges=use_bridges, bridges=bridges, disable_ipv6=disable_ipv6, From 1802036617bd2fc2000e940750b1ac72b4d26c9d Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:14:20 +0100 Subject: [PATCH 14/16] Resolve the Tor UID once and keep one list of Tor account names apply_rules returns the UID it exempted, and start records that one in the lock, instead of resolving the name a second time behind an `except Exception: pass` that production could not reach. The Tor account names lived in four lists. tor_detect.TOR_ACCOUNTS is now the only one; the teardown and BYOD fallbacks also try toranon and _tor, and try debian-tor before tor. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- tests/test_cli_start.py | 34 +++++++--------------------------- tests/test_tor_detect.py | 4 ++-- ttp/commands/_tor_setup.py | 5 +++-- ttp/commands/lifecycle.py | 3 ++- ttp/commands/start.py | 8 +------- ttp/firewall/runner.py | 6 +++++- ttp/tor_detect.py | 6 ++++-- 7 files changed, 24 insertions(+), 42 deletions(-) diff --git a/tests/test_cli_start.py b/tests/test_cli_start.py index 5860afe..3a6e7fb 100644 --- a/tests/test_cli_start.py +++ b/tests/test_cli_start.py @@ -27,6 +27,7 @@ from ttp.evidence import ExitCode, Verification, VerificationState from ttp.exceptions import DNSError, FirewallError, StateError, TorError from ttp.runtime_records import RecordStore +from ttp.tor_detect import TOR_ACCOUNTS runner = CliRunner() @@ -176,7 +177,7 @@ def ready(**kwargs): patch("ttp.vpn.inspect_profile", side_effect=[profile, None if condition == "changed" else profile]), patch("ttp.vpn_guard.retained", return_value=condition == "retained"), patch("ttp.vpn_guard.install", side_effect=lambda *a: events.append("guard-verified")), - patch("ttp.firewall.apply_rules") as rules, + patch("ttp.firewall.apply_rules", return_value=100) as rules, patch("ttp.state.write_lock") as lock, patch("ttp.watchdog.start_watchdog"), ): @@ -591,35 +592,14 @@ def test_start_rollback_never_stops_a_tor_it_does_not_own( # --------------------------------------------------------------------------- -@patch("ttp.firewall.apply_rules") -@patch("pwd.getpwnam", side_effect=KeyError("no such user")) +@patch("ttp.firewall.apply_rules", return_value=4242) @patch("ttp.state.write_lock") -def test_start_records_an_unresolvable_tor_user_as_a_null_uid( - mock_write, - mock_pwnam, - mock_apply_rules, - mock_base_start, -): - """An unresolvable Tor user is swallowed, and the lock says so explicitly. - - `start` wraps the UID lookup in a bare `except Exception: pass`, so a Tor - user that does not resolve does not stop the session - it writes - `tor_uid: None` into the lock instead. That is not a dead end: `do_stop()` - treats a missing `tor_uid` as "work it out yourself" and falls back to - `get_uid_from_port(transport_port)`, then to `pwd.getpwnam` on "tor" and - "debian-tor" in turn (`ttp/commands/lifecycle.py:42-52`). - - That fallback chain is reachable *only* through this `pass`, which means it - was reachable only through an uncovered line. Pinning the null here is what - makes the chain's own tests meaningful: if this silently started writing a - real UID, or crashing, the fallback would become unreachable code that - still has tests. - """ +def test_start_records_the_uid_the_firewall_exempted(mock_write, mock_apply_rules, mock_base_start): + """The lock's tor_uid is the one the table exempts, resolved once by apply_rules.""" result = runner.invoke(app, ["start"]) assert result.exit_code == 0, result.output - assert mock_write.call_count == 1 - assert mock_write.call_args.kwargs["tor_uid"] is None + assert mock_write.call_args.kwargs["tor_uid"] == 4242 @patch("ttp.watchdog.start_watchdog", side_effect=RuntimeError("fork failed")) @@ -1051,7 +1031,7 @@ def test_start_external_daemon_happy_path_fallback_user( assert result.exit_code == 0, result.output assert "Tor daemon detected operating under UID: 110" in result.output - mock_pwnam.assert_any_call("tor") + mock_pwnam.assert_any_call(TOR_ACCOUNTS[0]) @patch("ttp.commands.start._is_port_listening_tcp", return_value=True) diff --git a/tests/test_tor_detect.py b/tests/test_tor_detect.py index 25da4b1..46ac23e 100644 --- a/tests/test_tor_detect.py +++ b/tests/test_tor_detect.py @@ -215,8 +215,8 @@ def test_detect_tor_user_custom_passwd(mock_run): mock_run.return_value = MagicMock(returncode=1) # ps fails with patch("ttp.tor_detect.Path.read_text") as mock_read: mock_read.return_value = "my-custom-tor:x:110:110::/var/lib/tor:/bin/false\n" - # Since 'my-custom-tor' is not in _KNOWN_USERS, it fallbacks to 'tor' - # Unless we update _KNOWN_USERS or improve detection. + # Since 'my-custom-tor' is not in TOR_ACCOUNTS, it fallbacks to 'tor' + # Unless we update TOR_ACCOUNTS or improve detection. assert _detect_tor_user() == "tor" diff --git a/ttp/commands/_tor_setup.py b/ttp/commands/_tor_setup.py index 03a3bbc..d1e38d8 100644 --- a/ttp/commands/_tor_setup.py +++ b/ttp/commands/_tor_setup.py @@ -29,6 +29,7 @@ ) from ttp.exceptions import TorError from ttp.paths import resolve +from ttp.tor_detect import TOR_ACCOUNTS from ttp.vpn import GUIDE, VPNError #: Largest bridge file read. A real one is a few lines; this bounds what a @@ -212,7 +213,7 @@ def _parse_bridges( # account names -- victor, actor, contractor, mentor, factory, history -- and # the UID matched here receives a full cleartext exemption in both the NAT # redirect chain and the fail-closed filter chain. -_KNOWN_TOR_USERNAMES = frozenset({"tor", "debian-tor", "toranon", "_tor"}) +_KNOWN_TOR_USERNAMES = frozenset(TOR_ACCOUNTS) def _resolve_external_tor_uid( @@ -273,7 +274,7 @@ def _resolve_external_tor_uid( # Step 3 — Known usernames fallback if resolved_uid is None: - for fallback_user in ("tor", "debian-tor"): + for fallback_user in TOR_ACCOUNTS: try: resolved_uid = pwd.getpwnam(fallback_user).pw_uid logger.info( diff --git a/ttp/commands/lifecycle.py b/ttp/commands/lifecycle.py index fab04ea..5a4fc67 100644 --- a/ttp/commands/lifecycle.py +++ b/ttp/commands/lifecycle.py @@ -21,6 +21,7 @@ ) from ttp.exceptions import FirewallError from ttp.paths import resolve_optional +from ttp.tor_detect import TOR_ACCOUNTS def close_redirected_or_retain(lock: dict | None) -> None: @@ -94,7 +95,7 @@ def do_stop() -> None: transport_port = lock.get("transport_port", 9041) tor_uid = get_uid_from_port(transport_port) if tor_uid is None: - for fallback_user in ("tor", "debian-tor"): + for fallback_user in TOR_ACCOUNTS: try: tor_uid = pwd.getpwnam(fallback_user).pw_uid break diff --git a/ttp/commands/start.py b/ttp/commands/start.py index 2dc702e..788a14d 100644 --- a/ttp/commands/start.py +++ b/ttp/commands/start.py @@ -317,7 +317,7 @@ def protect_vpn(tor_user: str) -> None: if vpn_policy is not None: kwargs_fw["vpn"] = vpn_policy.snapshot() - firewall.apply_rules( + tor_uid_val = firewall.apply_rules( tor_user=tor_user, transport_port=transport_port, dns_port=dns_port, @@ -358,12 +358,6 @@ def protect_vpn(tor_user: str) -> None: # --- Step 4: Write lock file --- try: - tor_uid_val: int | None = None - try: - tor_uid_val = int(tor_user) if tor_user.isdigit() else pwd.getpwnam(tor_user).pw_uid - except Exception: - pass - kwargs_lock: dict = {} if users: kwargs_lock["bypass_users"] = users diff --git a/ttp/firewall/runner.py b/ttp/firewall/runner.py index 5ee5752..6365520 100644 --- a/ttp/firewall/runner.py +++ b/ttp/firewall/runner.py @@ -174,7 +174,7 @@ def apply_rules( bypass_gids: list[int] | None = None, disable_ipv6: bool = False, vpn: dict | None = None, -) -> None: +) -> int: """Create the dedicated 'inet ttp' table and inject redirection rules. Create Table -> Flush Table -> Apply Ruleset is submitted to nft as a single @@ -191,6 +191,9 @@ def apply_rules( bypass_gids: Optional list of numeric GIDs exempted from redirection. disable_ipv6: If True, forces dropping all IPv6 traffic regardless of host availability. + Returns: + The Tor user's numeric UID, as exempted in the table. + Raises: FirewallError: If the tor_user is invalid or rule injection fails. """ @@ -243,6 +246,7 @@ def apply_rules( if not isinstance(e, FirewallError): raise FirewallError(f"Failed to apply stateless rules: {e}") from e raise + return tor_uid def destroy_rules() -> bool: diff --git a/ttp/tor_detect.py b/ttp/tor_detect.py index ebf0916..e2caeca 100644 --- a/ttp/tor_detect.py +++ b/ttp/tor_detect.py @@ -31,6 +31,9 @@ # Volatile runtime config path TORRC_PATH = Path("/run/tor/ttp/torrc") +#: The Tor account's name on the distributions TTP supports, in lookup order. +TOR_ACCOUNTS = ("debian-tor", "toranon", "tor", "_tor") + def _check_installed() -> bool: """Return ``True`` if a trusted ``tor`` binary is installed. @@ -163,10 +166,9 @@ def _detect_tor_user() -> str: pass # 2. Static fallback - known distro usernames. - _KNOWN_USERS = ("debian-tor", "toranon", "tor", "_tor") try: passwd = Path("/etc/passwd").read_text(encoding="utf-8") - for user in _KNOWN_USERS: + for user in TOR_ACCOUNTS: if re.search(rf"^{user}:", passwd, re.MULTILINE): return user except OSError: From cdbfedd94ebdcfd8ba4f0a65fe69b9726f5e7a74 Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:17:14 +0100 Subject: [PATCH 15/16] Fold three near-copies into loops and one helper semanage's add-then-modify, the four localhost bind probes, and systemd-resolved's restart-and-flush were each written out twice. Same calls, same order, same log levels. Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- ttp/commands/_ports.py | 47 +++++++++++---------------------- ttp/dns_resolved.py | 60 +++++++++++++++++++----------------------- ttp/selinux.py | 50 ++++++++++------------------------- 3 files changed, 56 insertions(+), 101 deletions(-) diff --git a/ttp/commands/_ports.py b/ttp/commands/_ports.py index 05e9e8b..48ed69d 100644 --- a/ttp/commands/_ports.py +++ b/ttp/commands/_ports.py @@ -16,40 +16,23 @@ def is_port_in_use(port: int) -> bool: import errno import socket - try: - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - s.bind(("127.0.0.1", port)) - except OSError: - return True - try: - with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - s.bind(("127.0.0.1", port)) - except OSError: - return True - - try: - with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - try: - s.bind(("::1", port)) - except OSError as e: - if e.errno == errno.EADDRINUSE: - return True - except OSError: - pass + for kind in (socket.SOCK_STREAM, socket.SOCK_DGRAM): + try: + with socket.socket(socket.AF_INET, kind) as s: + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.bind(("127.0.0.1", port)) + except OSError: + return True - try: - with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as s: - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - try: + # IPv6 may be disabled, so only "address in use" counts there. + for kind in (socket.SOCK_STREAM, socket.SOCK_DGRAM): + try: + with socket.socket(socket.AF_INET6, kind) as s: + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(("::1", port)) - except OSError as e: - if e.errno == errno.EADDRINUSE: - return True - except OSError: - pass + except OSError as e: + if e.errno == errno.EADDRINUSE: + return True return False diff --git a/ttp/dns_resolved.py b/ttp/dns_resolved.py index db2b88c..3580e57 100644 --- a/ttp/dns_resolved.py +++ b/ttp/dns_resolved.py @@ -45,6 +45,31 @@ def is_resolved_active(*, strict: bool = False) -> bool: return False +def _restart_resolved() -> None: + """Restart systemd-resolved on its current drop-ins, then drop its cache. + + A failed restart raises. A failed flush is only logged: it is the least + important step, already unchecked when resolvectl runs and fails. + """ + subprocess.run( + [resolve("systemctl"), "restart", "systemd-resolved"], + capture_output=True, + text=True, + check=True, + timeout=10, + ) + try: + subprocess.run( + [resolve("resolvectl"), "flush-caches"], + capture_output=True, + text=True, + check=False, + timeout=10, + ) + except Exception as e: + logger.debug("Failed to flush systemd-resolved caches: %s", e) + + def apply_resolved(dns_port: int, disable_ipv6: bool = False) -> bool: """Write volatile resolved configuration and restart systemd-resolved. @@ -89,21 +114,7 @@ def apply_resolved(dns_port: int, disable_ipv6: bool = False) -> bool: RESOLVED_CONF_FILE.write_text(config_content, encoding="utf-8") RESOLVED_CONF_FILE.chmod(0o644) - subprocess.run( - [resolve("systemctl"), "restart", "systemd-resolved"], - capture_output=True, - text=True, - check=True, - timeout=10, - ) - - subprocess.run( - [resolve("resolvectl"), "flush-caches"], - capture_output=True, - text=True, - check=False, - timeout=10, - ) + _restart_resolved() logger.info("Configured systemd-resolved for Tor DNS redirection.") return True except Exception as e: @@ -122,23 +133,6 @@ def restore_resolved() -> None: logger.warning("Failed to remove systemd-resolved drop-in: %s", e) try: - subprocess.run( - [resolve("systemctl"), "restart", "systemd-resolved"], - capture_output=True, - text=True, - check=True, - timeout=10, - ) + _restart_resolved() except Exception as e: logger.warning("Failed to restart systemd-resolved during restore: %s", e) - - try: - subprocess.run( - [resolve("resolvectl"), "flush-caches"], - capture_output=True, - text=True, - check=False, - timeout=10, - ) - except Exception as e: - logger.debug("Failed to flush systemd-resolved caches: %s", e) diff --git a/ttp/selinux.py b/ttp/selinux.py index 8125a47..f8a2511 100644 --- a/ttp/selinux.py +++ b/ttp/selinux.py @@ -171,48 +171,26 @@ def label_ports_selinux(transport_port: int, dns_port: int) -> None: return for port, proto in [(transport_port, "tcp"), (dns_port, "udp")]: - try: - logger.debug("Adding SELinux port label tor_port_t for %s/%s", port, proto) - subprocess.run( - [ - semanage, - "port", - "-a", - "-t", - "tor_port_t", - "-p", - proto, - str(port), - ], - capture_output=True, - check=True, - timeout=10, - ) - except subprocess.CalledProcessError: - # If the port mapping already exists, modify it instead + logger.debug("Adding SELinux port label tor_port_t for %s/%s", port, proto) + # -a (add) fails when the port already has a label; -m (modify) then changes it. + for action in ("-a", "-m"): try: subprocess.run( - [ - semanage, - "port", - "-m", - "-t", - "tor_port_t", - "-p", - proto, - str(port), - ], + [semanage, "port", action, "-t", "tor_port_t", "-p", proto, str(port)], capture_output=True, check=True, timeout=10, ) - except subprocess.CalledProcessError as e_mod: - logger.warning( - "Failed to label port %d/%s as tor_port_t: %s", - port, - proto, - e_mod.stderr.decode().strip(), - ) + break + except subprocess.CalledProcessError as e: + failure = e + else: + logger.warning( + "Failed to label port %d/%s as tor_port_t: %s", + port, + proto, + failure.stderr.decode().strip(), + ) def unlabel_ports_selinux(transport_port: int, dns_port: int) -> None: From a4c1054574e7031a4aa9dc83cb4c7f5ec9c433a4 Mon Sep 17 00:00:00 2001 From: onyks-os <129986281+onyks-os@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:18:27 +0100 Subject: [PATCH 16/16] Note the wider Tor account fallback in the changelog Co-Authored-By: Claude Opus 5.5 Signed-off-by: onyks-os <129986281+onyks-os@users.noreply.github.com> --- CHANGELOG.md | 7 +++++++ docs/web/release-notes/changelog.md | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7af95d4..12f8f82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 longer records `watchdog_active` and `watchdog_pid`, which nothing read: `ttp watchdog status` asks systemd. +### Changed + +- When the session lock does not say which UID Tor runs as, `ttp stop` and + `ttp start --external-daemon` look the account up among all four known + names (`debian-tor`, `toranon`, `tor`, `_tor`), the list that Tor detection + already used, instead of only `tor` and `debian-tor`. + ### Fixed - `ttp stop` deleted the session lock even when it could not remove the diff --git a/docs/web/release-notes/changelog.md b/docs/web/release-notes/changelog.md index 69dc482..1b88c3b 100644 --- a/docs/web/release-notes/changelog.md +++ b/docs/web/release-notes/changelog.md @@ -27,6 +27,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 longer records `watchdog_active` and `watchdog_pid`, which nothing read: `ttp watchdog status` asks systemd. +### Changed + +- When the session lock does not say which UID Tor runs as, `ttp stop` and + `ttp start --external-daemon` look the account up among all four known + names (`debian-tor`, `toranon`, `tor`, `_tor`), the list that Tor detection + already used, instead of only `tor` and `debian-tor`. + ### Fixed - `ttp stop` deleted the session lock even when it could not remove the