Support bridge firewall for sandbox WAN probe
This commit is contained in:
parent
b5274f6cbc
commit
e6812b1c45
|
|
@ -31,12 +31,15 @@ recognizes them. The WAN stays disconnected by default.
|
|||
`./jeannie network-sandbox wan-probe` runs verification, then temporarily
|
||||
connects the router WAN to test TCP internet access from each client. Before
|
||||
connecting, it installs a temporary host-side `tc` guard on the sandbox WAN
|
||||
tap. The guard blocks private, link-local and Tailscale IPv4 destination
|
||||
tap, using `tc` or, if unavailable, dedicated `ebtables` filter chains. The
|
||||
bridge fallback also drops frames addressed to the host. The guard blocks
|
||||
private, link-local and Tailscale IPv4 destination
|
||||
ranges, permits other IPv4 and ARP, and drops other Ethernet protocols. It
|
||||
checks that each client can reach 1.1.1.1:443 and cannot reach the hypervisor's
|
||||
SSH port, for which it first establishes a host-side positive control. These
|
||||
sampled checks do not prove every service, protocol, or firewall rule works.
|
||||
The probe requires `tc`, QEMU QMP access and host SSH listening on vmbr0;
|
||||
The probe requires a supported `tc` or legacy `ebtables` bridge filter,
|
||||
QEMU QMP access and host SSH listening on vmbr0;
|
||||
it refuses to proceed if it cannot install its guard. A detached watchdog
|
||||
brings the sandbox WAN tap down after two minutes if the probe is interrupted.
|
||||
The persistent VM configuration remains disconnected. If cleanup fails, run
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@
|
|||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
|
|
@ -68,6 +70,47 @@ def install_guard():
|
|||
'pref', '102', 'matchall', 'action', 'drop')
|
||||
|
||||
|
||||
def ebt(*args):
|
||||
return run('/sbin/ebtables', '-t', 'filter', *args)
|
||||
|
||||
|
||||
def install_bridge_guard():
|
||||
# Unique chains avoid taking ownership of existing firewall rules. Build
|
||||
# them while the tap is down, and attach them only after they are complete.
|
||||
suffix = secrets.token_hex(4)
|
||||
names = {'input': 'JSI' + suffix, 'forward': 'JSF' + suffix}
|
||||
state = {'backend': 'ebtables', 'chains': []}
|
||||
MARKER.write_text(json.dumps(state))
|
||||
for chain in names.values():
|
||||
ebt('-N', chain)
|
||||
state['chains'].append(chain)
|
||||
MARKER.write_text(json.dumps(state))
|
||||
ebt('-A', names['input'], '-j', 'DROP')
|
||||
for cidr in BLOCKED:
|
||||
ebt('-A', names['forward'], '-p', 'IPv4', '--ip-destination', cidr, '-j', 'DROP')
|
||||
for protocol in ('IPv4', 'ARP'):
|
||||
ebt('-A', names['forward'], '-p', protocol, '-j', 'RETURN')
|
||||
ebt('-A', names['forward'], '-j', 'DROP')
|
||||
ebt('-I', 'INPUT', '1', '-i', TAP, '-j', names['input'])
|
||||
ebt('-I', 'FORWARD', '1', '-i', TAP, '-j', names['forward'])
|
||||
return 'ebtables'
|
||||
|
||||
|
||||
def remove_bridge_guard(state):
|
||||
for chain in reversed(state['chains']):
|
||||
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:
|
||||
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)
|
||||
|
||||
|
||||
def isolate():
|
||||
# Disable the host tap first; if QMP fails the guest is still isolated.
|
||||
run('ip', 'link', 'set', 'dev', TAP, 'down')
|
||||
|
|
@ -79,8 +122,14 @@ def cleanup():
|
|||
if MARKER.exists():
|
||||
# A marker is created before installing our qdisc. A failed qdisc
|
||||
# installation must never cause deletion of someone else's qdisc.
|
||||
if MARKER.read_text().strip() == 'owned':
|
||||
marker = MARKER.read_text().strip()
|
||||
if marker == 'owned':
|
||||
run('tc', 'qdisc', 'del', 'dev', TAP, 'clsact')
|
||||
elif marker:
|
||||
state = json.loads(marker)
|
||||
if state.get('backend') != 'ebtables' or not isinstance(state.get('chains'), list):
|
||||
raise RuntimeError('Unknown sandbox firewall ownership marker')
|
||||
remove_bridge_guard(state)
|
||||
MARKER.unlink()
|
||||
|
||||
|
||||
|
|
@ -128,9 +177,14 @@ def main():
|
|||
os.close(fd)
|
||||
try:
|
||||
run('ip', 'link', 'set', 'dev', TAP, 'down')
|
||||
run('tc', 'qdisc', 'add', 'dev', TAP, 'clsact')
|
||||
MARKER.write_text('owned\n')
|
||||
install_guard()
|
||||
try:
|
||||
run('tc', 'qdisc', 'add', 'dev', TAP, 'clsact')
|
||||
except (OSError, RuntimeError):
|
||||
backend = install_bridge_guard()
|
||||
else:
|
||||
MARKER.write_text('owned\n')
|
||||
install_guard()
|
||||
backend = 'tc'
|
||||
# If this process dies, the detached watchdog shuts the tap after two minutes.
|
||||
watchdog = subprocess.Popen([sys.executable, '-c',
|
||||
'import subprocess,time; time.sleep(120); subprocess.run(["ip","link","set","dev","tap9100i0","down"])'],
|
||||
|
|
@ -153,7 +207,7 @@ def main():
|
|||
raise RuntimeError(f'Client {ctid} reached the host SSH port')
|
||||
results[str(ctid)] = {'internet_tcp_1_1_1_1_443': 'connected',
|
||||
'host_ssh': detail}
|
||||
print(json.dumps({'clients': results, 'host_guard_ipv4_destinations': BLOCKED,
|
||||
print(json.dumps({'clients': results, 'host_guard': backend, 'host_guard_ipv4_destinations': BLOCKED,
|
||||
'note': 'Sampled TCP checks; not proof for every endpoint or protocol.'}, indent=2))
|
||||
finally:
|
||||
cleanup()
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
|
@ -26,6 +28,26 @@ class WanGuardTest(unittest.TestCase):
|
|||
run.assert_called_once_with('ip', 'link', 'set', 'dev', wan.TAP, 'down')
|
||||
qmp.assert_called_once_with(False)
|
||||
|
||||
def test_bridge_guard_attaches_only_after_all_rules(self):
|
||||
with tempfile.TemporaryDirectory() as directory, \
|
||||
patch.object(wan, 'MARKER', Path(directory) / 'marker'), \
|
||||
patch.object(wan.secrets, 'token_hex', return_value='1234abcd'), \
|
||||
patch.object(wan, 'ebt') as ebt:
|
||||
self.assertEqual(wan.install_bridge_guard(), 'ebtables')
|
||||
state = json.loads(wan.MARKER.read_text())
|
||||
self.assertEqual(state['chains'], ['JSI1234abcd', 'JSF1234abcd'])
|
||||
calls = [call.args for call in ebt.call_args_list]
|
||||
self.assertEqual(calls[-2:], [('-I', 'INPUT', '1', '-i', wan.TAP, '-j', 'JSI1234abcd'),
|
||||
('-I', 'FORWARD', '1', '-i', wan.TAP, '-j', 'JSF1234abcd')])
|
||||
for cidr in wan.BLOCKED:
|
||||
self.assertIn(('-A', 'JSF1234abcd', '-p', 'IPv4', '--ip-destination', cidr, '-j', 'DROP'), calls)
|
||||
self.assertIn(('-A', 'JSI1234abcd', '-j', 'DROP'), calls)
|
||||
self.assertIn(('-A', 'JSF1234abcd', '-j', 'DROP'), calls)
|
||||
|
||||
def test_cleanup_rejects_foreign_chain_names(self):
|
||||
with self.assertRaises(RuntimeError):
|
||||
wan.remove_bridge_guard({'chains': ['FORWARD']})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
|
|
|||
Loading…
Reference in New Issue