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

93 lines
4.2 KiB
Python

#!/usr/bin/env python3
"""Run additional sandbox learning probes; verify module is injected by wrapper."""
import json
import secrets
import select
import subprocess
import sys
UDP_LISTENER = '''import socket,sys
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind((sys.argv[1],0)); s.settimeout(12)
print(s.getsockname()[1],flush=True)
for _ in range(2):
data,addr=s.recvfrom(256)
if data==sys.argv[2].encode(): s.sendto(data,addr)
'''
UDP_CLIENT = '''import socket,sys
try:
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM); s.settimeout(2)
s.sendto(sys.argv[3].encode(),(sys.argv[1],int(sys.argv[2])))
data,_=s.recvfrom(256)
if data!=sys.argv[3].encode(): sys.exit(2)
except OSError as e:
print('UDP_ERROR: '+str(e)); sys.exit(1)
'''
def udp_connect(pid, ip, port, token):
return subprocess.run(['nsenter', '-t', str(pid), '-n', '--', 'python3', '-c',
UDP_CLIENT, ip, str(port), token], capture_output=True, text=True, timeout=8)
def udp_probe(source_pid, destination_pid, destination_ip):
token = secrets.token_hex(16)
listener = subprocess.Popen(['nsenter', '-t', str(destination_pid), '-n', '--', 'python3',
'-c', UDP_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: UDP listener did not become ready'
port = listener.stdout.readline().strip()
if not port.isdigit() or not 1 <= int(port) <= 65535:
return 'inconclusive: UDP listener did not report a valid port'
if udp_connect(destination_pid, destination_ip, port, token).returncode:
return 'inconclusive: UDP same-client positive control failed'
result = udp_connect(source_pid, destination_ip, port, token)
if result.returncode == 0:
return 'failed: cross-VLAN UDP response received'
if listener.poll() is not None:
return 'inconclusive: UDP listener exited during peer probe'
if result.returncode == 1 and result.stdout.startswith('UDP_ERROR: '):
return 'no UDP reply with positive control: ' + result.stdout.strip()[11:200]
return 'inconclusive: UDP client could not run or validate its response'
except (OSError, subprocess.SubprocessError) as exc:
return f'inconclusive: UDP probe error: {exc}'
finally:
if listener.poll() is None:
listener.terminate()
try:
listener.communicate(timeout=3)
except subprocess.TimeoutExpired:
listener.kill()
listener.communicate()
def main():
try:
clients = {9110: ('172.29.210.0/24', '172.29.210.1'),
9111: ('172.29.220.0/24', '172.29.220.1')}
addresses = {guest: verify.client_address(guest, network)
for guest, (network, _) in clients.items()}
pids = {guest: verify.container_pid(guest) for guest in clients}
gateways = {}
for guest, (_, gateway) in clients.items():
result = subprocess.run(['pct', 'exec', str(guest), '--', 'ping', '-c', '1', '-W', '2', gateway],
capture_output=True, text=True, timeout=12)
gateways[str(guest)] = 'reachable' if result.returncode == 0 else 'failed or inconclusive'
udp = {'vlan10_to_vlan20': udp_probe(pids[9110], pids[9111], addresses[9111]),
'vlan20_to_vlan10': udp_probe(pids[9111], pids[9110], addresses[9110])}
print(json.dumps({'gateway_icmp': gateways, 'cross_vlan_udp': udp,
'interpretation': 'Gateway replies demonstrate local routing. UDP silence is a sampled result, not proof of universal isolation.'}, indent=2))
return int(any(x != 'reachable' for x in gateways.values()) or
any(x.startswith(('failed:', 'inconclusive:')) for x in udp.values()))
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
print(f'Sandbox isolation exercises failed: {exc}', file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())