diff --git a/scripts/network-sandbox-wan-host.py b/scripts/network-sandbox-wan-host.py index e706f9f..09c3c0b 100644 --- a/scripts/network-sandbox-wan-host.py +++ b/scripts/network-sandbox-wan-host.py @@ -5,6 +5,7 @@ import json import os import re import secrets +import shlex import socket import subprocess import sys @@ -101,12 +102,12 @@ def remove_bridge_guard(state): if not re.fullmatch(r'JS[IF][0-9a-f]{8}', chain): raise RuntimeError('Invalid sandbox firewall ownership marker') parent = 'INPUT' if chain.startswith('JSI') else 'FORWARD' - check = subprocess.run(('/sbin/ebtables', '-t', 'filter', '-C', parent, - '-i', TAP, '-j', chain), capture_output=True, text=True, timeout=20) - if check.returncode == 0: + # In legacy ebtables -C changes counters; it is not a rule check. + # Inspect the executable listing before deleting the exact owned hook. + listing = ebt('-L', parent, '--Lx') + rules = [shlex.split(line) for line in listing.splitlines() if line.strip()] + if any(TAP in rule and chain in rule for rule in rules): ebt('-D', parent, '-i', TAP, '-j', chain) - elif check.returncode != 1: - raise RuntimeError('Could not check sandbox firewall hook: ' + check.stderr.strip()[-300:]) ebt('-F', chain) ebt('-X', chain) diff --git a/tests/jeannie/test_network_sandbox_wan.py b/tests/jeannie/test_network_sandbox_wan.py index 7d4b26a..ca8190b 100644 --- a/tests/jeannie/test_network_sandbox_wan.py +++ b/tests/jeannie/test_network_sandbox_wan.py @@ -48,6 +48,21 @@ class WanGuardTest(unittest.TestCase): with self.assertRaises(RuntimeError): wan.remove_bridge_guard({'chains': ['FORWARD']}) + def test_cleanup_removes_exact_legacy_bridge_hook(self): + listing = 'ebtables -t filter -A FORWARD -i tap9100i0 -j JSF1234abcd\n' + with patch.object(wan, 'ebt', side_effect=[listing, '', '', '']) as ebt: + wan.remove_bridge_guard({'chains': ['JSF1234abcd']}) + self.assertEqual([call.args for call in ebt.call_args_list], [ + ('-L', 'FORWARD', '--Lx'), + ('-D', 'FORWARD', '-i', wan.TAP, '-j', 'JSF1234abcd'), + ('-F', 'JSF1234abcd'), ('-X', 'JSF1234abcd')]) + + def test_cleanup_handles_chain_without_attached_hook(self): + with patch.object(wan, 'ebt', side_effect=['', '', '']) as ebt: + wan.remove_bridge_guard({'chains': ['JSI1234abcd']}) + self.assertEqual([call.args for call in ebt.call_args_list], [ + ('-L', 'INPUT', '--Lx'), ('-F', 'JSI1234abcd'), ('-X', 'JSI1234abcd')]) + if __name__ == '__main__': unittest.main()