diff --git a/docs/network-sandbox.md b/docs/network-sandbox.md index 30e7187..c7d73e6 100644 --- a/docs/network-sandbox.md +++ b/docs/network-sandbox.md @@ -17,8 +17,11 @@ failure for inspection. `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. +live bridge VLAN assignments, client addresses, cross-VLAN ICMP replies, and +TCP connections to temporary listeners in both directions. Each TCP probe +requires a successful connection from the listener's own namespace first. The +listeners are removed when verification finishes. These selected probes do not +prove complete isolation or establish readiness to enable WAN access. 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/scripts/network-sandbox-verify-host.py b/scripts/network-sandbox-verify-host.py index 373076c..cf15002 100644 --- a/scripts/network-sandbox-verify-host.py +++ b/scripts/network-sandbox-verify-host.py @@ -2,7 +2,10 @@ """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 @@ -54,6 +57,88 @@ def peer_probe(source, own_ip, peer_ip): 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: @@ -108,12 +193,20 @@ def main(): '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, - 'note': 'ICMP results alone do not establish firewall isolation or internet readiness.'} + '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()): + 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) diff --git a/tests/jeannie/test_network_sandbox_verify.py b/tests/jeannie/test_network_sandbox_verify.py index 8d43f1e..d3c5fe0 100644 --- a/tests/jeannie/test_network_sandbox_verify.py +++ b/tests/jeannie/test_network_sandbox_verify.py @@ -3,7 +3,7 @@ import importlib.util import subprocess import unittest from pathlib import Path -from unittest.mock import patch +from unittest.mock import MagicMock, patch ROOT = Path(__file__).resolve().parents[2] spec = importlib.util.spec_from_file_location('sandbox_verify', ROOT / 'scripts/network-sandbox-verify-host.py') @@ -29,6 +29,43 @@ class SandboxVerifyTests(unittest.TestCase): self.assertIn('inconclusive', message) self.assertIn('permission denied', message) + def test_tcp_probe_requires_positive_control_and_cleans_up(self): + listener = MagicMock() + listener.stdout.readline.return_value = '45678\n' + listener.poll.return_value = None + control = subprocess.CompletedProcess([], 0, stdout='', stderr='') + blocked = subprocess.CompletedProcess([], 1, stdout='CONNECT_ERROR: timed out\n', stderr='') + with patch.object(verify.subprocess, 'Popen', return_value=listener), \ + patch.object(verify.select, 'select', return_value=([listener.stdout], [], [])), \ + patch.object(verify, 'tcp_connect', side_effect=[control, blocked]): + result = verify.tcp_probe(10, 20, '172.29.220.107') + self.assertIn('connection failed with positive control', result) + listener.terminate.assert_called_once() + listener.communicate.assert_called_once() + + def test_tcp_probe_reports_unexpected_connection(self): + listener = MagicMock() + listener.stdout.readline.return_value = '45678\n' + listener.poll.return_value = None + success = subprocess.CompletedProcess([], 0, stdout='', stderr='') + with patch.object(verify.subprocess, 'Popen', return_value=listener), \ + patch.object(verify.select, 'select', return_value=([listener.stdout], [], [])), \ + patch.object(verify, 'tcp_connect', side_effect=[success, success]): + result = verify.tcp_probe(10, 20, '172.29.220.107') + self.assertIn('cross-VLAN TCP isolation failed', result) + + def test_tcp_probe_does_not_treat_nsenter_failure_as_isolation(self): + listener = MagicMock() + listener.stdout.readline.return_value = '45678\n' + listener.poll.return_value = None + control = subprocess.CompletedProcess([], 0, stdout='', stderr='') + failed = subprocess.CompletedProcess([], 1, stdout='', stderr='nsenter: permission denied') + with patch.object(verify.subprocess, 'Popen', return_value=listener), \ + patch.object(verify.select, 'select', return_value=([listener.stdout], [], [])), \ + patch.object(verify, 'tcp_connect', side_effect=[control, failed]): + result = verify.tcp_probe(10, 20, '172.29.220.107') + self.assertIn('inconclusive', result) + if __name__ == '__main__': unittest.main()