105 lines
4.6 KiB
Python
105 lines
4.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Inspect the running sandbox without changing its network or guest state."""
|
|
import ipaddress
|
|
import json
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def run(*args, timeout=30):
|
|
result = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
|
|
if result.returncode:
|
|
raise RuntimeError(f'{args[0]} failed: {result.stderr.strip()[-500:]}')
|
|
return result.stdout.strip()
|
|
|
|
|
|
def address_from_output(output, network):
|
|
expected = ipaddress.ip_network(network)
|
|
found = []
|
|
for value in re.findall(r'\binet\s+(\d+\.\d+\.\d+\.\d+)/\d+', output):
|
|
address = ipaddress.ip_address(value)
|
|
if address in expected:
|
|
found.append(str(address))
|
|
if len(found) != 1:
|
|
raise RuntimeError(f'Expected one client address in {network}; found {len(found)}')
|
|
return found[0]
|
|
|
|
|
|
def vlan_ids(output):
|
|
# bridge(8) prints a header and one or more VLAN numbers per port.
|
|
result = set()
|
|
for line in output.splitlines()[1:]:
|
|
for token in line.split():
|
|
if token.isdigit() and 1 <= int(token) <= 4094:
|
|
result.add(int(token))
|
|
return result
|
|
|
|
|
|
def peer_probe(source, own_ip, peer_ip):
|
|
def ping(address):
|
|
return subprocess.run(['pct', 'exec', str(source), '--', 'ping', '-c', '1', '-W', '2', address],
|
|
capture_output=True, text=True, timeout=12)
|
|
baseline = ping(own_ip)
|
|
if baseline.returncode != 0:
|
|
return 'inconclusive: client ping self-check failed'
|
|
result = ping(peer_ip)
|
|
if result.returncode == 0:
|
|
return 'replied: VLAN isolation needs investigation'
|
|
if result.returncode == 1:
|
|
return 'no reply observed; not proof that all traffic is blocked'
|
|
return 'inconclusive: peer ping failed to execute'
|
|
|
|
|
|
def main():
|
|
try:
|
|
for command, guest in (('qm', 9100), ('pct', 9110), ('pct', 9111)):
|
|
if run(command, 'status', str(guest)) != 'status: running':
|
|
raise RuntimeError(f'{command} guest {guest} is not running')
|
|
router = run('qm', 'config', '9100')
|
|
net0 = next((line for line in router.splitlines() if line.startswith('net0: ')), '')
|
|
if 'link_down=1' not in net0.split(','):
|
|
raise RuntimeError('Router WAN is not configured as disconnected')
|
|
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 members != allowed:
|
|
raise RuntimeError(f'Unexpected sandbox bridge members: {sorted(members)}')
|
|
expected_vlans = {'tap9100i1': {10, 20}, 'veth9110i0': {10}, 'veth9111i0': {20}}
|
|
ports = {}
|
|
for port, expected in expected_vlans.items():
|
|
ids = vlan_ids(run('/usr/sbin/bridge', 'vlan', 'show', 'dev', port))
|
|
if not expected.issubset(ids):
|
|
raise RuntimeError(f'{port} is missing expected VLANs: {sorted(expected - ids)}')
|
|
if port != 'tap9100i1' and (ids & {10, 20}) != expected:
|
|
raise RuntimeError(f'{port} has an unexpected sandbox VLAN')
|
|
ports[port] = sorted(ids)
|
|
addresses = {
|
|
9110: address_from_output(run('pct', 'exec', '9110', '--', 'ip', '-4', 'addr', 'show', 'dev', 'eth0'), '172.29.210.0/24'),
|
|
9111: address_from_output(run('pct', 'exec', '9111', '--', 'ip', '-4', 'addr', 'show', 'dev', 'eth0'), '172.29.220.0/24'),
|
|
}
|
|
probes = {
|
|
'vlan10_to_vlan20': peer_probe(9110, addresses[9110], addresses[9111]),
|
|
'vlan20_to_vlan10': peer_probe(9111, addresses[9111], addresses[9110]),
|
|
}
|
|
report = {'wan': 'configured disconnected', 'bridge': 'vmbr9',
|
|
'port_vlans': ports, 'client_ipv4': addresses,
|
|
'cross_vlan_icmp': probes,
|
|
'note': 'ICMP results alone do not establish firewall isolation or internet readiness.'}
|
|
print(json.dumps(report, indent=2))
|
|
if any(value.startswith(('replied:', 'inconclusive:')) for value in probes.values()):
|
|
return 1
|
|
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
|
|
print(f'Sandbox verification failed: {exc}', file=sys.stderr)
|
|
return 1
|
|
return 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|