Repository navigation
rooter: drop non-redirected FORWARD traffic and track active Tor clients in socks5_enable - #102
karlhiramoto wants to merge 1 commit into
Conversation
gracehopper-vt
left a comment
There was a problem hiding this comment.
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
FORWARDdrop is the correct fix for the QUIC/UDP/ICMP leak. Traffic redirected to the ResultServer,DNSPortandTransPortgoes throughINPUT, so it isn't affected. Inserting at position 1 puts the drop ahead of theESTABLISHED,RELATEDaccept, and it's idempotent through_iptables_delete_all. - Cleanup: everything except the
-Ngoes throughrun_iptables, so it carries theCAPE-rootercomment, andcleanup_rooter()filters those out ofiptables-savefor every table, includingraw. The add and delete argument lists match exactly. tests/test_rooter_socks5.py: 2 passed locally (a minimal tree withutils/rooter.py,path_utilsandconstantsfrom 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.
| 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") |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Review Summary: Changes Requested ❌
Reviewed VirusTotal/CAPEv2#102 (fix/socks5-tor-forward-drop, commit 4d0b3031b392da320189914f20020e97f3a2e1f3).
Blocking / Actionable Findings
- [CRITICAL]
CAPE_TOR_CLIENTSuses-j RETURNinstead of-j ACCEPT, dropping Tor.oniontraffic inVT_GUEST_FWD(utils/rooter.py:1126): WhenVT_GUEST_FWD(raw PREROUTINGincustom_firewall.sh) jumps toCAPE_TOR_CLIENTSfor Tor'sVirtualAddrNetwork(10.192.0.0/10), evaluating-j RETURNinCAPE_TOR_CLIENTSresumes traversal inVT_GUEST_FWDat the very next rule (-d 10.0.0.0/8 -j DROP), causing Tor.onionTCP connections to be unconditionally dropped. Must use-j ACCEPTinsocks5_enable(L1125, L1126) andsocks5_disable(L1161). - [HIGH] Unit test asserts flawed
-j RETURNrule (tests/test_rooter_socks5.py:29,tests/test_rooter_socks5.py:40): Unit tests currently assert that-j RETURNis passed toiptables. 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 DROPinsocks5_enable(and clearing via_iptables_delete_allinsocks5_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 onINPUT(ResultServer on2042, Tor DNS on5354, Tor TransPort on9040). - Idempotency & rule cleanup (
utils/rooter.py):_iptables_delete_allcorrectly purges matching rules prior to insertion and upon disable. - Chain creation (
utils/rooter.py): Directly invokingrun(ServicePaths.iptables, "-t", "raw", "-N", "CAPE_TOR_CLIENTS")is correct becauseiptables -Ncreates a chain and does not accept match extensions (unlikerun_iptableswhich appends-m comment).
| 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") |
There was a problem hiding this comment.
[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
doneIn 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)
There was a problem hiding this comment.
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>).
There was a problem hiding this comment.
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).
| 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"] |
There was a problem hiding this comment.
[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)
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
gracehopper-vt
left a comment
There was a problem hiding this comment.
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 withutils/rooter.py,path_utilsandconstantsfrom this head. That includes the newcleanup_rooter()test, which checks that:CAPE_TOR_CLIENTSand theVT_GUEST_FWDjump survive theiptables-savefiltering while the tagged per-VM rule is removed.- The injected
socks5_enable/socks5_disableblocks are byte-identical to_ENABLE_REPLACEMENT/_DISABLE_REPLACEMENTin VirusTotal/vt-cape#923 atbc3bfc7, sopatch_capev2_tor.pyis a no-op on this rooter and the two PRs stay in sync. - Creating the chain with
run(...)instead ofrun_iptablesis correct:-Nrejects the appended-m comment, and leaving the chain untagged keeps it acrosscleanup_rooter().
LGTM. Two small notes:
_iptables_delete_allstops looping at the first non-empty stderr. With-w 5, iptables can printAnother 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.)run("conntrack", ...)needs theconntrackCLI on the host.run()swallows the error if it's missing, so the flush would silently not happen. Samewhich conntrackcheck oncape-base-templateas for kevoreilly#923.
dsecuma
left a comment
There was a problem hiding this comment.
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
- [HIGH]
socks5_enablefails open oniptables -w 5timeout / error and_iptables_delete_allaborts on lock stderr (utils/rooter.py:1126-1129,utils/rooter.py:715-718):run()(utils/rooter.py:57-58) usescheck=Falseand discardsreturncode, andsocks5_enableignores allrun_iptablesreturn values. Ifiptables -w 5 -I FORWARD 1 --source <ipaddr> -j DROPfails or times out on the xtables lock,socks5_enablereturnsNone(exception=None) andAnalysisManagerlaunches the malware VM withoutFORWARD DROP(failing open to UDP/QUIC/ICMP egress leaks). Additionally,_iptables_delete_all(utils/rooter.py:717) stops on any non-emptystderr, so an xtables lock-wait/timeout stderr line on-w 5exits with0deletions—leavingFORWARD DROPorCAPE_TOR_CLIENTS ACCEPTstuck on that VM IP for subsequent tasks. - [HIGH]
tests/test_rooter_socks5.pybypassesrun_iptablesand omits lock/duplicate/ordering assertions (tests/test_rooter_socks5.py:25,tests/test_rooter_socks5.py:40-45): Monkeypatchingrooter.run_iptablesdirectly skips-m comment --comment CAPE-rooterattachment (breaking end-to-end verification withcleanup_rooter()), splittingcalls["run"]andcalls["iptables"]prevents cross-call ordering assertions,delete_counts == 3is not asserted insocks5_enable, and-w 5lock-wait/timeout stderr paths are untested. - [MEDIUM]
conntrack -D -s ipaddrruns beforenat PREROUTINGREDIRECTrules are deleted insocks5_disable(utils/rooter.py:1164): BecauseAnalysisManager.network_routing()callssocks5_disable()while the VM is still running (stop_machine()runs later inmachine_running().__exit__), flushingconntrackbefore removingnat PREROUTINGREDIRECTrules (1165-1190) lets packets from the still-running VM recreate Tor conntrack entries during teardown.
Verification Summary (Passing Checks)
- Tor
VirtualAddrNetworkacceptance (utils/rooter.py:1125-1127, 1162): Verified-j ACCEPTis used insocks5_enableand both_iptables_delete_allcalls, exitingraw PREROUTINGintoconntrack+nat PREROUTINGREDIRECTwhile preserving:CAPE_TOR_CLIENTSacrosscleanup_rooter()(run(ServicePaths.iptables, ...)withoutCAPE-rootercomment). - Test & lint execution (
tests/test_rooter_socks5.py):pytest(3 passed) andruff check(All checks passed!) pass on6788c02133c19f5346c4a86a540dc94bab66c54a.
| _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") |
There was a problem hiding this comment.
[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.)
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
|
|
||
| monkeypatch.setattr(rooter.ServicePaths, "iptables", "iptables", raising=False) | ||
| monkeypatch.setattr(rooter, "run", fake_run) | ||
| monkeypatch.setattr(rooter, "run_iptables", fake_run_iptables) |
There was a problem hiding this comment.
[HIGH] Mock rooter.run instead of rooter.run_iptables and assert socks5_enable duplicate deletion, ordering, and -w 5 lock handling
Trigger & Impact:
- Monkeypatching
rooter.run_iptablesdirectly (line 25) bypassesrun_iptables()(utils/rooter.py:126-135), so the tests never verify that per-VM rules receive-m comment --comment CAPE-rooter(required bycleanup_rooter()atline 164). - Recording
runandrun_iptablesin separate lists (calls["run"]vscalls["iptables"]) cannot catch ordering regressions (e.g.conntrack -Dor-N CAPE_TOR_CLIENTSrunning after-A CAPE_TOR_CLIENTSor-Dinsocks5_disable). test_socks5_enable_installs_forward_drop_and_tor_client_accept(lines 40-45) never assertsrec["delete_counts"][tor_del] == 3/rec["delete_counts"][fwd_del] == 3, and neither test covers-w 5xtables lock-wait/timeoutstderror existing/missingCAPE_TOR_CLIENTSchain 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.
There was a problem hiding this comment.
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.
dsecuma
left a comment
There was a problem hiding this comment.
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
- [HIGH]
socks5_disableaborts remaining teardown on the first_iptables_delete_all_statusfailure (utils/rooter.py:1195): If_iptables_delete_all_statusforCAPE_TOR_CLIENTS(line 1195) orFORWARD(line 1196) raisesRuntimeError(e.g. an xtables lock timeout),socks5_disable()exits before removingFORWARD 1 DROP,nat PREROUTINGTCP/DNSREDIRECT,OUTPUT DROP, or flushingconntrack -D -s, leaving subsequent non-Tor tasks on that VM IP blackholed or hijacked to Tor. - [HIGH]
socks5_enableaddsCAPE_TOR_CLIENTSbeforeFORWARD 1 DROPwithout rollback, andnat PREROUTING REDIRECTlacks-w 5/ error checks (utils/rooter.py:1156): IfFORWARD 1 DROPsetup (lines 1159-1162) raisesRuntimeError,<ipaddr>stays authorized inCAPE_TOR_CLIENTS(__exit__never runs). Additionally, the subsequentnat PREROUTING REDIRECTcalls (lines 1163-1189) omit"-w", "5"and discardreturncode; under xtables lock contention, a failedREDIRECTleaves guest TCP/DNS traffic silently blackholed behind the newly installedFORWARD 1 DROP. - [MEDIUM] Modified
_iptables_delete_alllock check spins 32x on non--wcallers and duplicates_iptables_delete_all_status(utils/rooter.py:731):nexthop_enable/nexthop_disablecall_iptables_delete_allwithout-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 line731is 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_CLIENTSusesrun_status(preserving the chain acrosscleanup_rooter()), while per-VM rules userun_iptables_status(-m comment --comment CAPE-rooter) with-j ACCEPTso Tor.onion(10.192.0.0/10) TCP proceeds tonat PREROUTING REDIRECT.- Sync with
VirusTotal/vt-cape#923(6694a1d): Verifiedutils/rooter.pymatchesCAPE/Server/patch_capev2_tor.pybyte-for-byte. - Tests:
pytest tests/test_rooter_socks5.py(11 passedin isolated environment).
| 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") |
There was a problem hiding this comment.
[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]There was a problem hiding this comment.
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.)
| 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") |
There was a problem hiding this comment.
[HIGH] socks5_enable adds CAPE_TOR_CLIENTS before FORWARD 1 DROP without rollback, and nat REDIRECT lacks -w 5 / error checks
Trigger & Impact:
CAPE_TOR_CLIENTS -A(utils/rooter.py:1156) runs beforeFORWARD 1 DROP(lines 1159-1162). IfFORWARDdeletion or insertion fails and raisesRuntimeError,AnalysisManager.network_routing().__enter__aborts without callingsocks5_disable(), leaving<ipaddr>authorized inCAPE_TOR_CLIENTS.nat PREROUTINGREDIRECTcalls (lines 1163-1188) still userun_iptableswithout"-w", "5"orreturncodechecks. WithFORWARD 1 DROPnewly installed at1160, a lock-contendedREDIRECTfailure silently returnsNone(exception=None) and blackholes guest TCP/DNS behindFORWARD 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")
raiseThere was a problem hiding this comment.
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.
| 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()): |
There was a problem hiding this comment.
[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)There was a problem hiding this comment.
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.
c9dbd4f to
7c5ce86
Compare
|
Closing fork PR in favor of upstream PR kevoreilly#3448. |
Summary
Fixes packet-filtering and connection-tracking gaps in
socks5_enable/socks5_disable(utils/rooter.py) used for Tor and SOCKS5 transparent proxy routing:FORWARDchain):socks5_enablepreviously appended-A OUTPUT --source <ipaddr> -j DROP. Because bridged/routed guest VM packets that are not redirected to a local proxy/DNS port traverseFORWARD(notOUTPUT), non-TCP traffic (such as browser HTTP/3 QUIC overUDP/443orICMP) could bypass Tor/SOCKS5 when bridge forwarding (libvirt_fwo_enable) and host NAT masquerading are enabled.-w 5 -I FORWARD 1 --source <ipaddr> -j DROPinsocks5_enableand removes all matching entries via_iptables_delete_allinsocks5_disable. Guest traffic redirected to localResultServer,DNSPort, andTransPort/SOCKSport traversesINPUTand continues to work normally.rawchainCAPE_TOR_CLIENTS:rawchainCAPE_TOR_CLIENTS(iptables -w 5 -t raw -N CAPE_TOR_CLIENTS) and registers--source <ipaddr> -p tcp -j ACCEPTwhilesocks5_enableis active (cleaned up insocks5_disableand oncleanup_rooter()). Using-j ACCEPTinrawexitsraw PREROUTINGtraversal (passing packets into conntrack andnat PREROUTINGREDIRECT --to-ports <proxy_port>) even when jumped to from a nestedrawRFC1918 guard subchain, allowing TorVirtualAddrNetwork(e.g.10.192.0.0/10for.onionAutomapHostsOnResolve) strictly for active Tor/SOCKS5 VMs.conntrack -D -s <ipaddr>):socks5_enableandsocks5_disable(matchingnexthop_enable/nexthop_disable) so recycled snapshot VM IPs cannot reuse prior NAT/UDP state across tasks.Testing
tests/test_rooter_socks5.pyverifyingsocks5_enable,socks5_disable, duplicate rule cleanup,conntrackflushing, andcleanup_rooter()preservation of:CAPE_TOR_CLIENTS.