Skip to content

rooter: drop non-redirected FORWARD traffic and track active Tor clients in socks5_enable - #102

Closed
karlhiramoto wants to merge 1 commit into
masterfrom
fix/socks5-tor-forward-drop
Closed

karlhiramoto wants to merge 1 commit into
masterfrom
fix/socks5-tor-forward-drop

Conversation

@karlhiramoto

@karlhiramoto karlhiramoto commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes packet-filtering and connection-tracking gaps in socks5_enable / socks5_disable (utils/rooter.py) used for Tor and SOCKS5 transparent proxy routing:

  1. Drop non-redirected forwarded guest traffic (FORWARD chain):
    • socks5_enable previously appended -A OUTPUT --source <ipaddr> -j DROP. Because bridged/routed guest VM packets that are not redirected to a local proxy/DNS port traverse FORWARD (not OUTPUT), non-TCP traffic (such as browser HTTP/3 QUIC over UDP/443 or ICMP) could bypass Tor/SOCKS5 when bridge forwarding (libvirt_fwo_enable) and host NAT masquerading are enabled.
    • Inserts -w 5 -I FORWARD 1 --source <ipaddr> -j DROP in socks5_enable and removes all matching entries via _iptables_delete_all in socks5_disable. Guest traffic redirected to local ResultServer, DNSPort, and TransPort/SOCKSport traverses INPUT and continues to work normally.
  2. Accept active Tor/SOCKS5 guest IPs in raw chain CAPE_TOR_CLIENTS:
    • Pre-creates raw chain CAPE_TOR_CLIENTS (iptables -w 5 -t raw -N CAPE_TOR_CLIENTS) and registers --source <ipaddr> -p tcp -j ACCEPT while socks5_enable is active (cleaned up in socks5_disable and on cleanup_rooter()). Using -j ACCEPT in raw exits raw PREROUTING traversal (passing packets into conntrack and nat PREROUTING REDIRECT --to-ports <proxy_port>) even when jumped to from a nested raw RFC1918 guard subchain, allowing Tor VirtualAddrNetwork (e.g. 10.192.0.0/10 for .onion AutomapHostsOnResolve) strictly for active Tor/SOCKS5 VMs.
  3. Flush per-VM conntrack state (conntrack -D -s <ipaddr>):
    • Clears stale conntrack flows on socks5_enable and socks5_disable (matching nexthop_enable / nexthop_disable) so recycled snapshot VM IPs cannot reuse prior NAT/UDP state across tasks.

Testing

  • Added unit tests in tests/test_rooter_socks5.py verifying socks5_enable, socks5_disable, duplicate rule cleanup, conntrack flushing, and cleanup_rooter() preservation of :CAPE_TOR_CLIENTS.

@gracehopper-vt gracehopper-vt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 4d0b303. This is the fork-side counterpart of VirusTotal/vt-cape#923 (patch_capev2_tor.py injects exactly these lines), so the same main finding applies.

What's right:

  • The FORWARD drop is the correct fix for the QUIC/UDP/ICMP leak. Traffic redirected to the ResultServer, DNSPort and TransPort goes through INPUT, so it isn't affected. Inserting at position 1 puts the drop ahead of the ESTABLISHED,RELATED accept, and it's idempotent through _iptables_delete_all.
  • Cleanup: everything except the -N goes through run_iptables, so it carries the CAPE-rooter comment, and cleanup_rooter() filters those out of iptables-save for every table, including raw. The add and delete argument lists match exactly.
  • tests/test_rooter_socks5.py: 2 passed locally (a minimal tree with utils/rooter.py, path_utils and constants from this head).

Blocking (inline): the CAPE_TOR_CLIENTS entry uses -j RETURN, so it can't actually let .onion traffic through the RFC1918 drop. The tests only assert the argument tuples, so they can't catch this.

