🛡️ Defense-in-Depth Hardening for V3 Onion Infrastructure
Deploying an onion service protects network-layer routing automatically, yet most real-world server deanonymizations stem from application-layer misconfigurations: services listening on public interfaces (0.0.0.0), leaked server headers, clearnet DNS lookups, or unpatched web endpoints. Hardening requires strict loopback or Unix-socket binding, firewall egress/ingress lockdown, protocol-level DoS defenses, and strict separation from public Tor relays.
1. Example 1: Loopback-Only torrc & Unix Domain Socket Binding
Configure
/etc/tor/torrc to route virtual onion ports exclusively to a local Unix domain socket (eliminating TCP port exposure entirely) and prevent running a public relay on the same host.
Config / Bash (hardened_torrc.sh)
cat << 'EOF'
# /etc/tor/torrc - Hardened Onion Service Configuration
User debian-tor
DataDirectory /var/lib/tor
SafeLogging 1
DisableDebuggerAttachment 1
# Never run a public relay or exit on an onion service host
ORPort 0
ExitRelay 0
# V3 Onion Service bound to a restricted Unix Domain Socket
HiddenServiceDir /var/lib/tor/secure_cti_service/
HiddenServiceVersion 3
HiddenServicePort 80 unix:/run/tor-onion/nginx.sock
EOF
chmod 700 /var/lib/tor/secure_cti_service/
Output:
# /etc/tor/torrc - Hardened Onion Service Configuration
User debian-tor
DataDirectory /var/lib/tor
SafeLogging 1
DisableDebuggerAttachment 1
# Never run a public relay or exit on an onion service host
ORPort 0
ExitRelay 0
# V3 Onion Service bound to a restricted Unix Domain Socket
HiddenServiceDir /var/lib/tor/secure_cti_service/
HiddenServiceVersion 3
HiddenServicePort 80 unix:/run/tor-onion/nginx.sock
2. Example 2: Hardened Nginx Reverse Proxy Without Metadata Leaks
Strip server version banners, disable
server_status endpoints, disable access logs that store timestamps, and enforce strict Content-Security-Policy headers so the web tier reveals zero host fingerprints.
Nginx Config (onion_vhost.conf)
server {
listen unix:/run/tor-onion/nginx.sock;
server_name r6j52r5p6j32q3u6y32k4q6f4d3s2a1z9x8c7v6b5n4m3l2k1j0h9g8d.onion;
# Strip identifying server tokens and disable logging
server_tokens off;
access_log off;
error_log /dev/null crit;
# Block external resource loads & clearnet leaks
add_header Content-Security-Policy "default-src 'self'; frame-ancestors 'none';" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer" always;
location / {
root /var/www/onion_portal;
index index.html;
limit_except GET HEAD { deny all; }
}
}
Output:
[OK] Nginx vhost bound exclusively to unix:/run/tor-onion/nginx.sock
[OK] server_tokens=off | access_log=off | External CSP origins blocked
3. Example 3: UFW & iptables Leak-Prevention Firewall Rules
Drop all unsolicited inbound traffic, block non-Tor outbound connections from the web application user (
www-data), and prevent accidental clearnet DNS or HTTP callbacks.
Bash (onion_firewall.sh)
# Default deny all incoming traffic (Tor initiates outbound circuits only)
ufw default deny incoming
ufw default allow outgoing
# Block web service user from initiating direct clearnet TCP/UDP sockets
iptables -A OUTPUT -m owner --uid-owner www-data -d 127.0.0.1/8 -j ACCEPT
iptables -A OUTPUT -m owner --uid-owner www-data -j REJECT --reject-with icmp-port-unreachable
echo "Firewall Policy: Inbound=DENY | www-data Non-Loopback Egress=REJECT"
Output:
Firewall Policy: Inbound=DENY | www-data Non-Loopback Egress=REJECT
4. Example 4: Socket Exposure & Leak Surface Auditor
Programmatically audit active listening sockets to flag any backend daemon bound to
0.0.0.0 or :: instead of 127.0.0.1 or a Unix socket.
Python (audit_listening_sockets.py)
listeners = [
{"service": "nginx-onion", "bind": "unix:/run/tor-onion/nginx.sock", "port": None},
{"service": "postgres-db", "bind": "127.0.0.1", "port": 5432},
{"service": "debug-api", "bind": "0.0.0.0", "port": 8080},
{"service": "tor-socks", "bind": "127.0.0.1", "port": 9050},
]
for item in listeners:
bind = item["bind"]
is_safe = bind.startswith("127.") or bind == "::1" or bind.startswith("unix:")
status = "PASS (Isolated)" if is_safe else "FAIL (Public Interface Leak!)"
print(f"{item['service']:<14} | Bind: {bind:<32} | {status}")
Output:
nginx-onion | Bind: unix:/run/tor-onion/nginx.sock | PASS (Isolated)
postgres-db | Bind: 127.0.0.1 | PASS (Isolated)
debug-api | Bind: 0.0.0.0 | FAIL (Public Interface Leak!)
tor-socks | Bind: 127.0.0.1 | PASS (Isolated)
5. Example 5: Introduction Point DoS Rate-Limiting (Proposal 305)
Instruct your Introduction Points to enforce per-second rate and burst limits on incoming client
INTRODUCE1 cells before they ever reach your hidden service circuits.
Python (intro_dos_config.py)
def generate_intro_dos_torrc(rate_per_sec: int = 25, burst_per_sec: int = 200) -> str:
if rate_per_sec <= 0 or burst_per_sec <= 0:
raise ValueError("Setting rate or burst to 0 disables Introduction Point DoS defense!")
return "\n".join([
"HiddenServiceEnableIntroDoSDefense 1",
f"HiddenServiceEnableIntroDoSRatePerSec {rate_per_sec}",
f"HiddenServiceEnableIntroDoSBurstPerSec {burst_per_sec}"
])
print(generate_intro_dos_torrc(rate_per_sec=20, burst_per_sec=150))
Output:
HiddenServiceEnableIntroDoSDefense 1
HiddenServiceEnableIntroDoSRatePerSec 20
HiddenServiceEnableIntroDoSBurstPerSec 150
6. Example 6: Proof-of-Work (PoW) Anti-DDoS Priority Queue
Enable Tor's dynamic Equi-X / HashX client puzzle defense so legitimate visitors are prioritized over automated flood bots during active DDoS attacks.
Python (pow_defense_sim.py)
pow_torrc = """HiddenServicePoWDefensesEnabled 1
HiddenServicePoWQueueRate 15
HiddenServicePoWQueueBurst 75"""
incoming_requests = [
{"client": "TorBrowser_User_A", "pow_effort": 5000},
{"client": "Botnet_Flood_01", "pow_effort": 0},
{"client": "TorBrowser_User_B", "pow_effort": 12000},
{"client": "Botnet_Flood_02", "pow_effort": 10},
]
prioritized = sorted(incoming_requests, key=lambda r: r["pow_effort"], reverse=True)
print(pow_torrc + "\n")
for rank, req in enumerate(prioritized, start=1):
print(f"Queue #{rank}: {req['client']:<20} | Submitted PoW Effort: {req['pow_effort']}")
Output:
HiddenServicePoWDefensesEnabled 1
HiddenServicePoWQueueRate 15
HiddenServicePoWQueueBurst 75
Queue #1: TorBrowser_User_B | Submitted PoW Effort: 12000
Queue #2: TorBrowser_User_A | Submitted PoW Effort: 5000
Queue #3: Botnet_Flood_02 | Submitted PoW Effort: 10
Queue #4: Botnet_Flood_01 | Submitted PoW Effort: 0
7. Example 7: Multi-Layer Vanguards Guard Protection
Mitigate Guard Discovery and Sybil traffic-analysis attacks by pinning second-layer (Layer 2) and third-layer (Layer 3) guard sets in front of your onion service's primary Entry Guards.
Python (vanguards_topology.py)
torrc_vanguards = {
"HSLayer2Nodes": "8A4F19C2...,3E7B04A1...,9D2A81F0...,51C0E7B4...",
"HSLayer3Nodes": "2B89A4E3...,6F12C8D9...,7C31B0E5...,4D90F2A8..."
}
print("Vanguard Circuit Protection Layers:")
print(" Layer 1 (Entry Guards) : Pinned for 60-90 days (protects server IP)")
print(" Layer 2 (Middle Guards): Pinned for 1-45 days (blocks Layer-1 Sybil enumeration)")
print(" Layer 3 (Outer Guards) : Pinned for 1-48 hours (absorbs fast circuit churn)")
for key, val in torrc_vanguards.items():
print(f"{key} {val}")
Output:
Vanguard Circuit Protection Layers:
Layer 1 (Entry Guards) : Pinned for 60-90 days (protects server IP)
Layer 2 (Middle Guards): Pinned for 1-45 days (blocks Layer-1 Sybil enumeration)
Layer 3 (Outer Guards) : Pinned for 1-48 hours (absorbs fast circuit churn)
HSLayer2Nodes 8A4F19C2...,3E7B04A1...,9D2A81F0...,51C0E7B4...
HSLayer3Nodes 2B89A4E3...,6F12C8D9...,7C31B0E5...,4D90F2A8...
8. Example 8: Systemd Sandboxing & Read-Only Filesystem Isolation
Apply a systemd drop-in override (
/etc/systemd/system/tor@default.service.d/hardening.conf) to restrict kernel access, isolate /tmp, and mount system directories read-only.
Systemd Unit (tor_hardening.conf)
[Service]
NoNewPrivileges=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectHome=yes
ProtectSystem=strict
ReadWritePaths=/var/lib/tor /var/log/tor /run/tor-onion
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictRealtime=yes
SystemCallFilter=@system-service
Output:
[OK] Systemd sandbox active: ProtectSystem=strict, PrivateTmp=yes, NoNewPrivileges=yes
9. Example 9: Automated HTTP Response Header & Leak Scanner
Query your hosted
.onion service over local SOCKS5h and verify that no clearnet URLs, server version strings, or identifying ETag/Server headers appear in responses.
Python (onion_header_audit.py)
import re
sample_headers = {
"Server": "nginx",
"Content-Type": "text/html; charset=utf-8",
"Content-Security-Policy": "default-src 'self'",
"Referrer-Policy": "no-referrer"
}
findings = []
if re.search(r"\d+\.\d+", sample_headers.get("Server", "")):
findings.append("HIGH: Server header exposes software version number")
if "X-Powered-By" in sample_headers:
findings.append("HIGH: X-Powered-By header leaks backend runtime")
if "Content-Security-Policy" not in sample_headers:
findings.append("MEDIUM: Missing CSP header allows external clearnet asset loads")
print("Security Audit Status:", "CLEAN (0 Leaks)" if not findings else findings)
Output:
Security Audit Status: CLEAN (0 Leaks)
10. Example 10: High-Availability Onionbalance Frontend Architecture
Scale a critical v3 onion service across multiple isolated backend Tor instances using Onionbalance, publishing a unified master descriptor containing Introduction Points from active backends without exposing backend keys.
Python (onionbalance_aggregator.py)
backends = [
{"name": "backend-eu-01", "status": "HEALTHY", "intro_points": ["IP_EU_1", "IP_EU_2"]},
{"name": "backend-na-02", "status": "HEALTHY", "intro_points": ["IP_NA_1", "IP_NA_2"]},
{"name": "backend-as-03", "status": "OFFLINE", "intro_points": ["IP_AS_1", "IP_AS_2"]},
]
active_ips = []
for node in backends:
if node["status"] == "HEALTHY":
active_ips.extend(node["intro_points"])
print("Master V3 Descriptor Published Introduction Points:", active_ips)
print("Total Active Introduction Points:", len(active_ips))
Output:
Master V3 Descriptor Published Introduction Points: ['IP_EU_1', 'IP_EU_2', 'IP_NA_1', 'IP_NA_2']
Total Active Introduction Points: 4