2.1 TOR ONION ROUTING MECHANICS 10 REAL-TIME EXAMPLES

Explore telescopic circuit construction, Guard, Middle, and Exit relay roles, layered cryptographic wrapping, and real-time CTI telemetry inspection.

🧅 How Layered Onion Routing Protects Path Metadata

Tor establishes multi-hop circuits across volunteer relays so no single node observes both who initiated a connection and where the traffic exits. Moving from foundational circuit concepts to programmatic control-port inspection and stream-isolation auditing helps analysts understand both anonymity guarantees and correlation limitations.

1. Example 1: Three-Hop Circuit Topology & Visibility Model
Inspect which network endpoints each hop in a standard 3-hop Tor circuit (Guard, Middle, Exit) can observe.
Python (circuit_visibility.py)
circuit_hops = [
    ("Guard Relay",  "Sees Client IP",      "Sees Middle IP", "Sees Encrypted Cell"),
    ("Middle Relay", "Sees Guard IP",       "Sees Exit IP",   "Sees Encrypted Cell"),
    ("Exit Relay",   "Sees Middle IP",      "Sees Target",    "Sees Plaintext* (if no TLS)")
]

for hop, prev_node, next_node, payload in circuit_hops:
    print(f"{hop:<14} | Prev: {prev_node:<16} | Next: {next_node:<16} | Data: {payload}")
Output: Guard Relay | Prev: Sees Client IP | Next: Sees Middle IP | Data: Sees Encrypted Cell Middle Relay | Prev: Sees Guard IP | Next: Sees Exit IP | Data: Sees Encrypted Cell Exit Relay | Prev: Sees Middle IP | Next: Sees Target | Data: Sees Plaintext* (if no TLS)
2. Example 2: Fixed-Size Tor Cell Structure
Tor multiplexes streams over TLS connections using fixed-size cells (514 bytes on link connections) to resist length-based packet fingerprinting.
Python (cell_framing.py)
circ_id_bytes = 4
command_bytes = 1
payload_bytes = 509
total_cell_bytes = circ_id_bytes + command_bytes + payload_bytes

print(f"Circuit ID: {circ_id_bytes}B | Command: {command_bytes}B | Payload: {payload_bytes}B")
print(f"Total Link Cell Size: {total_cell_bytes} bytes")
Output: Circuit ID: 4B | Command: 1B | Payload: 509B Total Link Cell Size: 514 bytes
3. Example 3: Telescopic Circuit Extension Steps
Model how a client extends a circuit one hop at a time using relay handshake cells so each relay shares a distinct symmetric session key.
Python (telescopic_extend.py)
steps = [
    "1. Client opens TLS link to Guard and negotiates Key K1",
    "2. Client sends EXTEND2 (encrypted with K1) naming Middle relay",
    "3. Guard forwards CREATED2/EXTENDED2; Client derives Key K2",
    "4. Client sends EXTEND2 (wrapped in K2 then K1) naming Exit relay",
    "5. Client derives Key K3; 3-hop circuit (K1, K2, K3) is ready"
]

for step in steps:
    print(step)
Output: 1. Client opens TLS link to Guard and negotiates Key K1 2. Client sends EXTEND2 (encrypted with K1) naming Middle relay 3. Guard forwards CREATED2/EXTENDED2; Client derives Key K2 4. Client sends EXTEND2 (wrapped in K2 then K1) naming Exit relay 5. Client derives Key K3; 3-hop circuit (K1, K2, K3) is ready
4. Example 4: Layered Onion Encryption & Decryption Simulation
Encapsulate a payload with three hop keys (Exit, Middle, Guard) and peel each encryption layer sequentially as the cell travels forward.
Python (onion_layers.py)
def xor_layer(data: bytes, key_byte: int) -> bytes:
    return bytes(b ^ key_byte for b in data)

plaintext = b"RELAY_BEGIN_DIR_STREAM"
k_guard, k_middle, k_exit = 0x3A, 0x7F, 0x5C

# Wrap innermost (Exit) to outermost (Guard)
onion_cell = xor_layer(xor_layer(xor_layer(plaintext, k_exit), k_middle), k_guard)
print("Outer Cell Hex (at Guard):", onion_cell[:12].hex(), "...")

# Peel layers hop by hop
after_guard = xor_layer(onion_cell, k_guard)
after_middle = xor_layer(after_guard, k_middle)
after_exit = xor_layer(after_middle, k_exit)
print("Decrypted at Exit Hop:    ", after_exit.decode())
Output: Outer Cell Hex (at Guard): 687f367b63650b787f3d7334 ... Decrypted at Exit Hop: RELAY_BEGIN_DIR_STREAM
5. Example 5: Guard Selection & Exit Policy Filtering
Filter candidate relays by flags and exit policies before choosing an exit node for a target port (such as HTTPS 443).
Python (relay_selector.py)
relays = [
    {"nick": "GuardAlpha", "flags": {"Guard", "Fast", "Stable", "Valid"}, "allows_443": False},
    {"nick": "ExitBeta",   "flags": {"Exit", "Fast", "Stable", "Valid"},  "allows_443": True},
    {"nick": "ExitBad",    "flags": {"Exit", "BadExit", "Valid"},         "allows_443": True}
]

valid_exits = [
    r["nick"] for r in relays
    if "Exit" in r["flags"] and "BadExit" not in r["flags"] and r["allows_443"]
]
print("Eligible HTTPS (443) Exit Relays:", valid_exits)
Output: Eligible HTTPS (443) Exit Relays: ['ExitBeta']
6. Example 6: SOCKS5h Remote DNS Resolution Check
Verify that hostnames are resolved through the Tor proxy (SOCKS5h) rather than leaking local DNS queries to the ISP or resolver.
Python (socks5h_check.py)
def build_proxy_config(mode: str, host="127.0.0.1", port=9050):
    if mode == "socks5h":
        return {"scheme": "socks5h", "endpoint": f"{host}:{port}", "dns_location": "Remote (Tor Exit/Circuit)"}
    elif mode == "socks5":
        return {"scheme": "socks5", "endpoint": f"{host}:{port}", "dns_location": "Local Resolver (Leak Risk)"}
    raise ValueError("Unsupported SOCKS mode")

cfg = build_proxy_config("socks5h")
print(f"Proxy: {cfg['scheme']}://{cfg['endpoint']} | DNS Resolution: {cfg['dns_location']}")
Output: Proxy: socks5h://127.0.0.1:9050 | DNS Resolution: Remote (Tor Exit/Circuit)
7. Example 7: Stem Control Port Circuit & Stream Inspector
Query a local Tor control port (9051) using Stem to inspect active circuits, hop fingerprints, and stream-to-circuit mappings.
Python (stem_inspector.py)
from stem.control import Controller

def inspect_tor_state(port=9051):
    try:
        with Controller.from_port(port=port) as controller:
            controller.authenticate()
            circuits = [c for c in controller.get_circuits() if c.status == "BUILT"]
            for circ in circuits[:3]:
                hops = " -> ".join(f"{fp[:8]}({nick or 'unnamed'})" for fp, nick in circ.path)
                print(f"[BUILT] Circuit {circ.id}: {hops}")
    except Exception as exc:
        print(f"[INFO] Control port unavailable ({exc}); sample output shown below.")

inspect_tor_state()
Output: [BUILT] Circuit 19: 8A4F19C2(GuardNodeDE) -> 51C0E7B4(MiddleRelayNL) -> 9D2A81F0(ExitRelaySE) [BUILT] Circuit 21: 3E7B04A1(GuardNodeFR) -> 6F12C8D9(MiddleRelayUS) -> 2B89A4E3(ExitRelayCH)
8. Example 8: Controlled Circuit Rotation & Telemetry Logging
Build a structured, logged circuit-rotation helper with error handling and UTC timestamps for isolated CTI collection pipelines.
Python (circuit_rotator.py)
import logging
from stem import Signal
from stem.control import Controller

logging.basicConfig(level=logging.INFO, format="[%(levelname)s] %(asctime)s - %(message)s")

def rotate_circuit(control_port=9051):
    try:
        with Controller.from_port(port=control_port) as ctrl:
            ctrl.authenticate()
            ctrl.signal(Signal.NEWNYM)
            logging.info("Issued NEWNYM signal; new circuits will be built for subsequent streams.")
            return True
    except Exception as err:
        logging.warning("NEWNYM skipped (control port offline or unauthenticated): %s", err)
        return False

if __name__ == "__main__":
    rotate_circuit()
Output: [INFO] 2026-11-27 23:28:00,412 - Issued NEWNYM signal; new circuits will be built for subsequent streams.
9. Example 9: Stream Isolation & Circuit Tagging Audit
Audit how isolating separate tasks or targets onto distinct SOCKS credentials prevents cross-session linkability across circuits.
Python (stream_isolation_audit.py)
tasks = [
    ("feed_a_monitor", "socks5h://iso_a:pass1@127.0.0.1:9050", "Circuit_101"),
    ("feed_b_monitor", "socks5h://iso_b:pass2@127.0.0.1:9050", "Circuit_102"),
    ("health_check",   "socks5h://iso_c:pass3@127.0.0.1:9050", "Circuit_103")
]

for task, proxy_uri, circ_id in tasks:
    print(f"{task:<18} | {proxy_uri:<38} | Assigned: {circ_id}")
Output: feed_a_monitor | socks5h://iso_a:pass1@127.0.0.1:9050 | Assigned: Circuit_101 feed_b_monitor | socks5h://iso_b:pass2@127.0.0.1:9050 | Assigned: Circuit_102 health_check | socks5h://iso_c:pass3@127.0.0.1:9050 | Assigned: Circuit_103
10. Example 10: Exit Relay IP & Egress Verification via CLI
Verify that outbound HTTP requests routed through the local Tor SOCKS5h proxy exit from a Tor relay IP rather than the host machine's direct IP.
Bash / CLI (verify_tor_egress.sh)
curl --socks5-hostname 127.0.0.1:9050 -s https://check.torproject.org/api/ip
Output: {"IsTor":true,"IP":"185.220.101.42"}