Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- `ttp start` interrupted with Ctrl-C or SIGTERM before it recorded its session
undid nothing and exited `0`. It printed "Signal received, restoring
network...", but the nftables table, the DNS overlay and the managed Tor
stayed in place. `ttp status` then reported `INACTIVE`, `ttp stop` reported
that no session was found, and a script that trusted the `0` believed the
host was protected. The start is now undone as `ttp stop --restore-only`
would undo it, including closing connections redirected during the start
before the rules go, and it exits `1`. Interrupted after the session was
recorded, start still stops the session, but now exits `1` instead of `0`.
A latched emergency (exit `8`) and a retained VPN guard (exit `10`) are kept
as before. The signal handler no longer tears anything down itself: it
raises, so an `nft` or `systemctl` call in flight finishes unwinding before
the undo starts.

### Tests

- The `nse` extra requires `network-sandbox-engine>=2.5.2`. Each rule load in
Expand Down Expand Up @@ -59,6 +75,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Documentation

- [Startup phases and their failure
contract](https://onyks-os.github.io/ttp/explanation/startup/) states what
each phase of `ttp start` changes, where the first barrier falls and what a
failure or an interruption leaves behind. It is the L01 contract of the
leak-testing plan.

- The VPN guide shows how to import a provider's WireGuard file into
NetworkManager, and what to check first. It must have one peer, a numeric
endpoint (with how to replace a hostname) and a full-tunnel `AllowedIPs`. The
Expand Down
2 changes: 1 addition & 1 deletion docs/security/leak-testing-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ security promise against applications holding raw-packet capabilities.
| N03 / P1 | Competing-ruleset NSE + VM | Existing Docker/UFW/firewalld/WireGuard shapes; reload real firewall managers during traffic | Distinguish coexistence from destructive removal; rule-specific mutation detects regressions; recovery cannot hide initial exposure |

L01 requires documenting the intended failure contract before assigning pass
criteria to rollback. The plan does not silently change a failed start into a
criteria to rollback. That contract is [Startup phases and their failure contract](../web/explanation/startup.md). The plan does not silently change a failed start into a
persistent lockdown feature. Keep full-capture diagnostics even for failures
that occur before the normal session lock exists.

Expand Down
80 changes: 80 additions & 0 deletions docs/web/explanation/startup.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<!--
Copyright (c) 2026 onyks-os
SPDX-License-Identifier: MIT
-->

# Explanation: Startup Phases and Their Failure Contract

`ttp start` does not protect the host from the moment it is invoked. It
changes the system in a fixed order, and what a failure or an interruption
leaves behind depends on how far it got. This page states that contract, phase
by phase, from the code in `ttp/commands/start.py`. It is the reference that
L01 of the [leak-testing plan](https://github.com/onyks-os/TransparentTorProxy/blob/main/docs/security/leak-testing-plan.md)
measures against.

**Status:** each failure and interruption outcome below has a unit test
(`tests/test_cli_start.py`). Where the first barrier falls, and what crosses
the wire before it, has not yet been measured from outside a VM. That is L01's
external part, which waits for the continuous capture of slice 3.

## The two halves

Startup has two halves, and they fail differently.

- **Before the session is recorded** (phases 1 to 4), a failure undoes
everything start did and leaves the host in cleartext, deliberately. A failed
start is not turned into a lockdown: nothing would record it, and nothing
would tell `ttp stop` or `ttp status` that it exists.
- **After the session is recorded** (phases 5 to 7), the session exists. A
failure no longer rolls back. It either leaves the session configured and
says so with a nonzero exit code, or requests emergency containment, which
holds until an explicit `ttp stop`.

No outcome that leaves the host unprotected exits `0`.

## Phases

| 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 |
| 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 |
| 4. Session record | The session lock, with the fingerprint of the table the watchdog must find | As phase 2 | Own Tor stopped, table destroyed, DNS restored: cleartext, exit `1` | As phase 1 |
| 5. Notifications | The desktop agent, if selected | Contained | Session kept, exit `9` | Session stopped, exit `1` |
| 6. Watchdog | Required watchdog readiness, if selected | Contained | Emergency containment requested and latched, exit nonzero | Session stopped, exit `1`; a latched emergency is retained, exit `8` |
| 7. Verification | Nothing; Tor routing is checked from outside | Contained | Inconclusive: session kept, exit `3`. Negative: emergency containment | As phase 6 |

"Undone like `stop --restore-only`" means that start derives what to undo from
the host instead of a session record. It stops the managed Tor and closes the
connections redirected during the start while the rules still hold them. If
one cannot be closed, the rules stay and start exits `8`. Then it removes the
table and the DNS overlay. An external Tor (`--external-daemon`) is never
stopped.

## Interruptions

The signal handler does not undo anything itself. It runs between two
bytecodes of whatever start was doing, possibly while an `nft` or `systemctl`
child is still running, so a teardown there could remove the table before that
child loads it. It raises `StartInterrupted` instead. The call in flight
unwinds first (`subprocess.run` kills and reaps its child), and only then does
start undo itself. A second Ctrl-C during the undo is ignored.

Until the release after 0.5.1, an interruption in phases 1 to 4 found no session record and
undid nothing. The table, the overlay and Tor stayed in place. `ttp status`
reported `INACTIVE` and `ttp stop` reported that no session was found. Start
exited `0`, so a script that trusted it believed the host was protected.
After phase 4 the session was stopped, but start still exited `0`.

## What this contract does not claim

- **Protection before phase 2.** Applications that run while Tor starts send
in cleartext, unless the required VPN guard is in place.
- **That a connection opened before `ttp start` is moved into Tor.** It is
ended at its next packet; see [Architecture](architecture.md).
- **Anything about `SIGKILL` or a power loss during startup.** Nothing runs.
A table without a session record (phases 2 to 4) stays until `ttp stop
--restore-only`. A recorded session stays until `ttp stop`, and the next
`ttp start` refuses to run until then. A power loss ends both, because the
rules and the record live only in memory and `/run`.
22 changes: 22 additions & 0 deletions docs/web/release-notes/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- `ttp start` interrupted with Ctrl-C or SIGTERM before it recorded its session
undid nothing and exited `0`. It printed "Signal received, restoring
network...", but the nftables table, the DNS overlay and the managed Tor
stayed in place. `ttp status` then reported `INACTIVE`, `ttp stop` reported
that no session was found, and a script that trusted the `0` believed the
host was protected. The start is now undone as `ttp stop --restore-only`
would undo it, including closing connections redirected during the start
before the rules go, and it exits `1`. Interrupted after the session was
recorded, start still stops the session, but now exits `1` instead of `0`.
A latched emergency (exit `8`) and a retained VPN guard (exit `10`) are kept
as before. The signal handler no longer tears anything down itself: it
raises, so an `nft` or `systemctl` call in flight finishes unwinding before
the undo starts.

### Tests

- The `nse` extra requires `network-sandbox-engine>=2.5.2`. Each rule load in
Expand Down Expand Up @@ -54,6 +70,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Documentation

- [Startup phases and their failure
contract](https://onyks-os.github.io/ttp/explanation/startup/) states what
each phase of `ttp start` changes, where the first barrier falls and what a
failure or an interruption leaves behind. It is the L01 contract of the
leak-testing plan.

- The VPN guide shows how to import a provider's WireGuard file into
NetworkManager, and what to check first. It must have one peer, a numeric
endpoint (with how to replace a hostname) and a full-tunnel `AllowedIPs`. The
Expand Down
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ nav:
- Security and Quality Findings: how-to/security-quality.md
- Explanation:
- Architecture & Flow: explanation/architecture.md
- Startup Phases & Failures: explanation/startup.md
- Session Watchdog: explanation/watchdog-fsm.md
- Zero-Leak Verification: explanation/verification.md
- Security & Threat Model: explanation/security-assessment.md
Expand Down
16 changes: 16 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@

import os
import shutil
import signal
import stat
import sys
import tempfile
Expand Down Expand Up @@ -266,3 +267,18 @@ def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None:
if _shim_dir is not None:
shutil.rmtree(_shim_dir, ignore_errors=True)
_shim_dir = None


@pytest.fixture(autouse=True)
def restore_signal_handlers():
"""Undo what ``ttp start`` does to SIGINT/SIGTERM in the test process.

``register_signal_handlers`` installs TTP's handler and an interrupted
start ignores both signals while it undoes itself. Left in place, the
first would turn a Ctrl-C of the test run into ``StartInterrupted`` and the
second would make the run ignore Ctrl-C altogether.
"""
saved = {signum: signal.getsignal(signum) for signum in (signal.SIGINT, signal.SIGTERM)}
yield
for signum, handler in saved.items():
signal.signal(signum, handler)
109 changes: 109 additions & 0 deletions tests/test_cli_start.py
Original file line number Diff line number Diff line change
Expand Up @@ -1468,3 +1468,112 @@ def test_start_notification_and_degraded_outcomes(mock_write, mock_firewall, moc
if scenario == "recipient_missing":
agent.assert_not_called()
assert "notifications.recipient_unavailable" in result.output


# interrupted start (L01)


def _interrupt(*args, **kwargs):
"""SIGINT arriving inside whatever start is doing at that moment."""
from ttp.commands import lifecycle

lifecycle.signal_handler(2, None)


@pytest.fixture
def undo_mocks(monkeypatch):
"""What `stop --restore-only` touches, recorded instead of run."""
from ttp.runtime_records import RecordStore

mocks = types.SimpleNamespace(
destroy=MagicMock(), restore_dns=MagicMock(), stop_tor=MagicMock(), close=MagicMock(return_value=0)
)
monkeypatch.setattr("ttp.firewall.destroy_rules", mocks.destroy)
monkeypatch.setattr("ttp.dns.restore_dns", mocks.restore_dns)
monkeypatch.setattr("ttp.tor_install.stop_tor_service", mocks.stop_tor)
monkeypatch.setattr("ttp.firewall.close_redirected_sockets", mocks.close)
monkeypatch.setattr("ttp.tor_control.graceful_shutdown", MagicMock(return_value=False))
monkeypatch.setattr("ttp.watchdog.stop_watchdog", MagicMock())
monkeypatch.setattr("ttp.state.delete_lock", MagicMock())
monkeypatch.setattr("ttp.state.write_stop_marker", MagicMock())
store = MagicMock(spec=RecordStore)
monkeypatch.setattr("ttp.runtime_records.session_store", lambda: store)
return mocks


@pytest.mark.parametrize(
"target",
[
pytest.param("ttp.tor_install.ensure_tor_ready", id="tor-setup"),
pytest.param("ttp.firewall.runner._run_nft_string", id="rules-load"),
pytest.param("ttp.dns.apply_dns", id="dns-overlay"),
],
)
@patch("ttp.firewall.runner._run_nft")
@patch("ttp.firewall.runner.pwd.getpwnam", return_value=types.SimpleNamespace(pw_uid=110))
def test_a_start_interrupted_before_its_session_is_recorded_is_undone(
_pw, _nft, target, undo_mocks, mock_base_start, monkeypatch
):
"""Ctrl-C or SIGTERM between Tor setup and the session record.

The handler used to call do_stop, which returns at once without a lock: the
table, the overlay and Tor stayed, `ttp stop` said "No active session
found", `ttp status` said INACTIVE, and start exited 0, so a script that
trusted it ran on believing it was protected. Now everything start did is
undone as `stop --restore-only` would, and it exits 1.
"""
# patch(), not monkeypatch: mock_base_start patches some of these targets,
# and monkeypatch would put its mock back after the fixture removed it.
with patch("ttp.firewall.runner._run_nft_string"), patch(target, side_effect=_interrupt):
result = runner.invoke(app, ["start"])

assert result.exit_code == 1, result.output
assert "undoing its changes" in result.output
assert "Network restored" in result.output
# Before removing the rules, as stop does: a redirected connection opened
# during the start must not retransmit in cleartext once they are gone.
assert undo_mocks.close.call_count == 1
assert undo_mocks.destroy.call_count == 1
assert undo_mocks.stop_tor.call_count == 1
# The overlay may be half applied: it is found on the host, not in a backup.
undo_mocks.restore_dns.assert_called_once_with(None)


@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_a_start_interrupted_after_its_session_is_recorded_stops_it(
_write, _pw, _nft, _nfts, undo_mocks, mock_base_start, monkeypatch
):
"""Interrupted during verification: the recorded session is stopped, and start exits 1, not 0."""
monkeypatch.setattr("ttp.session_safety.emergency_latched", lambda lock: False)
stop = MagicMock()
monkeypatch.setattr("ttp.commands.lifecycle.do_stop", stop)

with patch("ttp.commands.start._verify_tor", side_effect=_interrupt):
result = runner.invoke(app, ["start", "--no-watchdog"])

assert result.exit_code == 1, result.output
stop.assert_called_once()
assert "Session active" not 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.state.write_lock")
def test_an_interrupted_start_with_latched_emergency_keeps_it(
_write, _pw, _nft, _nfts, undo_mocks, mock_base_start, monkeypatch
):
"""Emergency containment holds until an explicit `ttp stop`, Ctrl-C included."""
monkeypatch.setattr("ttp.session_safety.emergency_latched", lambda lock: True)
stop = MagicMock()
monkeypatch.setattr("ttp.commands.lifecycle.do_stop", stop)

with patch("ttp.commands.start._verify_tor", side_effect=_interrupt):
result = runner.invoke(app, ["start", "--no-watchdog"])

assert result.exit_code == 8, result.output
stop.assert_not_called()
assert undo_mocks.destroy.call_count == 0
28 changes: 21 additions & 7 deletions tests/test_cli_stop.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ def test_partial_vpn_start_requires_explicit_restore(tmp_path, monkeypatch):
monkeypatch.setattr("ttp.state.read_lock", lambda **kw: None)
result = runner.invoke(app, ["stop"])
assert result.exit_code == 10 and "restore-only" in result.output
with pytest.raises(SystemExit) as stopped:
lifecycle.signal_handler(2, None)
assert stopped.value.code == 10
assert lifecycle.finish_interrupted_start() == 10


@pytest.fixture(autouse=True)
Expand Down Expand Up @@ -546,16 +544,32 @@ def test_do_stop_survives_a_watchdog_that_will_not_stop():
delete_lock.assert_called_once()


def test_signal_handler_tears_down_and_exits_zero():
"""SIGINT/SIGTERM during a foreground session must restore the network."""
def test_the_signal_handler_only_raises():
"""It runs between two bytecodes of start, maybe while an nft child still runs.

Tearing down there could destroy the table before that child loads it, so
the handler changes nothing: interruptible_start undoes the start once the
in-flight call has unwound.
"""
with (
patch("ttp.commands.lifecycle.do_stop") as do_stop,
pytest.raises(SystemExit) as exc,
patch("ttp.commands.lifecycle.restore_without_session") as restore,
pytest.raises(lifecycle.StartInterrupted) as interrupted,
):
lifecycle.signal_handler(15, None)

assert interrupted.value.signum == 15
do_stop.assert_not_called()
restore.assert_not_called()


def test_an_interrupted_recorded_start_stops_the_session_and_exits_one(monkeypatch):
"""The network is restored, and start does not report a session it never finished."""
monkeypatch.setattr("ttp.state.read_lock", lambda **kw: {"session_id": "s", "pid": 1})
monkeypatch.setattr("ttp.session_safety.emergency_latched", lambda lock: False)
with patch("ttp.commands.lifecycle.do_stop") as do_stop:
assert lifecycle.finish_interrupted_start() == 1
do_stop.assert_called_once()
assert exc.value.code == 0


@pytest.mark.parametrize("restore", [False, True])
Expand Down
4 changes: 1 addition & 3 deletions tests/test_contract_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,7 @@ def test_interrupt_does_not_remove_latched_or_unknown_protection(monkeypatch, un
)
stop = Mock()
monkeypatch.setattr(lifecycle, "do_stop", stop)
with pytest.raises(SystemExit) as error:
lifecycle.signal_handler(2, None)
assert error.value.code == 8
assert lifecycle.finish_interrupted_start() == 8
stop.assert_not_called()


Expand Down
Loading