Comment thread utils/rooter.py Outdated
log.info("Enabling socks route.")
run(ServicePaths.iptables, "-t", "raw", "-N", "CAPE_TOR_CLIENTS")
_iptables_delete_all("-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "RETURN")
run_iptables("-t", "raw", "-A", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "RETURN")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RETURN in a user chain resumes the calling chain at its next rule. On our CAPE hosts the caller is VT_GUEST_FWD (raw PREROUTING, vt-cape custom_firewall.sh), and the rules right after the -j CAPE_TOR_CLIENTS jump are -d 10.0.0.0/8 -j DROP and friends. So a Tor VM's SYN to Tor's VirtualAddrNetwork (10.192.x.y) returns into VT_GUEST_FWD and is dropped, the same as a non-Tor VM falling off the end of the empty chain. The .onion routing stays broken.

Use -j ACCEPT here and in both _iptables_delete_all calls (L1125, L1161). In the raw table, ACCEPT only ends raw-table traversal; conntrack and nat PREROUTING still run, so the REDIRECT --to-ports <proxy_port> installed below still applies.

Keep this and vt-cape#923 in sync. kevoreilly#923's idempotency check only looks for CAPE_TOR_CLIENTS plus the FORWARD strings, so if one side is switched to ACCEPT and the other isn't, the patch script will report "already up to date" and leave RETURN in place.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in commit 6788c02: switched CAPE_TOR_CLIENTS in utils/rooter.py (socks5_enable and socks5_disable _iptables_delete_all / run_iptables calls) from -j RETURN to -j ACCEPT (with -w 5 and per-VM conntrack -D -s <ipaddr> flushes) so active Tor/SOCKS5 VM packets exit raw PREROUTING into conntrack and nat PREROUTING REDIRECT instead of returning to VT_GUEST_FWD's RFC1918 DROP rules. vt-cape#923 should also be kept in sync with -j ACCEPT.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6788c02: switched CAPE_TOR_CLIENTS add/delete rules from -j RETURN to -j ACCEPT (with -w 5 lock wait and conntrack -D -s per-VM flush) and updated tests/test_rooter_socks5.py.

@dsecuma dsecuma left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary: Changes Requested ❌

Reviewed VirusTotal/CAPEv2#102 (fix/socks5-tor-forward-drop, commit 4d0b3031b392da320189914f20020e97f3a2e1f3).

Blocking / Actionable Findings

  1. [CRITICAL] CAPE_TOR_CLIENTS uses -j RETURN instead of -j ACCEPT, dropping Tor .onion traffic in VT_GUEST_FWD (utils/rooter.py:1126): When VT_GUEST_FWD (raw PREROUTING in custom_firewall.sh) jumps to CAPE_TOR_CLIENTS for Tor's VirtualAddrNetwork (10.192.0.0/10), evaluating -j RETURN in CAPE_TOR_CLIENTS resumes traversal in VT_GUEST_FWD at the very next rule (-d 10.0.0.0/8 -j DROP), causing Tor .onion TCP connections to be unconditionally dropped. Must use -j ACCEPT in socks5_enable (L1125, L1126) and socks5_disable (L1161).
  2. [HIGH] Unit test asserts flawed -j RETURN rule (tests/test_rooter_socks5.py:29, tests/test_rooter_socks5.py:40): Unit tests currently assert that -j RETURN is passed to iptables. Must be updated to assert -j ACCEPT.

Verification Summary (Passing Checks)

  • Forwarded UDP/QUIC leak mitigation (utils/rooter.py): Inserting -I FORWARD 1 --source <ipaddr> -j DROP in socks5_enable (and clearing via _iptables_delete_all in socks5_disable) cleanly drops non-redirected guest traffic (HTTP/3 QUIC over UDP/443, ICMP) before bridge forward and host NAT masquerade, without impacting local/redirected traffic on INPUT (ResultServer on 2042, Tor DNS on 5354, Tor TransPort on 9040).
  • Idempotency & rule cleanup (utils/rooter.py): _iptables_delete_all correctly purges matching rules prior to insertion and upon disable.
  • Chain creation (utils/rooter.py): Directly invoking run(ServicePaths.iptables, "-t", "raw", "-N", "CAPE_TOR_CLIENTS") is correct because iptables -N creates a chain and does not accept match extensions (unlike run_iptables which appends -m comment).

Comment thread utils/rooter.py Outdated
log.info("Enabling socks route.")
run(ServicePaths.iptables, "-t", "raw", "-N", "CAPE_TOR_CLIENTS")
_iptables_delete_all("-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "RETURN")
run_iptables("-t", "raw", "-A", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "RETURN")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[CRITICAL] CAPE_TOR_CLIENTS must use -j ACCEPT instead of -j RETURN

Trigger & Impact:
In custom_firewall.sh (raw PREROUTING), VT_GUEST_FWD jumps to CAPE_TOR_CLIENTS strictly for Tor virtual destinations:

"$ipt" -t raw -A VT_GUEST_FWD -s 172.16.1.0/24 -d 10.192.0.0/10 -p tcp -j CAPE_TOR_CLIENTS
for net in 169.254.0.0/16 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 100.64.0.0/10; do
  "$ipt" -t raw -A VT_GUEST_FWD -d "$net" -j DROP
done

In netfilter, evaluating -j RETURN in a user-defined chain terminates subchain traversal and resumes at the next rule in the calling chain (VT_GUEST_FWD).
The rule immediately following the jump is -d 10.0.0.0/8 -j DROP. Because Tor's VirtualAddrNetwork (10.192.0.0/10) falls entirely within 10.0.0.0/8, returning to VT_GUEST_FWD causes Tor .onion TCP SYNs to be dropped immediately, leaving .onion routing non-functional.

In the raw table, -j ACCEPT terminates traversal of the raw table, allowing the packet to proceed to nat PREROUTING where REDIRECT --to-ports <proxy_port> intercepts it. Non-Tor VMs fall off the end of CAPE_TOR_CLIENTS, return to VT_GUEST_FWD, and hit -d 10.0.0.0/8 -j DROP as intended.

Suggested Fix:

    run(ServicePaths.iptables, "-t", "raw", "-N", "CAPE_TOR_CLIENTS")
    _iptables_delete_all("-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "ACCEPT")
    run_iptables("-t", "raw", "-A", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "ACCEPT")
    _iptables_delete_all("-D", "FORWARD", "--source", ipaddr, "-j", "DROP")
    run_iptables("-I", "FORWARD", "1", "--source", ipaddr, "-j", "DROP")

(Also update _iptables_delete_all in socks5_disable on line 1161 to delete -j ACCEPT)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in commit 6788c02: updated CAPE_TOR_CLIENTS in utils/rooter.py (socks5_enable _iptables_delete_all/run_iptables and socks5_disable _iptables_delete_all) to use -j ACCEPT instead of -j RETURN (along with -w 5 and per-VM conntrack -D -s <ipaddr>).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you! Fixed in 6788c02: updated CAPE_TOR_CLIENTS in socks5_enable and socks5_disable to use -j ACCEPT (along with -w 5 and conntrack -D -s).

Comment thread tests/test_rooter_socks5.py Outdated
rooter.socks5_enable("172.16.1.4", "2042", "5354", "9040")

assert ("iptables", "-t", "raw", "-N", "CAPE_TOR_CLIENTS") in rec["run"]
assert ("-t", "raw", "-A", "CAPE_TOR_CLIENTS", "--source", "172.16.1.4", "-p", "tcp", "-j", "RETURN") in rec["iptables"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] Update test assertion to expect -j ACCEPT

Trigger & Impact:
test_socks5_enable_installs_forward_drop_and_tor_client_mark and test_socks5_disable_removes_forward_drop_and_tor_client_mark currently assert that -j RETURN is passed to iptables. Because test_rooter_socks5.py mocks command execution by recording arguments, asserting -j RETURN enshrines the flawed packet-drop behavior.

Suggested Fix:

    assert ("-t", "raw", "-A", "CAPE_TOR_CLIENTS", "--source", "172.16.1.4", "-p", "tcp", "-j", "ACCEPT") in rec["iptables"]

(And update test_socks5_disable_removes_forward_drop_and_tor_client_mark on line 40 to assert deletion of -j ACCEPT)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in commit 6788c02: updated tests/test_rooter_socks5.py (test_socks5_enable_installs_forward_drop_and_tor_client_accept and test_socks5_disable_removes_stacked_duplicates_and_flushes_conntrack) to assert -j ACCEPT (and added test_cleanup_rooter_preserves_cape_tor_clients_chain_and_strips_vm_rules).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6788c02: updated tests/test_rooter_socks5.py to assert -j ACCEPT, delete-before-add ordering, stacked duplicate removal, conntrack flushing, and cleanup_rooter() preservation of :CAPE_TOR_CLIENTS.

@karlhiramoto
karlhiramoto requested a review from dsecuma November 18, 2026 13:20

@gracehopper-vt gracehopper-vt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at 6788c02. The blocker is fixed: the per-VM CAPE_TOR_CLIENTS rule is now -j ACCEPT in socks5_enable and in both deletes, so Tor VMs' TCP to 10.192.0.0/10 leaves raw PREROUTING and reaches the nat REDIRECT instead of returning into the 10.0.0.0/8 DROP.

Verified locally:

  • tests/test_rooter_socks5.py: 3 passed, in a minimal tree with utils/rooter.py, path_utils and constants from this head. That includes the new cleanup_rooter() test, which checks that :CAPE_TOR_CLIENTS and the VT_GUEST_FWD jump survive the iptables-save filtering while the tagged per-VM rule is removed.
  • The injected socks5_enable/socks5_disable blocks are byte-identical to _ENABLE_REPLACEMENT/_DISABLE_REPLACEMENT in VirusTotal/vt-cape#923 at bc3bfc7, so patch_capev2_tor.py is a no-op on this rooter and the two PRs stay in sync.
  • Creating the chain with run(...) instead of run_iptables is correct: -N rejects the appended -m comment, and leaving the chain untagged keeps it across cleanup_rooter().

LGTM. Two small notes:

  1. _iptables_delete_all stops looping at the first non-empty stderr. With -w 5, iptables can print Another app is currently holding the xtables lock; waiting... to stderr while it's still going to succeed, which would cut the duplicate-removal loop short after one deletion. That's harmless in the normal case (one copy), but if you want it airtight, break on the return code / "Bad rule" text rather than on any stderr. (This is upstream helper behaviour, so it's optional here.)
  2. run("conntrack", ...) needs the conntrack CLI on the host. run() swallows the error if it's missing, so the flush would silently not happen. Same which conntrack check on cape-base-template as for kevoreilly#923.

@dsecuma dsecuma left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary: Changes Requested ❌

Reviewed VirusTotal/CAPEv2#102 (fix/socks5-tor-forward-drop, commit 6788c02133c19f5346c4a86a540dc94bab66c54a).

The prior CAPE_TOR_CLIENTS -j RETURN blocker from 4d0b303 is fixed (-j ACCEPT in socks5_enable and socks5_disable, matching VirusTotal/vt-cape#923 byte-for-byte). However, 3 substantive reliability and test issues remain:

Blocking / Actionable Findings

  1. [HIGH] socks5_enable fails open on iptables -w 5 timeout / error and _iptables_delete_all aborts on lock stderr (utils/rooter.py:1126-1129, utils/rooter.py:715-718): run() (utils/rooter.py:57-58) uses check=False and discards returncode, and socks5_enable ignores all run_iptables return values. If iptables -w 5 -I FORWARD 1 --source <ipaddr> -j DROP fails or times out on the xtables lock, socks5_enable returns None (exception=None) and AnalysisManager launches the malware VM without FORWARD DROP (failing open to UDP/QUIC/ICMP egress leaks). Additionally, _iptables_delete_all (utils/rooter.py:717) stops on any non-empty stderr, so an xtables lock-wait/timeout stderr line on -w 5 exits with 0 deletions—leaving FORWARD DROP or CAPE_TOR_CLIENTS ACCEPT stuck on that VM IP for subsequent tasks.
  2. [HIGH] tests/test_rooter_socks5.py bypasses run_iptables and omits lock/duplicate/ordering assertions (tests/test_rooter_socks5.py:25, tests/test_rooter_socks5.py:40-45): Monkeypatching rooter.run_iptables directly skips -m comment --comment CAPE-rooter attachment (breaking end-to-end verification with cleanup_rooter()), splitting calls["run"] and calls["iptables"] prevents cross-call ordering assertions, delete_counts == 3 is not asserted in socks5_enable, and -w 5 lock-wait/timeout stderr paths are untested.
  3. [MEDIUM] conntrack -D -s ipaddr runs before nat PREROUTING REDIRECT rules are deleted in socks5_disable (utils/rooter.py:1164): Because AnalysisManager.network_routing() calls socks5_disable() while the VM is still running (stop_machine() runs later in machine_running().__exit__), flushing conntrack before removing nat PREROUTING REDIRECT rules (1165-1190) lets packets from the still-running VM recreate Tor conntrack entries during teardown.

Verification Summary (Passing Checks)

  • Tor VirtualAddrNetwork acceptance (utils/rooter.py:1125-1127, 1162): Verified -j ACCEPT is used in socks5_enable and both _iptables_delete_all calls, exiting raw PREROUTING into conntrack + nat PREROUTING REDIRECT while preserving :CAPE_TOR_CLIENTS across cleanup_rooter() (run(ServicePaths.iptables, ...) without CAPE-rooter comment).
  • Test & lint execution (tests/test_rooter_socks5.py): pytest (3 passed) and ruff check (All checks passed!) pass on 6788c02133c19f5346c4a86a540dc94bab66c54a.

Comment thread utils/rooter.py Outdated
_iptables_delete_all("-w", "5", "-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "ACCEPT")
run_iptables("-w", "5", "-t", "raw", "-A", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "ACCEPT")
_iptables_delete_all("-w", "5", "-D", "FORWARD", "--source", ipaddr, "-j", "DROP")
run_iptables("-w", "5", "-I", "FORWARD", "1", "--source", ipaddr, "-j", "DROP")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] socks5_enable silently fails open if iptables -w 5 fails or times out

Trigger & Impact:
run() (utils/rooter.py:57-58) invokes subprocess.run(..., check=False) and returns (p.stdout, p.stderr) without checking p.returncode. socks5_enable ignores the return values of run_iptables("-w", "5", "-t", "raw", "-A", "CAPE_TOR_CLIENTS", ...) (line 1127) and run_iptables("-w", "5", "-I", "FORWARD", "1", "--source", ipaddr, "-j", "DROP") (line 1129). If iptables -w 5 times out on the xtables lock (exit code 4) or errors, socks5_enable still returns None (exception=None in the rooter response at line 1470), so AnalysisManager starts the Tor/SOCKS5 VM without FORWARD DROP—failing open to UDP/QUIC/ICMP egress leaks.

Additionally, passing "-w", "5" to _iptables_delete_all (lines 1126, 1128, 1162, 1163) interacts badly with if err: break at utils/rooter.py:717: under xtables lock contention or 5s timeout, iptables prints a lock notice to stderr, causing _iptables_delete_all to break immediately (deleting 0 rules on timeout or only 1 duplicate on wait) and leaving FORWARD DROP or CAPE_TOR_CLIENTS ACCEPT stuck on the VM IP for future tasks.

Suggested Fix:
Raise RuntimeError if adding CAPE_TOR_CLIENTS or FORWARD 1 DROP fails (and update _iptables_delete_all / a helper checking returncode so lock-wait stderr does not abort deletion or mask a non-zero exit):

    _, err = run_iptables("-w", "5", "-t", "raw", "-A", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "ACCEPT")
    if err and "waiting" not in err.lower():
        raise RuntimeError(f"Failed to add CAPE_TOR_CLIENTS rule for {ipaddr}: {err.strip()}")
    _, err = run_iptables("-w", "5", "-I", "FORWARD", "1", "--source", ipaddr, "-j", "DROP")
    if err and "waiting" not in err.lower():
        raise RuntimeError(f"Failed to add FORWARD DROP rule for {ipaddr}: {err.strip()}")

(Ideally track returncode in a helper like run_status() so a "Stopped waiting after 5s" rc=4 timeout is unambiguously distinguished from a transient "still waiting" rc=0 notice. Remember to keep VirusTotal/vt-cape#923 CAPE/Server/patch_capev2_tor.py in sync.)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in commit 8c6b435: added run_status(), run_iptables_status(), and _iptables_delete_all_status() in utils/rooter.py to inspect returncode directly so transient -w 5 lock-wait stderr (rc == 0) does not abort duplicate deletion while lock timeouts (rc == 4) and rule errors raise RuntimeError in socks5_enable / socks5_disable. Synced VirusTotal/vt-cape#923 CAPE/Server/patch_capev2_tor.py (commit 6694a1d) to produce byte-identical output.

Comment thread utils/rooter.py
log.info("Disabling socks route.")
_iptables_delete_all("-w", "5", "-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "ACCEPT")
_iptables_delete_all("-w", "5", "-D", "FORWARD", "--source", ipaddr, "-j", "DROP")
run("conntrack", "-D", "-s", ipaddr)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Flush conntrack after deleting nat PREROUTING REDIRECT rules in socks5_disable

Trigger & Impact:
In AnalysisManager.perform_analysis() (lib/cuckoo/core/analysis_manager.py:463), network_routing().__exit__ invokes socks5_disable() before machine_running().__exit__ calls stop_machine(). Flushing run("conntrack", "-D", "-s", ipaddr) at line 1164 while the VM is still running and before the nat PREROUTING REDIRECT rules (lines 1165-1190) are removed leaves a race window where guest packets can recreate Tor-redirected conntrack entries during teardown.

Suggested Fix:
Move run("conntrack", "-D", "-s", ipaddr) to the end of socks5_disable (after line 1191) so no new Tor REDIRECT flows can be tracked after the flush.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in commit 8c6b435: moved run("conntrack", "-D", "-s", ipaddr) to the end of socks5_disable() after deleting the nat PREROUTING REDIRECT and OUTPUT rules.

Comment thread tests/test_rooter_socks5.py Outdated

monkeypatch.setattr(rooter.ServicePaths, "iptables", "iptables", raising=False)
monkeypatch.setattr(rooter, "run", fake_run)
monkeypatch.setattr(rooter, "run_iptables", fake_run_iptables)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] Mock rooter.run instead of rooter.run_iptables and assert socks5_enable duplicate deletion, ordering, and -w 5 lock handling

Trigger & Impact:

  1. Monkeypatching rooter.run_iptables directly (line 25) bypasses run_iptables() (utils/rooter.py:126-135), so the tests never verify that per-VM rules receive -m comment --comment CAPE-rooter (required by cleanup_rooter() at line 164).
  2. Recording run and run_iptables in separate lists (calls["run"] vs calls["iptables"]) cannot catch ordering regressions (e.g. conntrack -D or -N CAPE_TOR_CLIENTS running after -A CAPE_TOR_CLIENTS or -D in socks5_disable).
  3. test_socks5_enable_installs_forward_drop_and_tor_client_accept (lines 40-45) never asserts rec["delete_counts"][tor_del] == 3 / rec["delete_counts"][fwd_del] == 3, and neither test covers -w 5 xtables lock-wait/timeout stderr or existing/missing CAPE_TOR_CLIENTS chain responses.

Suggested Fix:
Mock rooter.run in a single ordered list so run_iptables executes for real, assert -m comment --comment CAPE-rooter on run_iptables-emitted args, assert cross-call ordering and delete_counts == 3 in socks5_enable, and add cases for -w 5 lock-wait/timeout stderr and Chain already exists / No chain.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in commit 8c6b435: updated tests/test_rooter_socks5.py to mock rooter.subprocess.run in a single ordered rec["cmds"] list so run_iptables / run_iptables_status execute for real (verifying -m comment --comment CAPE-rooter), assert cross-call ordering and delete_counts == 3 in both socks5_enable and socks5_disable, and cover -w 5 lock-wait stderr (rc=0), lock timeouts (rc=4), Chain already exists, and No chain.

@karlhiramoto
karlhiramoto requested a review from dsecuma November 18, 2026 15:02

@dsecuma dsecuma left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary: Changes Requested ❌

Reviewed VirusTotal/CAPEv2#102 (fix/socks5-tor-forward-drop, commit 8c6b435f629442be61df8d3b0ae9e317c051d606).

All 3 prior findings from 6788c02 (run_status / _iptables_delete_all_status fail-closed -w 5 handling, conntrack -D -s moved to the end of socks5_disable(), and tests/test_rooter_socks5.py subprocess.run mocking with ordering and lock-wait coverage) are cleanly fixed. However, 3 substantive reliability and code-hygiene issues remain:

Blocking / Actionable Findings

  1. [HIGH] socks5_disable aborts remaining teardown on the first _iptables_delete_all_status failure (utils/rooter.py:1195): If _iptables_delete_all_status for CAPE_TOR_CLIENTS (line 1195) or FORWARD (line 1196) raises RuntimeError (e.g. an xtables lock timeout), socks5_disable() exits before removing FORWARD 1 DROP, nat PREROUTING TCP/DNS REDIRECT, OUTPUT DROP, or flushing conntrack -D -s, leaving subsequent non-Tor tasks on that VM IP blackholed or hijacked to Tor.
  2. [HIGH] socks5_enable adds CAPE_TOR_CLIENTS before FORWARD 1 DROP without rollback, and nat PREROUTING REDIRECT lacks -w 5 / error checks (utils/rooter.py:1156): If FORWARD 1 DROP setup (lines 1159-1162) raises RuntimeError, <ipaddr> stays authorized in CAPE_TOR_CLIENTS (__exit__ never runs). Additionally, the subsequent nat PREROUTING REDIRECT calls (lines 1163-1189) omit "-w", "5" and discard returncode; under xtables lock contention, a failed REDIRECT leaves guest TCP/DNS traffic silently blackholed behind the newly installed FORWARD 1 DROP.
  3. [MEDIUM] Modified _iptables_delete_all lock check spins 32x on non--w callers and duplicates _iptables_delete_all_status (utils/rooter.py:731): nexthop_enable / nexthop_disable call _iptables_delete_all without -w; immediate lock errors ("Perhaps you want to use the -w option?") contain "xtables lock" without "stopped waiting", causing all 32 iterations to spin unnecessarily (and line 731 is untested).

Verification Summary (Passing Checks)

  • CAPE_TOR_CLIENTS & cleanup_rooter() lifecycle (utils/rooter.py:1152-1162, tests/test_rooter_socks5.py:185-211): -N CAPE_TOR_CLIENTS uses run_status (preserving the chain across cleanup_rooter()), while per-VM rules use run_iptables_status (-m comment --comment CAPE-rooter) with -j ACCEPT so Tor .onion (10.192.0.0/10) TCP proceeds to nat PREROUTING REDIRECT.
  • Sync with VirusTotal/vt-cape#923 (6694a1d): Verified utils/rooter.py matches CAPE/Server/patch_capev2_tor.py byte-for-byte.
  • Tests: pytest tests/test_rooter_socks5.py (11 passed in isolated environment).

Comment thread utils/rooter.py Outdated
def socks5_disable(ipaddr, resultserver_port, dns_port, proxy_port):
"""Enable hijacking of all traffic and send it to socks5."""
log.info("Disabling socks route.")
_iptables_delete_all_status("-w", "5", "-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "ACCEPT")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] socks5_disable aborts remaining teardown on first _iptables_delete_all_status error

Trigger & Impact:
If _iptables_delete_all_status at utils/rooter.py:1195 (CAPE_TOR_CLIENTS) or 1196 (FORWARD) hits an xtables lock timeout (rc=4) or error and raises RuntimeError, socks5_disable() unwinds immediately—skipping FORWARD DROP deletion (1196), nat PREROUTING TCP/DNS REDIRECT and OUTPUT deletions (1197-1223), and conntrack -D -s (1224). Subsequent non-Tor tasks reusing <ipaddr> inherit active FORWARD 1 DROP, nat PREROUTING REDIRECT, and stale conntrack state.

Suggested Fix:
Run all teardown steps and re-raise the first RuntimeError after cleanup completes (keeping VirusTotal/vt-cape#923 CAPE/Server/patch_capev2_tor.py in sync):

    errors = []
    for del_args in (
        ("-w", "5", "-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "ACCEPT"),
        ("-w", "5", "-D", "FORWARD", "--source", ipaddr, "-j", "DROP"),
    ):
        try:
            _iptables_delete_all_status(*del_args)
        except RuntimeError as e:
            errors.append(e)
    ...
    run("conntrack", "-D", "-s", ipaddr)
    if errors:
        raise errors[0]

@karlhiramoto karlhiramoto Nov 18, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in commit c9dbd4f: updated socks5_disable() in utils/rooter.py to run all teardown steps—_iptables_delete_all_status for CAPE_TOR_CLIENTS and FORWARD, run_iptables_status("-w", "5", ...) for all nat PREROUTING and OUTPUT rules (ignoring missing-rule errors while recording lock timeouts/errors), and conntrack -D -s—before re-raising the first RuntimeError. Added unit tests in tests/test_rooter_socks5.py covering CAPE_TOR_CLIENTS, FORWARD, and nat PREROUTING REDIRECT lock timeouts as well as missing nat rule tolerance. (VirusTotal/vt-cape#923 CAPE/Server/patch_capev2_tor.py should be kept in sync.)

Comment thread utils/rooter.py Outdated
if rc != 0 and "chain already exists" not in (err or "").lower():
raise RuntimeError(f"Failed to ensure CAPE_TOR_CLIENTS chain: {err.strip() or f'exit {rc}'}")
_iptables_delete_all_status("-w", "5", "-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "ACCEPT")
rc, _, err = run_iptables_status("-w", "5", "-t", "raw", "-A", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "ACCEPT")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] socks5_enable adds CAPE_TOR_CLIENTS before FORWARD 1 DROP without rollback, and nat REDIRECT lacks -w 5 / error checks

Trigger & Impact:

  1. CAPE_TOR_CLIENTS -A (utils/rooter.py:1156) runs before FORWARD 1 DROP (lines 1159-1162). If FORWARD deletion or insertion fails and raises RuntimeError, AnalysisManager.network_routing().__enter__ aborts without calling socks5_disable(), leaving <ipaddr> authorized in CAPE_TOR_CLIENTS.
  2. nat PREROUTING REDIRECT calls (lines 1163-1188) still use run_iptables without "-w", "5" or returncode checks. With FORWARD 1 DROP newly installed at 1160, a lock-contended REDIRECT failure silently returns None (exception=None) and blackholes guest TCP/DNS behind FORWARD 1 DROP.

Suggested Fix:
Install FORWARD 1 DROP first (fail-closed ordering), use run_iptables_status("-w", "5", ...) on nat PREROUTING REDIRECT / OUTPUT rules, and roll back installed rules if any step fails:

    _iptables_delete_all_status("-w", "5", "-D", "FORWARD", "--source", ipaddr, "-j", "DROP")
    rc, _, err = run_iptables_status("-w", "5", "-I", "FORWARD", "1", "--source", ipaddr, "-j", "DROP")
    if rc != 0:
        raise RuntimeError(f"Failed to add FORWARD DROP rule for {ipaddr}: {err.strip() or f'exit {rc}'}")
    try:
        rc, _, err = run_iptables_status("-w", "5", "-t", "raw", "-A", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "ACCEPT")
        if rc != 0:
            raise RuntimeError(f"Failed to add CAPE_TOR_CLIENTS rule for {ipaddr}: {err.strip() or f'exit {rc}'}")
        for nat_args in (...):
            rc, _, err = run_iptables_status("-w", "5", *nat_args)
            if rc != 0:
                raise RuntimeError(f"Failed to add socks5 rule for {ipaddr}: {err.strip() or f'exit {rc}'}")
    except Exception:
        run_iptables("-w", "5", "-D", "FORWARD", "--source", ipaddr, "-j", "DROP")
        run_iptables("-w", "5", "-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", ipaddr, "-p", "tcp", "-j", "ACCEPT")
        raise

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in commit c9dbd4f: reordered socks5_enable() in utils/rooter.py to install FORWARD 1 DROP first (fail-closed), shared the nat PREROUTING / OUTPUT rule definitions via _socks5_nat_and_output_rules(), switched all nat PREROUTING and OUTPUT installations to run_iptables_status("-w", "5", ...) with returncode checks, and added reverse-order rollback of all installed rules (FORWARD, CAPE_TOR_CLIENTS, and any partial nat/OUTPUT rules) if any step fails. Updated tests/test_rooter_socks5.py to assert the fail-closed ordering, -w 5 flags, and rollback across all failure points.

Comment thread utils/rooter.py Outdated
for _ in range(32):
_, err = run_iptables(*args)
if err:
if err and not ("xtables lock" in err.lower() and "stopped waiting" not in err.lower()):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] _iptables_delete_all lock check spins 32x on non--w callers and duplicates _iptables_delete_all_status

Trigger & Impact:
nexthop_enable (lines 761, 770) and nexthop_disable (lines 778, 779) call _iptables_delete_all without -w. When another process holds the xtables lock, iptables exits immediately (rc=4) with "Another app is currently holding the xtables lock. Perhaps you want to use the -w option?". Line 731 ("xtables lock" in err.lower() and "stopped waiting" not in err.lower()) evaluates to True, causing all 32 iterations to spin unnecessarily. This modified branch also has zero test coverage in tests/test_rooter_socks5.py (alongside run_status OSError and socks5_disable CAPE_TOR_CLIENTS timeout).

Suggested Fix:
Delegate _iptables_delete_all to _iptables_delete_all_status while preserving best-effort behavior for nexthop_*:

def _iptables_delete_all(*args):
    """Best-effort delete an iptables rule until it is no longer present."""
    try:
        _iptables_delete_all_status(*args)
    except RuntimeError as e:
        log.warning("Best-effort iptables delete failed: %s", e)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in commit c9dbd4f: refactored _iptables_delete_all() in utils/rooter.py to delegate to _iptables_delete_all_status() (catching RuntimeError and logging a warning so nexthop_* remains best-effort while avoiding the 32x spin on non--w xtables lock errors and preserving compatibility with tests/test_rooter_nexthop.py's run_iptables monkeypatch). Added unit tests in tests/test_rooter_socks5.py for non--w xtables lock handling in _iptables_delete_all, stacked duplicate deletion, and run_status() OSError handling.

…_enable

- Install a per-VM FORWARD 1 DROP rule in socks5_enable (with automatic
  rollback if subsequent rule setup fails) so non-TCP guest traffic such as
  QUIC/UDP and ICMP cannot bypass Tor/SOCKS5 when bridge forwarding and host
  NAT masquerading are enabled.
- Register active Tor/SOCKS5 guest IPs in raw chain CAPE_TOR_CLIENTS (-j ACCEPT)
  so host raw PREROUTING RFC1918 guards can exempt Tor VirtualAddrNetwork
  (10.192.0.0/10) traffic per-VM while preserving the chain across
  cleanup_rooter().
- Pass -w 5 and check exit codes via run_status / run_iptables_status /
  _iptables_delete_all_status across socks5_enable and socks5_disable, run all
  teardown steps before re-raising on error, and flush per-VM conntrack state.
@karlhiramoto
karlhiramoto force-pushed the fix/socks5-tor-forward-drop branch from c9dbd4f to 7c5ce86 Compare November 18, 2026 16:32
@karlhiramoto

Copy link
Copy Markdown
Member Author

Closing fork PR in favor of upstream PR kevoreilly#3448.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants