my-homelab-configs/scripts/network-sandbox-lifecycle-h...

137 lines
6.6 KiB
Python

#!/usr/bin/env python3
"""Start or stop only the dedicated, previously provisioned sandbox guests."""
import fcntl
import ipaddress
import json
import os
import subprocess
import sys
from pathlib import Path
def run(*args):
result = subprocess.run(args, capture_output=True, text=True, timeout=120)
if result.returncode:
raise RuntimeError(f'{args[0]} failed: {result.stderr.strip()[-500:]}')
return result.stdout.strip()
def config_fields(text):
return dict(line.split(': ', 1) for line in text.splitlines() if ': ' in line)
def network_options(text):
return dict(part.split('=', 1) for part in text.split(',') if '=' in part)
def verify_guests(require_isolated=True):
router = config_fields(run('qm', 'config', '9100'))
if router.get('name') != 'jeannie-sandbox-openwrt' or router.get('description') != 'jeannie-network-sandbox-v1':
raise RuntimeError('VM 9100 is not the dedicated sandbox router')
if require_isolated:
networks = {key for key in router if key.startswith('net') and key[3:].isdigit()}
if networks != {'net0', 'net1'}:
raise RuntimeError('Unexpected router interfaces; refusing to start it')
wan, lan = network_options(router['net0']), network_options(router['net1'])
if wan.get('bridge') != 'vmbr0' or wan.get('link_down') != '1':
raise RuntimeError('Router WAN must remain disconnected pending isolation validation')
if lan.get('bridge') != 'vmbr9' or set(lan.get('trunks', '').split(';')) != {'10', '20'}:
raise RuntimeError('Router is not attached to the expected sandbox VLAN trunk')
for ctid, vlan in ((9110, 10), (9111, 20)):
client = config_fields(run('pct', 'config', str(ctid)))
if client.get('hostname') != f'jeannie-sandbox-client-{vlan}' or client.get('unprivileged') != '1':
raise RuntimeError(f'Container {ctid} is not the expected unprivileged sandbox client')
if require_isolated:
net = network_options(client.get('net0', ''))
if net.get('bridge') != 'vmbr9' or net.get('tag') != str(vlan):
raise RuntimeError(f'Container {ctid} is not attached to its sandbox VLAN')
if any(k.startswith('net') and k[3:].isdigit() and k != 'net0' for k in client):
raise RuntimeError(f'Container {ctid} has an unexpected network interface')
def verify_bridge_and_routes():
bridge = Path('/sys/class/net/vmbr9')
if not (bridge / 'bridge').is_dir() or (bridge / 'ifalias').read_text().strip() != 'jeannie-network-sandbox':
raise RuntimeError('The dedicated sandbox bridge is missing or unmarked')
if (bridge / 'bridge/vlan_filtering').read_text().strip() != '1':
raise RuntimeError('Sandbox bridge is not VLAN aware')
allowed = {'tap9100i1', 'veth9110i0', 'veth9111i0'}
members = {p.name for p in (bridge / 'brif').iterdir()}
if not members.issubset(allowed):
raise RuntimeError('Sandbox bridge has unexpected members: ' + ', '.join(sorted(members - allowed)))
sandbox_nets = [ipaddress.ip_network('172.29.210.0/24'), ipaddress.ip_network('172.29.220.0/24')]
for route in json.loads(run('ip', '-j', '-4', 'route', 'show', 'table', 'all')):
if route.get('dst', 'default') == 'default':
continue
network = ipaddress.ip_network(route['dst'], strict=False)
if any(network.overlaps(sandbox) for sandbox in sandbox_nets):
raise RuntimeError(f'Sandbox subnet overlaps an existing host route: {network}')
def status(command, guest):
output = run(command, 'status', str(guest))
if output not in ('status: stopped', 'status: running'):
raise RuntimeError(f'Unexpected {command} status for {guest}: {output}')
return output.endswith('running')
def owned_existing_guests():
resources = json.loads(run('pvesh', 'get', '/cluster/resources', '--type', 'vm', '--output-format', 'json'))
indexed = {int(item['vmid']): item.get('type') for item in resources if 'vmid' in item}
result = []
for command, guest, kind in (('pct', 9111, 'lxc'), ('pct', 9110, 'lxc'), ('qm', 9100, 'qemu')):
if guest not in indexed:
continue
if indexed[guest] != kind:
raise RuntimeError(f'Guest ID {guest} has an unexpected resource type')
fields = config_fields(run(command, 'config', str(guest)))
if command == 'qm':
if fields.get('name') != 'jeannie-sandbox-openwrt' or fields.get('description') != 'jeannie-network-sandbox-v1':
raise RuntimeError('VM 9100 is not the dedicated sandbox router')
else:
vlan = 10 if guest == 9110 else 20
if fields.get('hostname') != f'jeannie-sandbox-client-{vlan}' or fields.get('unprivileged') != '1':
raise RuntimeError(f'Container {guest} is not the expected sandbox client')
result.append((command, guest))
return result
def main():
if os.geteuid() != 0 or len(sys.argv) != 2 or sys.argv[1] not in ('start', 'stop'):
print('Run as root with start or stop', file=sys.stderr)
return 2
action = sys.argv[1]
started = []
try:
with open('/run/lock/jeannie-network-sandbox.lock', 'a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
if action == 'start':
verify_guests()
verify_bridge_and_routes()
for command, guest in (('qm', 9100), ('pct', 9110), ('pct', 9111)):
if not status(command, guest):
run(command, 'start', str(guest))
started.append((command, guest))
if not status(command, guest):
raise RuntimeError(f'{command} guest {guest} did not remain running')
print('Sandbox guests started with the router WAN disconnected; internet access is not enabled.')
print('Guest startup does not prove firewall or VLAN isolation; validate both before connecting WAN.')
else:
for command, guest in owned_existing_guests():
if status(command, guest):
run(command, 'stop', str(guest))
print('Stopped sandbox guests; their disks and configuration were retained.')
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
for command, guest in reversed(started):
try:
run(command, 'stop', str(guest))
except (OSError, RuntimeError, subprocess.SubprocessError):
pass
print(f'Sandbox {action} failed: {exc}', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())