|
| 1 | +import subprocess |
| 2 | +import pytest |
| 3 | +import utils.rooter as rooter |
| 4 | + |
| 5 | +_CAPE_COMMENT = ("-m", "comment", "--comment", "CAPE-rooter") |
| 6 | + |
| 7 | + |
| 8 | +@pytest.fixture |
| 9 | +def rec(monkeypatch): |
| 10 | + state = { |
| 11 | + "cmds": [], |
| 12 | + "delete_counts": {}, |
| 13 | + "lock_wait_once": set(), |
| 14 | + "chain_exists": False, |
| 15 | + "missing_chain": False, |
| 16 | + "fail_match": None, |
| 17 | + } |
| 18 | + |
| 19 | + def fake_subprocess_run(args, capture_output=True, text=True, check=False): |
| 20 | + tup = tuple(str(a) for a in args) |
| 21 | + state["cmds"].append(tup) |
| 22 | + |
| 23 | + if state["fail_match"] and state["fail_match"](tup): |
| 24 | + err_msg = ( |
| 25 | + "Another app is currently holding the xtables lock. Stopped waiting after 5s.\n" |
| 26 | + if "-w" in tup |
| 27 | + else "Another app is currently holding the xtables lock. Perhaps you want to use the -w option?\n" |
| 28 | + ) |
| 29 | + return subprocess.CompletedProcess(tup, 4, "", err_msg) |
| 30 | + |
| 31 | + if "-N" in tup and "CAPE_TOR_CLIENTS" in tup and state["chain_exists"]: |
| 32 | + return subprocess.CompletedProcess(tup, 1, "", "iptables: Chain already exists.\n") |
| 33 | + |
| 34 | + if "-D" in tup and tup[0] == "iptables": |
| 35 | + count = state["delete_counts"].get(tup, 0) |
| 36 | + state["delete_counts"][tup] = count + 1 |
| 37 | + if state["missing_chain"] and "CAPE_TOR_CLIENTS" in tup: |
| 38 | + return subprocess.CompletedProcess(tup, 1, "", "iptables: No chain/target/match by that name.\n") |
| 39 | + if state.get("missing_nat_rule") and "nat" in tup: |
| 40 | + return subprocess.CompletedProcess( |
| 41 | + tup, |
| 42 | + 1, |
| 43 | + "", |
| 44 | + "iptables: Bad rule (does a matching rule exist in that chain?).\n", |
| 45 | + ) |
| 46 | + if count == 0 and any(tok in state["lock_wait_once"] for tok in tup): |
| 47 | + return subprocess.CompletedProcess( |
| 48 | + tup, |
| 49 | + 0, |
| 50 | + "", |
| 51 | + "Another app is currently holding the xtables lock; still 4s left...\n", |
| 52 | + ) |
| 53 | + if count >= 2: |
| 54 | + return subprocess.CompletedProcess( |
| 55 | + tup, |
| 56 | + 1, |
| 57 | + "", |
| 58 | + "iptables: Bad rule (does a matching rule exist in that chain?).\n", |
| 59 | + ) |
| 60 | + |
| 61 | + if any(tok in state["lock_wait_once"] for tok in tup): |
| 62 | + return subprocess.CompletedProcess( |
| 63 | + tup, |
| 64 | + 0, |
| 65 | + "", |
| 66 | + "Another app is currently holding the xtables lock; still 4s left...\n", |
| 67 | + ) |
| 68 | + |
| 69 | + return subprocess.CompletedProcess(tup, 0, "", "") |
| 70 | + |
| 71 | + monkeypatch.setattr(rooter.ServicePaths, "iptables", "iptables", raising=False) |
| 72 | + monkeypatch.setattr(rooter.subprocess, "run", fake_subprocess_run) |
| 73 | + return state |
| 74 | + |
| 75 | + |
| 76 | +def test_socks5_enable_installs_forward_drop_and_tor_client_accept(rec): |
| 77 | + rooter.socks5_enable("172.16.1.4", "2042", "5354", "9040") |
| 78 | + |
| 79 | + conntrack_cmd = ("conntrack", "-D", "-s", "172.16.1.4") |
| 80 | + chain_new_cmd = ("iptables", "-w", "5", "-t", "raw", "-N", "CAPE_TOR_CLIENTS") |
| 81 | + tor_del = ("iptables", "-w", "5", "-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", "172.16.1.4", "-p", "tcp", "-j", "ACCEPT", *_CAPE_COMMENT) |
| 82 | + tor_add = ("iptables", "-w", "5", "-t", "raw", "-A", "CAPE_TOR_CLIENTS", "--source", "172.16.1.4", "-p", "tcp", "-j", "ACCEPT", *_CAPE_COMMENT) |
| 83 | + fwd_del = ("iptables", "-w", "5", "-D", "FORWARD", "--source", "172.16.1.4", "-j", "DROP", *_CAPE_COMMENT) |
| 84 | + fwd_add = ("iptables", "-w", "5", "-I", "FORWARD", "1", "--source", "172.16.1.4", "-j", "DROP", *_CAPE_COMMENT) |
| 85 | + nat_redir = ( |
| 86 | + "iptables", |
| 87 | + "-w", |
| 88 | + "5", |
| 89 | + "-t", |
| 90 | + "nat", |
| 91 | + "-I", |
| 92 | + "PREROUTING", |
| 93 | + "--source", |
| 94 | + "172.16.1.4", |
| 95 | + "-p", |
| 96 | + "tcp", |
| 97 | + "--syn", |
| 98 | + "!", |
| 99 | + "--dport", |
| 100 | + "2042", |
| 101 | + "-j", |
| 102 | + "REDIRECT", |
| 103 | + "--to-ports", |
| 104 | + "9040", |
| 105 | + *_CAPE_COMMENT, |
| 106 | + ) |
| 107 | + nat_dns_udp = ( |
| 108 | + "iptables", |
| 109 | + "-w", |
| 110 | + "5", |
| 111 | + "-t", |
| 112 | + "nat", |
| 113 | + "-A", |
| 114 | + "PREROUTING", |
| 115 | + "-p", |
| 116 | + "udp", |
| 117 | + "--dport", |
| 118 | + "53", |
| 119 | + "--source", |
| 120 | + "172.16.1.4", |
| 121 | + "-j", |
| 122 | + "REDIRECT", |
| 123 | + "--to-ports", |
| 124 | + "5354", |
| 125 | + *_CAPE_COMMENT, |
| 126 | + ) |
| 127 | + |
| 128 | + assert conntrack_cmd in rec["cmds"] |
| 129 | + assert chain_new_cmd in rec["cmds"] |
| 130 | + assert rec["delete_counts"][tor_del] == 3 |
| 131 | + assert rec["delete_counts"][fwd_del] == 3 |
| 132 | + assert tor_add in rec["cmds"] |
| 133 | + assert fwd_add in rec["cmds"] |
| 134 | + assert nat_redir in rec["cmds"] |
| 135 | + assert nat_dns_udp in rec["cmds"] |
| 136 | + |
| 137 | + # Cross-call ordering: conntrack flush -> FORWARD DROP (fail-closed) -> CAPE_TOR_CLIENTS -> nat REDIRECT |
| 138 | + assert rec["cmds"].index(conntrack_cmd) < rec["cmds"].index(fwd_del) |
| 139 | + last_fwd_del = max(i for i, cmd in enumerate(rec["cmds"]) if cmd == fwd_del) |
| 140 | + assert last_fwd_del < rec["cmds"].index(fwd_add) |
| 141 | + assert rec["cmds"].index(fwd_add) < rec["cmds"].index(chain_new_cmd) |
| 142 | + assert rec["cmds"].index(chain_new_cmd) < rec["cmds"].index(tor_del) |
| 143 | + last_tor_del = max(i for i, cmd in enumerate(rec["cmds"]) if cmd == tor_del) |
| 144 | + assert last_tor_del < rec["cmds"].index(tor_add) |
| 145 | + assert rec["cmds"].index(tor_add) < rec["cmds"].index(nat_redir) |
| 146 | + |
| 147 | + # Every run_iptables/run_iptables_status call carries CAPE-rooter comment and -w 5; -N does not carry comment. |
| 148 | + for cmd in rec["cmds"]: |
| 149 | + if cmd[0] == "iptables": |
| 150 | + assert cmd[1:3] == ("-w", "5") |
| 151 | + if "-N" not in cmd: |
| 152 | + assert cmd[-4:] == _CAPE_COMMENT |
| 153 | + |
| 154 | + |
| 155 | +def test_socks5_disable_removes_stacked_duplicates_and_flushes_conntrack_last(rec): |
| 156 | + rooter.socks5_disable("172.16.1.4", "2042", "5354", "9040") |
| 157 | + |
| 158 | + tor_del = ("iptables", "-w", "5", "-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", "172.16.1.4", "-p", "tcp", "-j", "ACCEPT", *_CAPE_COMMENT) |
| 159 | + fwd_del = ("iptables", "-w", "5", "-D", "FORWARD", "--source", "172.16.1.4", "-j", "DROP", *_CAPE_COMMENT) |
| 160 | + nat_redir_del = ( |
| 161 | + "iptables", |
| 162 | + "-w", |
| 163 | + "5", |
| 164 | + "-t", |
| 165 | + "nat", |
| 166 | + "-D", |
| 167 | + "PREROUTING", |
| 168 | + "--source", |
| 169 | + "172.16.1.4", |
| 170 | + "-p", |
| 171 | + "tcp", |
| 172 | + "--syn", |
| 173 | + "!", |
| 174 | + "--dport", |
| 175 | + "2042", |
| 176 | + "-j", |
| 177 | + "REDIRECT", |
| 178 | + "--to-ports", |
| 179 | + "9040", |
| 180 | + *_CAPE_COMMENT, |
| 181 | + ) |
| 182 | + conntrack_cmd = ("conntrack", "-D", "-s", "172.16.1.4") |
| 183 | + |
| 184 | + assert rec["delete_counts"][tor_del] == 3 |
| 185 | + assert rec["delete_counts"][fwd_del] == 3 |
| 186 | + assert nat_redir_del in rec["cmds"] |
| 187 | + assert rec["cmds"][-1] == conntrack_cmd |
| 188 | + for cmd in rec["cmds"]: |
| 189 | + if cmd[0] == "iptables": |
| 190 | + assert cmd[1:3] == ("-w", "5") |
| 191 | + assert cmd[-4:] == _CAPE_COMMENT |
| 192 | + |
| 193 | + |
| 194 | +def test_socks5_enable_tolerates_chain_exists_and_lock_wait_stderr(rec): |
| 195 | + rec["chain_exists"] = True |
| 196 | + rec["lock_wait_once"] = {"CAPE_TOR_CLIENTS", "FORWARD"} |
| 197 | + |
| 198 | + rooter.socks5_enable("172.16.1.4", "2042", "5354", "9040") |
| 199 | + |
| 200 | + tor_del = ("iptables", "-w", "5", "-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", "172.16.1.4", "-p", "tcp", "-j", "ACCEPT", *_CAPE_COMMENT) |
| 201 | + fwd_del = ("iptables", "-w", "5", "-D", "FORWARD", "--source", "172.16.1.4", "-j", "DROP", *_CAPE_COMMENT) |
| 202 | + # Transient lock-wait stderr on rc=0 must not abort duplicate deletion loop |
| 203 | + assert rec["delete_counts"][tor_del] == 3 |
| 204 | + assert rec["delete_counts"][fwd_del] == 3 |
| 205 | + |
| 206 | + |
| 207 | +def test_socks5_disable_tolerates_missing_chain_and_missing_nat_rule(rec): |
| 208 | + rec["missing_chain"] = True |
| 209 | + rec["missing_nat_rule"] = True |
| 210 | + rooter.socks5_disable("172.16.1.4", "2042", "5354", "9040") |
| 211 | + |
| 212 | + tor_del = ("iptables", "-w", "5", "-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", "172.16.1.4", "-p", "tcp", "-j", "ACCEPT", *_CAPE_COMMENT) |
| 213 | + fwd_del = ("iptables", "-w", "5", "-D", "FORWARD", "--source", "172.16.1.4", "-j", "DROP", *_CAPE_COMMENT) |
| 214 | + assert rec["delete_counts"][tor_del] == 1 |
| 215 | + assert rec["delete_counts"][fwd_del] == 3 |
| 216 | + assert rec["cmds"][-1] == ("conntrack", "-D", "-s", "172.16.1.4") |
| 217 | + |
| 218 | + |
| 219 | +@pytest.mark.parametrize( |
| 220 | + "label,matcher,expect_tor_attempted,expect_fwd_rollback,expect_tor_rollback,expect_nat_rollback", |
| 221 | + [ |
| 222 | + ("fwd_delete", lambda cmd: "-D" in cmd and "FORWARD" in cmd, False, False, False, False), |
| 223 | + ("fwd_insert", lambda cmd: "-I" in cmd and "FORWARD" in cmd, False, False, False, False), |
| 224 | + ("chain_create", lambda cmd: "-N" in cmd and "CAPE_TOR_CLIENTS" in cmd, False, True, False, False), |
| 225 | + ("tor_delete", lambda cmd: "-D" in cmd and "CAPE_TOR_CLIENTS" in cmd, False, True, False, False), |
| 226 | + ("tor_add", lambda cmd: "-A" in cmd and "CAPE_TOR_CLIENTS" in cmd, True, True, False, False), |
| 227 | + ("nat_tcp_redirect", lambda cmd: "-I" in cmd and "PREROUTING" in cmd and "REDIRECT" in cmd, True, True, True, False), |
| 228 | + ( |
| 229 | + "nat_dns_udp_redirect", |
| 230 | + lambda cmd: "-A" in cmd and "PREROUTING" in cmd and "udp" in cmd and "53" in cmd, |
| 231 | + True, |
| 232 | + True, |
| 233 | + True, |
| 234 | + True, |
| 235 | + ), |
| 236 | + ("output_drop", lambda cmd: "-A" in cmd and "OUTPUT" in cmd and "--source" in cmd, True, True, True, True), |
| 237 | + ], |
| 238 | +) |
| 239 | +def test_socks5_enable_fails_closed_and_rolls_back_on_error( |
| 240 | + rec, label, matcher, expect_tor_attempted, expect_fwd_rollback, expect_tor_rollback, expect_nat_rollback |
| 241 | +): |
| 242 | + rec["fail_match"] = matcher |
| 243 | + with pytest.raises(RuntimeError): |
| 244 | + rooter.socks5_enable("172.16.1.4", "2042", "5354", "9040") |
| 245 | + |
| 246 | + tor_add = ("iptables", "-w", "5", "-t", "raw", "-A", "CAPE_TOR_CLIENTS", "--source", "172.16.1.4", "-p", "tcp", "-j", "ACCEPT", *_CAPE_COMMENT) |
| 247 | + fwd_add = ("iptables", "-w", "5", "-I", "FORWARD", "1", "--source", "172.16.1.4", "-j", "DROP", *_CAPE_COMMENT) |
| 248 | + fwd_del = ("iptables", "-w", "5", "-D", "FORWARD", "--source", "172.16.1.4", "-j", "DROP", *_CAPE_COMMENT) |
| 249 | + tor_del = ("iptables", "-w", "5", "-t", "raw", "-D", "CAPE_TOR_CLIENTS", "--source", "172.16.1.4", "-p", "tcp", "-j", "ACCEPT", *_CAPE_COMMENT) |
| 250 | + nat_redir_del = ( |
| 251 | + "iptables", |
| 252 | + "-w", |
| 253 | + "5", |
| 254 | + "-t", |
| 255 | + "nat", |
| 256 | + "-D", |
| 257 | + "PREROUTING", |
| 258 | + "--source", |
| 259 | + "172.16.1.4", |
| 260 | + "-p", |
| 261 | + "tcp", |
| 262 | + "--syn", |
| 263 | + "!", |
| 264 | + "--dport", |
| 265 | + "2042", |
| 266 | + "-j", |
| 267 | + "REDIRECT", |
| 268 | + "--to-ports", |
| 269 | + "9040", |
| 270 | + *_CAPE_COMMENT, |
| 271 | + ) |
| 272 | + |
| 273 | + assert (tor_add in rec["cmds"]) is expect_tor_attempted |
| 274 | + if expect_fwd_rollback: |
| 275 | + fwd_add_idx = rec["cmds"].index(fwd_add) |
| 276 | + assert fwd_del in rec["cmds"][fwd_add_idx + 1 :] |
| 277 | + if expect_tor_rollback: |
| 278 | + tor_add_idx = rec["cmds"].index(tor_add) |
| 279 | + assert tor_del in rec["cmds"][tor_add_idx + 1 :] |
| 280 | + if expect_nat_rollback: |
| 281 | + assert nat_redir_del in rec["cmds"] |
| 282 | + |
| 283 | + |
| 284 | +@pytest.mark.parametrize( |
| 285 | + "label,matcher", |
| 286 | + [ |
| 287 | + ("tor_delete", lambda cmd: "-D" in cmd and "CAPE_TOR_CLIENTS" in cmd), |
| 288 | + ("fwd_delete", lambda cmd: "-D" in cmd and "FORWARD" in cmd), |
| 289 | + ("nat_redir_delete", lambda cmd: "-D" in cmd and "PREROUTING" in cmd and "REDIRECT" in cmd), |
| 290 | + ], |
| 291 | +) |
| 292 | +def test_socks5_disable_completes_remaining_teardown_before_raising(rec, label, matcher): |
| 293 | + rec["fail_match"] = matcher |
| 294 | + with pytest.raises(RuntimeError): |
| 295 | + rooter.socks5_disable("172.16.1.4", "2042", "5354", "9040") |
| 296 | + |
| 297 | + fwd_del = ("iptables", "-w", "5", "-D", "FORWARD", "--source", "172.16.1.4", "-j", "DROP", *_CAPE_COMMENT) |
| 298 | + nat_dns_udp_del = ( |
| 299 | + "iptables", |
| 300 | + "-w", |
| 301 | + "5", |
| 302 | + "-t", |
| 303 | + "nat", |
| 304 | + "-D", |
| 305 | + "PREROUTING", |
| 306 | + "-p", |
| 307 | + "udp", |
| 308 | + "--dport", |
| 309 | + "53", |
| 310 | + "--source", |
| 311 | + "172.16.1.4", |
| 312 | + "-j", |
| 313 | + "REDIRECT", |
| 314 | + "--to-ports", |
| 315 | + "5354", |
| 316 | + *_CAPE_COMMENT, |
| 317 | + ) |
| 318 | + out_drop_del = ("iptables", "-w", "5", "-D", "OUTPUT", "--source", "172.16.1.4", "-j", "DROP", *_CAPE_COMMENT) |
| 319 | + |
| 320 | + assert fwd_del in rec["cmds"] |
| 321 | + assert nat_dns_udp_del in rec["cmds"] |
| 322 | + assert out_drop_del in rec["cmds"] |
| 323 | + assert rec["cmds"][-1] == ("conntrack", "-D", "-s", "172.16.1.4") |
| 324 | + |
| 325 | + |
| 326 | +def test_iptables_delete_all_does_not_spin_on_xtables_lock_without_wait(rec, caplog): |
| 327 | + rec["fail_match"] = lambda cmd: "-D" in cmd and "POSTROUTING" in cmd |
| 328 | + with caplog.at_level("WARNING"): |
| 329 | + rooter._iptables_delete_all("-t", "nat", "-D", "POSTROUTING", "-s", "172.16.1.4", "-j", "MASQUERADE") |
| 330 | + |
| 331 | + postrouting_cmds = [cmd for cmd in rec["cmds"] if "POSTROUTING" in cmd] |
| 332 | + assert len(postrouting_cmds) == 1 |
| 333 | + assert "Best-effort iptables delete failed" in caplog.text |
| 334 | + |
| 335 | + |
| 336 | +def test_iptables_delete_all_removes_stacked_duplicates(rec): |
| 337 | + rooter._iptables_delete_all("-t", "nat", "-D", "POSTROUTING", "-s", "172.16.1.4", "-j", "MASQUERADE") |
| 338 | + del_cmd = ("iptables", "-t", "nat", "-D", "POSTROUTING", "-s", "172.16.1.4", "-j", "MASQUERADE", *_CAPE_COMMENT) |
| 339 | + assert rec["delete_counts"][del_cmd] == 3 |
| 340 | + |
| 341 | + |
| 342 | +def test_run_status_handles_oserror(monkeypatch): |
| 343 | + def fake_run(*args, **kwargs): |
| 344 | + raise FileNotFoundError("No such file or directory: iptables") |
| 345 | + |
| 346 | + monkeypatch.setattr(rooter.subprocess, "run", fake_run) |
| 347 | + rc, out, err = rooter.run_status("iptables", "-L") |
| 348 | + assert rc == 1 |
| 349 | + assert out == "" |
| 350 | + assert "No such file or directory" in err |
| 351 | + |
| 352 | + |
| 353 | +def test_cleanup_rooter_preserves_cape_tor_clients_chain_and_strips_vm_rules(monkeypatch): |
| 354 | + saved_rules = "\n".join( |
| 355 | + [ |
| 356 | + "*raw", |
| 357 | + ":PREROUTING ACCEPT [0:0]", |
| 358 | + ":VT_GUEST_FWD - [0:0]", |
| 359 | + ":CAPE_TOR_CLIENTS - [0:0]", |
| 360 | + "-A VT_GUEST_FWD -s 172.16.1.0/24 -d 10.192.0.0/10 -p tcp -j CAPE_TOR_CLIENTS", |
| 361 | + '-A CAPE_TOR_CLIENTS -s 172.16.1.4/32 -p tcp -m comment --comment "CAPE-rooter" -j ACCEPT', |
| 362 | + "COMMIT", |
| 363 | + ] |
| 364 | + ) |
| 365 | + restored = {} |
| 366 | + |
| 367 | + class FakePopen: |
| 368 | + def __init__(self, cmd, **kwargs): |
| 369 | + restored["cmd"] = cmd |
| 370 | + |
| 371 | + def communicate(self, input=None): |
| 372 | + restored["input"] = input |
| 373 | + return ("", "") |
| 374 | + |
| 375 | + monkeypatch.setattr(rooter.ServicePaths, "iptables_save", "iptables-save", raising=False) |
| 376 | + monkeypatch.setattr(rooter.ServicePaths, "iptables_restore", "iptables-restore", raising=False) |
| 377 | + monkeypatch.setattr(rooter, "run", lambda *args: (saved_rules, "")) |
| 378 | + monkeypatch.setattr(rooter.subprocess, "Popen", FakePopen) |
| 379 | + monkeypatch.setattr(rooter.subprocess, "check_output", lambda *args, **kwargs: "") |
| 380 | + |
| 381 | + rooter.cleanup_rooter() |
| 382 | + |
| 383 | + assert ":CAPE_TOR_CLIENTS - [0:0]" in restored["input"] |
| 384 | + assert "-j CAPE_TOR_CLIENTS" in restored["input"] |
| 385 | + assert "172.16.1.4/32" not in restored["input"] |
0 commit comments