my-homelab-configs/scripts/network-sandbox-wan-host.py

172 lines
7.8 KiB
Python

#!/usr/bin/env python3
"""Temporarily test the sandbox WAN with host-side egress restrictions."""
import fcntl
import json
import os
import socket
import subprocess
import sys
import time
from pathlib import Path
TAP = 'tap9100i0'
MARKER = Path('/run/jeannie-sandbox-wan-probe')
BLOCKED = ('10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16',
'100.64.0.0/10', '169.254.0.0/16', '127.0.0.0/8')
def run(*args):
result = subprocess.run(args, capture_output=True, text=True, timeout=20)
if result.returncode:
raise RuntimeError(f'{args[0]}: {result.stderr.strip()[-400:]}')
return result.stdout.strip()
def qmp(up):
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.settimeout(5)
sock.connect('/var/run/qemu-server/9100.qmp')
stream = sock.makefile('rwb', buffering=0)
if 'QMP' not in json.loads(stream.readline()):
raise RuntimeError('Invalid QMP greeting')
for command in ({'execute': 'qmp_capabilities', 'id': 'caps'},
{'execute': 'set_link', 'arguments': {'name': 'net0', 'up': up}, 'id': 'link'}):
stream.write((json.dumps(command) + '\n').encode())
while True:
response = json.loads(stream.readline())
if response.get('id') == command['id']:
if 'error' in response:
raise RuntimeError(f'QMP {command["execute"]}: {response["error"]}')
break
def fields(text):
return dict(line.split(': ', 1) for line in text.splitlines() if ': ' in line)
def verify_router():
config = fields(run('qm', 'config', '9100'))
wan = dict(part.split('=', 1) for part in config.get('net0', '').split(',') if '=' in part)
if (config.get('name') != 'jeannie-sandbox-openwrt' or
config.get('description') != 'jeannie-network-sandbox-v1' or
wan.get('bridge') != 'vmbr0' or wan.get('link_down') != '1'):
raise RuntimeError('Sandbox router identity or disconnected WAN configuration changed')
if run('qm', 'status', '9100') != 'status: running':
raise RuntimeError('Sandbox router is not running')
if not (Path('/sys/class/net/vmbr0/brif') / TAP).exists():
raise RuntimeError('Sandbox WAN tap is not on vmbr0')
def install_guard():
for number, cidr in enumerate(BLOCKED, 10):
run('tc', 'filter', 'add', 'dev', TAP, 'ingress', 'protocol', 'ip',
'pref', str(number), 'flower', 'dst_ip', cidr, 'action', 'drop')
for protocol, pref in (('ip', '100'), ('arp', '101')):
run('tc', 'filter', 'add', 'dev', TAP, 'ingress', 'protocol', protocol,
'pref', pref, 'matchall', 'action', 'pass')
run('tc', 'filter', 'add', 'dev', TAP, 'ingress', 'protocol', 'all',
'pref', '102', 'matchall', 'action', 'drop')
def isolate():
# Disable the host tap first; if QMP fails the guest is still isolated.
run('ip', 'link', 'set', 'dev', TAP, 'down')
qmp(False)
def cleanup():
isolate()
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':
run('tc', 'qdisc', 'del', 'dev', TAP, 'clsact')
MARKER.unlink()
def client_connect(ctid, host, port):
pid = run('lxc-info', '-n', str(ctid), '-p', '-H')
if not pid.isdigit() or int(pid) <= 1:
raise RuntimeError(f'Container {ctid} is not running')
code = ('import socket,sys\n'
'try:\n socket.create_connection((sys.argv[1],int(sys.argv[2])),timeout=3).close()\n'
'except OSError as e:\n print("CONNECT_ERROR:",e); sys.exit(1)\n'
'print("CONNECTED")\n')
result = subprocess.run(('nsenter', '-t', pid, '-n', '--', sys.executable, '-c', code,
host, str(port)), capture_output=True, text=True, timeout=8)
if result.returncode == 0 and result.stdout.strip() == 'CONNECTED':
return True, 'connected'
if result.returncode == 1 and result.stdout.startswith('CONNECT_ERROR:'):
return False, result.stdout.strip()
raise RuntimeError(f'Container {ctid} probe failed: {result.stderr.strip()[-300:]}')
def main():
if os.geteuid() != 0 or len(sys.argv) != 2 or sys.argv[1] not in ('probe', 'reset'):
print('Run as root with probe or reset', file=sys.stderr)
return 2
watchdog = None
try:
with open('/run/lock/jeannie-network-sandbox.lock', 'a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
verify_router()
if sys.argv[1] == 'reset':
cleanup()
print('Sandbox WAN isolated; temporary probe guard removed if present.')
return 0
if MARKER.exists():
raise RuntimeError('Previous probe needs cleanup: run jeannie network-sandbox wan-reset')
addresses = json.loads(run('ip', '-j', '-4', 'addr', 'show', 'dev', 'vmbr0'))
host_ip = next((a['local'] for a in addresses[0]['addr_info'] if a.get('scope') == 'global'), None)
if not host_ip:
raise RuntimeError('vmbr0 has no IPv4 address for the positive control')
try:
socket.create_connection((host_ip, 22), timeout=3).close()
except OSError as exc:
raise RuntimeError(f'Host SSH positive control failed: {exc}') from exc
fd = os.open(MARKER, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
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()
# 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"])'],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True, close_fds=True)
qmp(True)
run('ip', 'link', 'set', 'dev', TAP, 'up')
results = {}
deadline = time.monotonic() + 60
for ctid in (9110, 9111):
while True:
ok, detail = client_connect(ctid, '1.1.1.1', 443)
if ok or time.monotonic() >= deadline:
break
time.sleep(3)
if not ok:
raise RuntimeError(f'Client {ctid} internet TCP probe failed: {detail}')
reachable, detail = client_connect(ctid, host_ip, 22)
if reachable:
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,
'note': 'Sampled TCP checks; not proof for every endpoint or protocol.'}, indent=2))
finally:
cleanup()
if watchdog:
watchdog.terminate()
watchdog.wait(timeout=5)
print('Sandbox WAN disconnected after test.')
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
print(f'Sandbox WAN probe failed: {exc}. WAN cleanup can be retried with ./jeannie network-sandbox wan-reset.', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())