Reference: Python API Reference
Automated API reference generated directly from Google-style Python docstrings in the codebase via mkdocstrings.
Firewall Package (ttp.firewall)
ttp.firewall.builder
Stateless Firewall Module - Pure ruleset string generator.
ttp.firewall.runner
Stateless Firewall Module - Low-level nftables execution engine.
apply_rules(tor_user, transport_port=9041, dns_port=9054, allow_root=False, lan_bypass=True, bypass_uids=None, bypass_gids=None, disable_ipv6=False)
Create the dedicated 'inet ttp' table and inject redirection rules.
Create Table -> Flush Table -> Apply Ruleset is submitted to nft as a single transaction, so the table is never observable in a half-applied state. If any step fails, triggers an automatic rollback (table destruction).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tor_user
|
str
|
Username or numeric UID string of the Tor daemon process. |
required |
transport_port
|
int
|
Local TCP port for Tor TransPort redirection. |
9041
|
dns_port
|
int
|
Local UDP/TCP port for Tor DNSPort redirection. |
9054
|
allow_root
|
bool
|
If True, allows processes running as root (UID 0) to bypass rules. |
False
|
lan_bypass
|
bool
|
If True, excludes local LAN subnets from redirection. |
True
|
bypass_uids
|
list[int] | None
|
Optional list of numeric UIDs exempted from redirection. |
None
|
bypass_gids
|
list[int] | None
|
Optional list of numeric GIDs exempted from redirection. |
None
|
disable_ipv6
|
bool
|
If True, forces dropping all IPv6 traffic regardless of host availability. |
False
|
Raises:
| Type | Description |
|---|---|
FirewallError
|
If the tor_user is invalid or rule injection fails. |
Source code in ttp/firewall/runner.py
destroy_rules()
Destroy the 'ttp' table and clean up firewall rules.
This is the atomic cleanup operation. It flushes the table, destroys it, and verifies that the table is no longer present in kernel state.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the table was successfully destroyed or already gone. |
Raises:
| Type | Description |
|---|---|
FirewallError
|
If table destruction fails and the table remains active. |
Source code in ttp/firewall/runner.py
ttp.firewall.emergency
Stateless Firewall Module - Emergency lockdown, killswitch, and socket slaughter mechanisms.
apply_active_socket_slaughter()
Inject temporary reject rules at the top of the filter_out chain.
Actively terminates pending local connections by sending immediate ICMP Port Unreachable for UDP sockets and TCP RST packets for open TCP streams.
Source code in ttp/firewall/emergency.py
apply_emergency_killswitch()
Apply an emergency network killswitch.
Replaces the 'inet ttp' table with an ultra-restrictive ruleset that drops all inbound, outbound, and forwarded network traffic on physical interfaces, permitting only local loopback communication.
Raises:
| Type | Description |
|---|---|
FirewallError
|
If table creation or killswitch ruleset injection fails. |
Source code in ttp/firewall/emergency.py
apply_teardown_lockdown(tor_uid=None)
Insert a lockdown drop rule at the top of the filter_out chain in table inet ttp.
Ensures all non-loopback outbound traffic is dropped during graceful session teardown, while permitting the Tor daemon UID to close control connections cleanly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tor_uid
|
int | None
|
Optional numeric UID of the Tor daemon process to exempt from lockdown. |
None
|
Source code in ttp/firewall/emergency.py
Tor Configuration & Lifecycle (ttp.tor_*)
ttp.tor_config
Tor configuration and torrc generation module.
generate_torrc(tor_user, transport_port=9041, dns_port=9054, block_doh=True, use_bridges=False, bridges=None, disable_ipv6=False)
Generate a volatile torrc in /run/tor/ttp/torrc.
The DataDirectory points to the persistent cache (/var/lib/tor/ttp)
so that Entry Guards are preserved across runs for fast bootstrapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tor_user
|
str
|
Username running the Tor process. |
required |
transport_port
|
int
|
Local TCP port for Tor TransPort redirection. |
9041
|
dns_port
|
int
|
Local UDP/TCP port for Tor DNSPort redirection. |
9054
|
block_doh
|
bool
|
If True, maps well-known DoH resolver domains to 0.0.0.0. |
True
|
use_bridges
|
bool
|
If True, configures Tor to route via Pluggable Transports. |
False
|
bridges
|
Optional[list[str]]
|
Optional list of bridge lines (e.g. |
None
|
disable_ipv6
|
bool
|
If True, forces IPv6 client routing off. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
Absolute path to the generated |
Source code in ttp/tor_config.py
ttp.tor_service
Tor systemd service lifecycle management module.
start_tor_service(tor_user, transport_port=9041, dns_port=9054, block_doh=True, use_bridges=False, bridges=None, disable_ipv6=False)
Generate the runtime torrc and start a dedicated TTP Tor systemd service.
Sequence
- Generate volatile torrc in
/run/tor/ttp/torrc. - Label SELinux ports if SELinux is enforcing.
- Write a volatile
ttp-tor.serviceunit to/run/systemd/system/. - Reload systemd daemon and start the service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tor_user
|
str
|
System user designated to run Tor. |
required |
transport_port
|
int
|
Local TCP port for Tor TransPort redirection. |
9041
|
dns_port
|
int
|
Local UDP/TCP port for Tor DNSPort redirection. |
9054
|
block_doh
|
bool
|
If True, maps canary DoH domains to 0.0.0.0. |
True
|
use_bridges
|
bool
|
If True, configures Tor to route via Pluggable Transports. |
False
|
bridges
|
Optional[list[str]]
|
Optional list of bridge configuration strings. |
None
|
disable_ipv6
|
bool
|
If True, forces IPv6 client routing off. |
False
|
Raises:
| Type | Description |
|---|---|
TorError
|
If systemd daemon reload or service restart fails. |
Source code in ttp/tor_service.py
stop_tor_service()
Stop the dedicated TTP Tor service and remove the volatile systemd unit.
Source code in ttp/tor_service.py
ttp.tor_install
Tor readiness checking and orchestration module.
This module enforces a strict NO AUTO-INSTALL policy. TTP will never attempt to install system packages automatically. If Tor or required pluggable transport helpers are missing, TTP displays distro-specific package guidance and official documentation links, then exits gracefully with status code 0.
ensure_pluggable_transports(required_transports)
Verify that required pluggable transport helper binaries are installed.
If any required binary is missing, displays distro package guidance and official Tor documentation links, then exits gracefully with status code 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
required_transports
|
list[str]
|
List of pluggable transport names (e.g. |
required |
Raises:
| Type | Description |
|---|---|
Exit
|
With exit code 0 if any transport binary is missing or unsupported. |
Source code in ttp/tor_install.py
ensure_tor_ready(transport_port=9041, dns_port=9054, block_doh=True, use_bridges=False, bridges=None, disable_ipv6=False)
Ensure Tor is installed and start it via the dedicated systemd service.
Enforces a strict NO AUTO-INSTALL policy. If Tor or required helper binaries are missing, displays distro-aware installation guidance and exits gracefully with status code 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transport_port
|
int
|
Local TCP port for Tor TransPort redirection. |
9041
|
dns_port
|
int
|
Local UDP/TCP port for Tor DNSPort redirection. |
9054
|
block_doh
|
bool
|
If True, blocks known DoH resolvers in firewall and torrc. |
True
|
use_bridges
|
bool
|
If True, enables Pluggable Transport bridges. |
False
|
bridges
|
Optional[list[str]]
|
Optional list of bridge configuration strings. |
None
|
disable_ipv6
|
bool
|
If True, forces IPv6 client routing off. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Dictionary containing detected Tor installation metadata. |
Raises:
| Type | Description |
|---|---|
Exit
|
With exit code 0 if Tor binary is not installed on the system. |
Source code in ttp/tor_install.py
ttp.tor_control
Tor daemon control and circuit verification.
This module is the "voice" of TTP. It communicates directly with the Tor daemon using the Stem library. It handles authentication, bootstrap monitoring, circuit rotation (Signal.NEWNYM), and external API verification to confirm that traffic is actually being routed through Tor.
KEY RESPONSIBILITIES: 1. Connect to Tor via Unix Socket or TCP ControlPort. 2. Monitor bootstrap progress until 100%. 3. Request new exit IPs (circuits). 4. Verify the current exit IP via multiple endpoints for resilience.
get_controller()
Connect to the dedicated ttp-tor control interface only.
Uses exclusively ControlSocket /run/tor/ttp/control.sock so
bootstrap queries, NEWNYM, and shutdown signals always target TTP's
isolated instance - never tor.service or TCP ControlPort.
Returns an authenticated :class:stem.control.Controller or None.
Source code in ttp/tor_control.py
get_exit_ip()
Fetch the current Tor exit IP, trying multiple endpoints for resilience.
Uses urllib.request from the stdlib so we don't need to add
requests as a dependency.
Source code in ttp/tor_control.py
graceful_shutdown(timeout=10)
Send SHUTDOWN signal to Tor for clean circuit teardown.
This MUST be called before firewall teardown to avoid leaking cleartext RST packets on the physical interface. Tor will close all circuits cryptographically, then exit.
Parameters
timeout: Maximum seconds to wait for Tor to finish closing circuits.
Returns
bool
True if the shutdown signal was sent successfully.
Source code in ttp/tor_control.py
request_new_circuit()
Request a new Tor circuit (new exit IP) and wait for it to change.
Returns
tuple[bool, str]
(ip_changed, current_ip)
Source code in ttp/tor_control.py
verify_tor()
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.
Source code in ttp/tor_control.py
wait_for_bootstrap(progress_callback=None, timeout=180)
Wait for Tor to reach 100% bootstrap status via ControlPort.
Parameters
progress_callback: Optional callable that takes an integer (0-100) representing the bootstrap percentage.
Source code in ttp/tor_control.py
DNS & State Management (ttp.dns, ttp.state)
ttp.dns
DNS Management Module - Handles routing DNS queries through Tor.
This module implements a stateless, Kernel-level DNS redirection strategy
using a mount --bind overlay on /etc/resolv.conf.
apply_dns(interface, disable_ipv6=False, dns_port=9054)
Apply Tor DNS settings using a Kernel-level overlay (mount --bind).
If systemd-resolved is active, also writes a volatile drop-in configuration and restarts it via the ttp.dns_resolved module.
Returns a dictionary containing backup data for restoration.
Source code in ttp/dns.py
detect_active_interface()
Detect the primary network interface using 'ip route'.
Source code in ttp/dns.py
restore_dns(backup)
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.
Source code in ttp/dns.py
ttp.state
State management - Volatile lock file for crash-safe operations.
This module acts as the "memory" of TTP. It tracks active sessions
using a JSON-formatted lock file stored in /run/ttp/ (a tmpfs
mount). Because the lock lives on a volatile filesystem, it vanishes
on reboot, eliminating stale-lock issues after power loss.
The only persistent path used by TTP is /var/lib/ttp/ which is
managed by ttp.ux (one-time UX engagement features).
CORE CONCEPTS: - Lock File: Located at /run/ttp/ttp.lock (volatile - tmpfs). - Orphans: A lock exists but the recorded PID is dead. - Recovery: The process of reading an orphan lock and calling rollback logic.
attempt_recovery(destroy_firewall, restore_dns)
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)
Source code in ttp/state.py
check_tmpfs_space(min_bytes=MIN_TMPFS_BYTES)
Abort if /run (tmpfs) has insufficient free space.
Must be called before any I/O to /run so that TTP
fails fast instead of crashing mid-setup with ENOSPC.
Raises
StateError
If free space on /run is below min_bytes.
Source code in ttp/state.py
delete_lock()
ensure_runtime_dir()
Create /run/ttp with mode 0700.
Must be called early in the CLI startup before any I/O that targets the runtime directory (lock file, log file, torrc, etc.).
Owned by ttp-watchdog if the user exists, otherwise owned by root.
Source code in ttp/state.py
is_orphan()
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.
Source code in ttp/state.py
read_lock()
Read and return the lock data, or None if no lock exists.
Source code in ttp/state.py
update_lock_keys(**kwargs)
Update specific keys in the existing lock file, preserving other keys.
If no lock file exists, this raises a StateError.
Source code in ttp/state.py
write_lock(*, pid=None, dns_backup=None, transport_port=9041, dns_port=9054, allow_root=False, lan_bypass=True, watchdog_active=False, watchdog_pid=None, interface=None, bypass_users=None, bypass_groups=None, use_bridges=False, bridge_file=None, bridges=None, external_daemon=False, no_ipv6=False, tor_uid=None)
Write the session lock file with the current state.
Parameters
pid: PID to record. Defaults to the current process. dns_backup: Original DNS data (resolv.conf mount target dictionary). transport_port: The customized or default TransPort port. dns_port: The customized or default DNSPort port. allow_root: 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: List of system users bypassed from Tor routing. bypass_groups: List of system groups bypassed from Tor routing. use_bridges: True if Tor bridges support is enabled. bridge_file: Path to the bridge file, if provided. bridges: List of configured bridge lines. tor_uid: The resolved UID of the Tor daemon process.
Source code in ttp/state.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
Watchdog Engine (ttp.watchdog)
ttp.watchdog.integrity
Session integrity checks and auto-healing logic.
attempt_auto_healing(failed_component)
Attempt to dynamically repair a failed session component.
Returns:
bool True if the healing commands succeeded, False otherwise.
Source code in ttp/watchdog/integrity.py
check_system_integrity()
Verify Tor connection, firewall rules and DNS overlay.
Returns:
tuple[Optional[str], Optional[str]] (failed_component, error_message) e.g., ("dns", "overlay unmounted") or (None, None) if all is healthy.
Source code in ttp/watchdog/integrity.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | |
has_default_route()
Return True if a default gateway route exists in the system.
Source code in ttp/watchdog/integrity.py
is_interface_online(interface)
Check if a network interface is physically online (has carrier and is up).
Source code in ttp/watchdog/integrity.py
ttp.watchdog.fsm
Finite State Machine (FSM) implementation for TTP watchdog.
WatchdogFSM
Watchdog Finite State Machine managing transitions, sockets, and recovery logic.
Source code in ttp/watchdog/fsm.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | |
flush_event_buffers(fds)
Discard any accumulated events in netlink or inotify queues.
Source code in ttp/watchdog/fsm.py
readd_watch()
Re-register inotify watches on the target file and symlink.