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

119 lines
5.6 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)
'''
DNS_CLIENT = '''import socket,sys
query=bytes.fromhex('5a3101000001000000000000096c6f63616c686f73740000010001')
try:
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM); s.settimeout(3)
s.connect((sys.argv[1],53)); s.send(query); data=s.recv(512)
if len(data)<12 or data[:2]!=query[:2] or not (data[2]&128):
print('DNS_INVALID: malformed or mismatched response'); sys.exit(2)
print('DNS_RESPONSE: rcode='+str(data[3]&15))
except OSError as e:
print('DNS_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 gateway_dns(pid, gateway):
result = subprocess.run(['nsenter', '-t', str(pid), '-n', '--', 'python3', '-c',
DNS_CLIENT, gateway], capture_output=True, text=True, timeout=8)
if result.returncode == 0 and result.stdout.startswith('DNS_RESPONSE: '):
return 'reachable: ' + result.stdout.strip()
detail = (result.stdout or result.stderr or 'no diagnostic output').strip().replace('\n', ' ')
return f'inconclusive: DNS probe exit {result.returncode}: {detail[:200]}'
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 = {}
gateway_icmp = {}
for guest, (_, gateway) in clients.items():
gateways[str(guest)] = gateway_dns(pids[guest], gateway)
result = subprocess.run(['pct', 'exec', str(guest), '--', 'ping', '-c', '1', '-W', '2', gateway],
capture_output=True, text=True, timeout=12)
if result.returncode == 0:
gateway_icmp[str(guest)] = 'reply received'
else:
detail = (result.stderr or result.stdout or 'no diagnostic output').strip().replace('\n', ' ')
gateway_icmp[str(guest)] = f'no reply or probe error (exit {result.returncode}): {detail[:160]}'
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_dns': gateways, 'gateway_icmp': gateway_icmp, 'cross_vlan_udp': udp,
'interpretation': 'Gateway DNS replies show the router DNS service responded; its firewall rejects ICMP by default. UDP silence is a sampled result, not proof of universal isolation.'}, indent=2))
return int(any(not x.startswith('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())