From dd9933f2f4fec4345aa05aea251df0a001ae73d4 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Fri, 6 Nov 2026 23:32:58 -0600 Subject: [PATCH] Add sandbox network isolation exercises --- docs/network-sandbox.md | 9 ++ jeannie | 15 ++- scripts/network-sandbox-isolation-host.py | 92 +++++++++++++++++++ scripts/network-sandbox-isolation.py | 30 ++++++ .../jeannie/test_network_sandbox_isolation.py | 38 ++++++++ 5 files changed, 181 insertions(+), 3 deletions(-) create mode 100644 scripts/network-sandbox-isolation-host.py create mode 100644 scripts/network-sandbox-isolation.py create mode 100644 tests/jeannie/test_network_sandbox_isolation.py diff --git a/docs/network-sandbox.md b/docs/network-sandbox.md index 20516a0..c9d0fb8 100644 --- a/docs/network-sandbox.md +++ b/docs/network-sandbox.md @@ -45,6 +45,15 @@ brings the sandbox WAN tap down after two minutes if the probe is interrupted. The persistent VM configuration remains disconnected. If cleanup fails, run `./jeannie network-sandbox wan-reset` to isolate the tap and remove the owned guard before retrying. This test does not enable permanent internet access. + +`./jeannie network-sandbox isolation-tests` runs the verification and WAN +probe together with additional learning exercises. It checks each VLAN's +gateway and sends UDP between temporary client listeners in both directions, +after proving each listener works locally. A peer UDP response is a failure; +a timeout is only an observation, and a failed local control is inconclusive. +The final stage temporarily enables WAN using the same guarded probe described +above, then disconnects it. The command stops on a failed or inconclusive +stage; it does not exhaustively prove isolation against every protocol. The existing cluster bridge, host addresses, and existing VM disks are not modified by this workflow. Download and disk-import staging files remain under `/data/jeannie/network-sandbox` after provisioning. diff --git a/jeannie b/jeannie index dd3cad8..e53f6f9 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|verify|wan-probe|wan-reset} Manage the independent network lab. + network-sandbox {plan|prepare|provision|start|stop|verify|isolation-tests|wan-probe|wan-reset} 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|verify|wan-probe|wan-reset}" >&2; exit 2; } + [[ $# -le 2 ]] || { echo "Usage: ./jeannie network-sandbox {plan|prepare|provision|start|stop|verify|isolation-tests|wan-probe|wan-reset}" >&2; exit 2; } case "${2:-plan}" in plan) python3 "${REPO_ROOT}/scripts/network-sandbox-plan.py" ;; prepare|provision|start) @@ -821,6 +821,15 @@ case "${1:-}" in -p 'test_network_sandbox_verify.py' || exit 1 python3 "${REPO_ROOT}/scripts/network-sandbox-verify.py" ;; + isolation-tests) + record_change_journal "network-sandbox" "$@" + python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_verify.py' || exit 1 + python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_isolation.py' || exit 1 + python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_wan.py' || exit 1 + python3 "${REPO_ROOT}/scripts/network-sandbox-verify.py" || exit 1 + python3 "${REPO_ROOT}/scripts/network-sandbox-isolation.py" || exit 1 + python3 "${REPO_ROOT}/scripts/network-sandbox-wan.py" probe + ;; wan-probe) record_change_journal "network-sandbox" "$@" python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_wan.py' || exit 1 @@ -832,7 +841,7 @@ case "${1:-}" in record_change_journal "network-sandbox" "$@" python3 "${REPO_ROOT}/scripts/network-sandbox-wan.py" reset ;; - *) echo "Usage: ./jeannie network-sandbox {plan|prepare|provision|start|stop|verify|wan-probe|wan-reset}" >&2; exit 2 ;; + *) echo "Usage: ./jeannie network-sandbox {plan|prepare|provision|start|stop|verify|isolation-tests|wan-probe|wan-reset}" >&2; exit 2 ;; esac ;; nuke) diff --git a/scripts/network-sandbox-isolation-host.py b/scripts/network-sandbox-isolation-host.py new file mode 100644 index 0000000..ddc4819 --- /dev/null +++ b/scripts/network-sandbox-isolation-host.py @@ -0,0 +1,92 @@ +#!/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()) diff --git a/scripts/network-sandbox-isolation.py b/scripts/network-sandbox-isolation.py new file mode 100644 index 0000000..f96ab75 --- /dev/null +++ b/scripts/network-sandbox-isolation.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Execute the sandbox isolation exercises on the Pimox host.""" +import os +from pathlib import Path +import subprocess +import sys + + +def main(): + directory = Path(__file__).resolve().parent + helper = (directory / 'network-sandbox-verify-host.py').read_text() + script = (directory / 'network-sandbox-isolation-host.py').read_text() + payload = ('import types\nverify = types.ModuleType("sandbox_verify")\n' + + 'exec(compile(' + repr(helper) + ', "sandbox_verify", "exec"), verify.__dict__)\n' + + script).encode() + 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: + 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=payload, timeout=120).returncode + except (OSError, subprocess.SubprocessError) as exc: + print(f'Sandbox isolation exercises failed: {exc}', file=sys.stderr) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/jeannie/test_network_sandbox_isolation.py b/tests/jeannie/test_network_sandbox_isolation.py new file mode 100644 index 0000000..f5d663f --- /dev/null +++ b/tests/jeannie/test_network_sandbox_isolation.py @@ -0,0 +1,38 @@ +import importlib.util +from pathlib import Path +import subprocess +import unittest +from unittest.mock import MagicMock, patch + +path = Path(__file__).resolve().parents[2] / 'scripts/network-sandbox-isolation-host.py' +spec = importlib.util.spec_from_file_location('sandbox_isolation', path) +isolation = importlib.util.module_from_spec(spec) +spec.loader.exec_module(isolation) + + +class IsolationExercisesTest(unittest.TestCase): + def probe(self, results): + listener = MagicMock() + listener.stdout.readline.return_value = '45678\n' + listener.poll.return_value = None + with patch.object(isolation.subprocess, 'Popen', return_value=listener), \ + patch.object(isolation.select, 'select', return_value=([listener.stdout], [], [])), \ + patch.object(isolation, 'udp_connect', side_effect=results): + result = isolation.udp_probe(10, 20, '172.29.220.107') + listener.terminate.assert_called_once() + return result + + def test_peer_silence_requires_successful_control(self): + success = subprocess.CompletedProcess([], 0, stdout='', stderr='') + timeout = subprocess.CompletedProcess([], 1, stdout='UDP_ERROR: timed out\n', stderr='') + self.assertIn('positive control', self.probe([success, timeout])) + self.assertIn('inconclusive', self.probe([timeout])) + + def test_udp_reply_is_failure(self): + success = subprocess.CompletedProcess([], 0, stdout='', stderr='') + self.assertTrue(self.probe([success, success]).startswith('failed:')) + + def test_execution_failure_is_inconclusive(self): + success = subprocess.CompletedProcess([], 0, stdout='', stderr='') + failure = subprocess.CompletedProcess([], 1, stdout='', stderr='nsenter failed') + self.assertTrue(self.probe([success, failure]).startswith('inconclusive:'))