diff --git a/docs/network-sandbox.md b/docs/network-sandbox.md index 9bf3ccc..30e7187 100644 --- a/docs/network-sandbox.md +++ b/docs/network-sandbox.md @@ -16,6 +16,9 @@ failure for inspection. **Guests are created stopped and the OpenWrt WAN virtual link is disconnected.** `network-sandbox start` starts only the dedicated sandbox guests after verifying their identity, isolation and host routes; `stop` stops only those guests. +`network-sandbox verify` checks running guests, the disconnected WAN setting, +live bridge VLAN assignments, client addresses, and cross-VLAN ICMP replies. +An ICMP timeout is only an observation and does not prove firewall isolation. These lifecycle commands are independent of K3s. The cluster runtime guard checks declared control-plane and worker VM IDs and Pimox cluster VM names; it does not depend on sandbox guests, bridge, storage, or health. Keep custom diff --git a/jeannie b/jeannie index 3d52a5f..ead1879 100755 --- a/jeannie +++ b/jeannie @@ -208,7 +208,7 @@ Apps And Services website-translation-model Prepare website translation model support. website-ollama-listen Configure website Ollama access. install-gitea-runner [TOKEN] Install the Gitea Actions runner. - network-sandbox {plan|prepare|provision|start|stop} Manage the independent network lab. + network-sandbox {plan|prepare|provision|start|stop|verify} Manage the independent network lab. Security Learning security-scan Run the security scan bundle. @@ -790,7 +790,7 @@ case "${1:-}" in ;; network-sandbox) require_debian_server "network-sandbox" - [[ $# -le 2 ]] || { echo "Usage: ./jeannie network-sandbox {plan|prepare|provision|start|stop}" >&2; exit 2; } + [[ $# -le 2 ]] || { echo "Usage: ./jeannie network-sandbox {plan|prepare|provision|start|stop|verify}" >&2; exit 2; } case "${2:-plan}" in plan) python3 "${REPO_ROOT}/scripts/network-sandbox-plan.py" ;; prepare|provision|start) @@ -816,7 +816,12 @@ case "${1:-}" in record_change_journal "network-sandbox" "$@" python3 "${REPO_ROOT}/scripts/network-sandbox-lifecycle.py" stop ;; - *) echo "Usage: ./jeannie network-sandbox {plan|prepare|provision|start|stop}" >&2; exit 2 ;; + verify) + python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" \ + -p 'test_network_sandbox_verify.py' || exit 1 + python3 "${REPO_ROOT}/scripts/network-sandbox-verify.py" + ;; + *) echo "Usage: ./jeannie network-sandbox {plan|prepare|provision|start|stop|verify}" >&2; exit 2 ;; esac ;; nuke) diff --git a/scripts/network-sandbox-verify-host.py b/scripts/network-sandbox-verify-host.py new file mode 100644 index 0000000..5a2e168 --- /dev/null +++ b/scripts/network-sandbox-verify-host.py @@ -0,0 +1,104 @@ +#!/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()) diff --git a/scripts/network-sandbox-verify.py b/scripts/network-sandbox-verify.py new file mode 100644 index 0000000..7b6c3fd --- /dev/null +++ b/scripts/network-sandbox-verify.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +"""Run the sandbox verification on the Orange Pi over SSH.""" +import os +import subprocess +import sys +from pathlib import Path + + +def main(): + host = os.environ.get('LAB_PIMOX_HOST', '192.168.100.80') + user = os.environ.get('LAB_PIMOX_USER', 'jv') + key = os.environ.get('LAB_PIMOX_SSH_KEY_PATH', '/home/jv/.ssh/id_ed25519') + try: + source = (Path(__file__).resolve().parent / 'network-sandbox-verify-host.py').read_bytes() + return subprocess.run(['ssh', '-T', '-i', key, '-o', 'BatchMode=yes', + '-o', 'IdentitiesOnly=yes', '-o', 'ConnectTimeout=10', + '-o', 'StrictHostKeyChecking=accept-new', f'{user}@{host}', + 'sudo -n python3 -'], input=source, timeout=180).returncode + except (OSError, subprocess.SubprocessError) as exc: + print(f'Sandbox verification failed: {exc}', file=sys.stderr) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/jeannie/test_network_sandbox_verify.py b/tests/jeannie/test_network_sandbox_verify.py new file mode 100644 index 0000000..0237a7b --- /dev/null +++ b/tests/jeannie/test_network_sandbox_verify.py @@ -0,0 +1,25 @@ +"""Offline checks for sandbox verification parsing.""" +import importlib.util +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location('sandbox_verify', ROOT / 'scripts/network-sandbox-verify-host.py') +verify = importlib.util.module_from_spec(spec) +spec.loader.exec_module(verify) + + +class SandboxVerifyTests(unittest.TestCase): + def test_vlan_output(self): + output = 'port vlan ids\ntap9100i1 1 PVID Egress Untagged\n 10\n 20\n' + self.assertEqual(verify.vlan_ids(output), {1, 10, 20}) + + def test_expected_client_address(self): + output = '2: eth0: \n inet 172.29.210.101/24 scope global eth0\n' + self.assertEqual(verify.address_from_output(output, '172.29.210.0/24'), '172.29.210.101') + with self.assertRaises(RuntimeError): + verify.address_from_output(output, '172.29.220.0/24') + + +if __name__ == '__main__': + unittest.main()