#!/usr/bin/env python3 """Capture one dedicated sandbox port and produce a private tshark report.""" import json import os from pathlib import Path import select import shutil import signal import subprocess import sys import tempfile import time PORTS = {'vlan10': ('veth9110i0', 'vmbr9'), 'vlan20': ('veth9111i0', 'vmbr9'), 'trunk': ('tap9100i1', 'vmbr9'), 'wan': ('tap9100i0', 'vmbr0')} UUID = '19972338-9757-4f4b-89d7-c202df14a9aa' def check_port(choice): port, bridge = PORTS[choice] config = subprocess.run(['qm', 'config', '9100'], capture_output=True, text=True, timeout=15, check=True).stdout fields = dict(line.split(': ', 1) for line in config.splitlines() if ': ' in line) 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') if choice in ('vlan10', 'vlan20'): guest, vlan = ('9110', '10') if choice == 'vlan10' else ('9111', '20') config = subprocess.run(['pct', 'config', guest], capture_output=True, text=True, timeout=15, check=True).stdout fields = dict(line.split(': ', 1) for line in config.splitlines() if ': ' in line) 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') if not (Path('/sys/class/net') / bridge / 'brif' / port).exists(): raise RuntimeError(f'{port} is not attached to {bridge}; start the sandbox first') if bridge == 'vmbr9' and (Path('/sys/class/net/vmbr9/ifalias').read_text().strip() != 'jeannie-network-sandbox'): raise RuntimeError('Sandbox bridge is not marked as owned by Jeannie') return port def storage_root(): result = subprocess.run(['findmnt', '-n', '-M', '/data', '-o', 'UUID,OPTIONS'], capture_output=True, text=True, timeout=10, check=True) fields = result.stdout.split() if len(fields) != 2 or fields[0] != UUID or 'rw' not in fields[1].split(','): raise RuntimeError('/data is not the expected writable SSD') base = Path('/data/jeannie/network-sandbox') for part in (Path('/data/jeannie'), base): if part.is_symlink() or not part.is_dir(): raise RuntimeError(f'Expected sandbox directory is missing or a symlink: {part}') captures = base / 'captures' captures.mkdir(mode=0o700, exist_ok=True) if captures.is_symlink() or not captures.is_dir() or captures.stat().st_uid != 0: raise RuntimeError('Capture directory must be a root-owned directory') os.chmod(captures, 0o700) return captures def report(tshark, capture, output, choice, status): sections = [ ('Protocol hierarchy and IPv4 conversations', [tshark, '-n', '-r', str(capture), '-q', '-z', 'io,phs', '-z', 'conv,ip']), ('DNS queries and responses', [tshark, '-n', '-r', str(capture), '-Y', 'dns', '-T', 'fields', '-e', 'frame.time_relative', '-e', 'ip.src', '-e', 'ip.dst', '-e', 'dns.qry.name', '-e', 'dns.flags.response', '-e', 'dns.flags.rcode']), ('TCP retransmissions', [tshark, '-n', '-r', str(capture), '-Y', 'tcp.analysis.retransmission', '-T', 'fields', '-e', 'frame.time_relative', '-e', 'ip.src', '-e', 'ip.dst', '-e', 'tcp.srcport', '-e', 'tcp.dstport'])] warnings = [] with output.open('w', encoding='utf-8') as out: out.write(f'Sandbox capture: {choice}\nCapture result: {status}\n') out.write('No response does not identify a firewall rule. Captured data may be sensitive.\n') for title, command in sections: out.write(f'\n== {title} ==\n') try: result = subprocess.run(command, capture_output=True, text=True, timeout=40) out.write(result.stdout[:1000000] or '(no matching packets)\n') if result.returncode: warnings.append(title) out.write('Report section failed: ' + result.stderr[-1000:] + '\n') except (OSError, subprocess.SubprocessError) as exc: warnings.append(title) out.write(f'Report section failed: {exc}\n') return warnings def main(): if os.geteuid() != 0 or len(sys.argv) != 2 or sys.argv[1] not in PORTS: print('Expected root and one capture point: vlan10, vlan20, trunk, wan', file=sys.stderr) return 2 capture_process = None try: tshark = shutil.which('tshark') if not tshark: raise RuntimeError('tshark is unavailable on the Orange Pi; install the Debian tshark package there') port = check_port(sys.argv[1]) directory = Path(tempfile.mkdtemp(prefix='capture-', dir=storage_root())) capture, text_report, errors = directory / 'traffic.pcapng', directory / 'report.txt', directory / 'capture-errors.txt' with errors.open('w', encoding='utf-8') as err: capture_process = subprocess.Popen([tshark, '-n', '-i', port, '-w', str(capture), '-a', 'duration:180', '-a', 'filesize:20480'], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=err) deadline = time.monotonic() + 10 while time.monotonic() < deadline and not capture.exists() and capture_process.poll() is None: time.sleep(0.1) if not capture.exists() or capture_process.poll() is not None: raise RuntimeError(f'tshark failed to start; see {errors}') print(json.dumps({'capture_ready': True, 'interface': port, 'directory': str(directory), 'limit': '180 seconds or approximately 20 MiB'}), flush=True) ready, _, _ = select.select([sys.stdin], [], [], 190) if ready: sys.stdin.readline() early = capture_process.poll() is not None if not early: capture_process.send_signal(signal.SIGINT) try: rc = capture_process.wait(timeout=15) except subprocess.TimeoutExpired: capture_process.kill() capture_process.wait() raise RuntimeError(f'tshark did not stop cleanly; capture retained at {directory}') status = 'ended before requested stop (time/size limit or error)' if early else 'stopped after exercises' warnings = report(tshark, capture, text_report, sys.argv[1], status) print(json.dumps({'capture': str(capture), 'report': str(text_report), 'diagnostics': str(errors), 'capture_exit': rc, 'capture_status': status, 'report_warnings': warnings, 'privacy': 'root-only; contains potentially sensitive traffic'}), flush=True) return int(rc != 0 or early or bool(warnings)) except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc: print(f'Sandbox capture failed: {exc}', file=sys.stderr, flush=True) return 1 finally: if capture_process and capture_process.poll() is None: capture_process.terminate() try: capture_process.wait(timeout=5) except subprocess.TimeoutExpired: capture_process.kill() capture_process.wait() if __name__ == '__main__': os.umask(0o077) sys.exit(main())