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

219 lines
9.8 KiB
Python

#!/usr/bin/env python3
"""Inspect the running sandbox without changing its network or guest state."""
import ipaddress
import json
import os
import re
import secrets
import select
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:
detail = (baseline.stderr or baseline.stdout or 'no diagnostic output').strip().replace('\n', ' ')
return f'inconclusive: client ping self-check failed (exit {baseline.returncode}): {detail[:300]}'
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'
detail = (result.stderr or result.stdout or 'no diagnostic output').strip().replace('\n', ' ')
return f'inconclusive: peer ping failed to execute (exit {result.returncode}): {detail[:300]}'
LISTENER = '''import socket, sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((sys.argv[1], 0))
sock.listen(2)
sock.settimeout(20)
print(sock.getsockname()[1], flush=True)
for _ in range(2):
conn, _ = sock.accept()
with conn:
conn.sendall(sys.argv[2].encode())
sock.close()
'''
CONNECT = '''import socket, sys
try:
with socket.create_connection((sys.argv[1], int(sys.argv[2])), timeout=3) as sock:
sock.settimeout(3)
received = sock.recv(128).decode()
if received != sys.argv[3]:
print('unexpected listener response')
sys.exit(2)
except OSError as exc:
print('CONNECT_ERROR: ' + str(exc))
sys.exit(1)
'''
def container_pid(guest):
output = run('lxc-info', '-n', str(guest), '-p', '-H')
if not output.isdigit() or int(output) <= 1:
raise RuntimeError(f'Cannot find init process for container {guest}')
pid = int(output)
if not Path(f'/proc/{pid}/ns/net').exists():
raise RuntimeError(f'Container {guest} network namespace is unavailable')
return pid
def tcp_connect(pid, ip, port, token):
return subprocess.run(['nsenter', '-t', str(pid), '-n', '--', 'python3', '-c', CONNECT,
ip, str(port), token], capture_output=True, text=True, timeout=8)
def tcp_probe(source_pid, destination_pid, destination_ip):
"""Probe a temporary listener, first locally and then from the other VLAN."""
token = secrets.token_hex(16)
listener = subprocess.Popen(
['nsenter', '-t', str(destination_pid), '-n', '--', 'python3', '-c', LISTENER,
destination_ip, token], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True)
try:
ready, _, _ = select.select([listener.stdout], [], [], 8)
if not ready:
return 'inconclusive: temporary listener did not become ready'
port_text = listener.stdout.readline().strip()
if not port_text.isdigit() or not 1 <= int(port_text) <= 65535:
detail = listener.stderr.read().strip() if listener.poll() is not None else ''
return f'inconclusive: temporary listener did not report a valid port: {detail[:200]}'
baseline = tcp_connect(destination_pid, destination_ip, int(port_text), token)
if baseline.returncode:
return 'inconclusive: same-client TCP positive control failed'
result = tcp_connect(source_pid, destination_ip, int(port_text), token)
if result.returncode == 0:
return 'connected: cross-VLAN TCP isolation failed'
if listener.poll() is not None:
return 'inconclusive: listener exited before the cross-VLAN result'
if result.returncode != 1 or not result.stdout.startswith('CONNECT_ERROR: '):
detail = (result.stderr or result.stdout or 'no diagnostic output').strip().replace('\n', ' ')
return f'inconclusive: TCP probe failed (exit {result.returncode}): {detail[:200]}'
detail = result.stdout.removeprefix('CONNECT_ERROR: ').strip().replace('\n', ' ')
return f'connection failed with positive control: {detail[:200]}'
except (OSError, subprocess.SubprocessError) as exc:
return f'inconclusive: TCP probe error: {exc}'
finally:
if listener.poll() is None:
listener.terminate()
try:
listener.communicate(timeout=3)
except subprocess.TimeoutExpired:
listener.kill()
listener.communicate()
def client_address(guest, network):
output = run('pct', 'exec', str(guest), '--', 'ip', '-4', 'addr', 'show', 'dev', 'eth0')
try:
return address_from_output(output, network)
except RuntimeError as exc:
print(f'Client {guest} address check: {exc}', file=sys.stderr)
print('Interface state:', file=sys.stderr)
print(output[:2000], file=sys.stderr)
for label, command in [('network configuration', ('cat', '/etc/network/interfaces')),
('processes', ('ps',))]:
diagnostic = subprocess.run(['pct', 'exec', str(guest), '--', *command],
capture_output=True, text=True, timeout=20)
print(f'-- {label}', file=sys.stderr)
print(diagnostic.stdout[:3000], file=sys.stderr)
if diagnostic.returncode:
print(f'Client diagnostics exit: {diagnostic.returncode}', file=sys.stderr)
raise
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: client_address(9110, '172.29.210.0/24'),
9111: client_address(9111, '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]),
}
pids = {guest: container_pid(guest) for guest in (9110, 9111)}
if os.stat(f'/proc/{pids[9110]}/ns/net').st_ino == os.stat(f'/proc/{pids[9111]}/ns/net').st_ino:
raise RuntimeError('Sandbox clients unexpectedly share a network namespace')
tcp_probes = {
'vlan10_to_vlan20': tcp_probe(pids[9110], pids[9111], addresses[9111]),
'vlan20_to_vlan10': tcp_probe(pids[9111], pids[9110], addresses[9110]),
}
report = {'wan': 'configured disconnected', 'bridge': 'vmbr9',
'port_vlans': ports, 'client_ipv4': addresses,
'cross_vlan_icmp': probes, 'cross_vlan_tcp': tcp_probes,
'note': 'These probes do not prove all traffic is blocked or establish internet readiness.'}
print(json.dumps(report, indent=2))
if any(value.startswith(('replied:', 'inconclusive:')) for value in probes.values()) or \
any(value.startswith(('connected:', 'inconclusive:')) for value in tcp_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())