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 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_cli_start.py b/tests/test_cli_start.py index 7b79417..3a6e7fb 100644 --- a/tests/test_cli_start.py +++ b/tests/test_cli_start.py @@ -24,10 +24,10 @@ 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 +from ttp.tor_detect import TOR_ACCOUNTS runner = CliRunner() @@ -177,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"), ): @@ -294,7 +294,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 +329,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 +353,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 +415,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 @@ -592,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")) @@ -1052,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_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_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_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/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/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/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/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/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/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/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/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"] +) 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/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/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/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/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: 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_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. 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: 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, 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, 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.