Add guarded sandbox WAN connectivity probe
Homelab Main / validate (push) Waiting to run Details
Homelab Main / running-update (push) Blocked by required conditions Details
Homelab Main / debian-ops (push) Blocked by required conditions Details

This commit is contained in:
juvenal.diaz 2026-11-06 23:12:21 -06:00
parent 9f72b74001
commit b5274f6cbc
5 changed files with 260 additions and 5 deletions

View File

@ -26,8 +26,22 @@ 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
cluster guests declared in the inventory or VM ID overrides so that the guard
recognizes them. The WAN stays disconnected; internet access is not yet
implemented because firewall and VLAN isolation require end-to-end validation.
recognizes them. The WAN stays disconnected by default.
`./jeannie network-sandbox wan-probe` runs verification, then temporarily
connects the router WAN to test TCP internet access from each client. Before
connecting, it installs a temporary host-side `tc` guard on the sandbox WAN
tap. The guard blocks private, link-local and Tailscale IPv4 destination
ranges, permits other IPv4 and ARP, and drops other Ethernet protocols. It
checks that each client can reach 1.1.1.1:443 and cannot reach the hypervisor's
SSH port, for which it first establishes a host-side positive control. These
sampled checks do not prove every service, protocol, or firewall rule works.
The probe requires `tc`, QEMU QMP access and host SSH listening on vmbr0;
it refuses to proceed if it cannot install its guard. A detached watchdog
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.
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.

17
jeannie
View File

@ -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} Manage the independent network lab.
network-sandbox {plan|prepare|provision|start|stop|verify|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}" >&2; exit 2; }
[[ $# -le 2 ]] || { echo "Usage: ./jeannie network-sandbox {plan|prepare|provision|start|stop|verify|wan-probe|wan-reset}" >&2; exit 2; }
case "${2:-plan}" in
plan) python3 "${REPO_ROOT}/scripts/network-sandbox-plan.py" ;;
prepare|provision|start)
@ -821,7 +821,18 @@ case "${1:-}" in
-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 ;;
wan-probe)
record_change_journal "network-sandbox" "$@"
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_wan.py' || exit 1
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" || exit 1
python3 "${REPO_ROOT}/scripts/network-sandbox-wan.py" probe
;;
wan-reset)
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 ;;
esac
;;
nuke)

View File

@ -0,0 +1,171 @@
#!/usr/bin/env python3
"""Temporarily test the sandbox WAN with host-side egress restrictions."""
import fcntl
import json
import os
import socket
import subprocess
import sys
import time
from pathlib import Path
TAP = 'tap9100i0'
MARKER = Path('/run/jeannie-sandbox-wan-probe')
BLOCKED = ('10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16',
'100.64.0.0/10', '169.254.0.0/16', '127.0.0.0/8')
def run(*args):
result = subprocess.run(args, capture_output=True, text=True, timeout=20)
if result.returncode:
raise RuntimeError(f'{args[0]}: {result.stderr.strip()[-400:]}')
return result.stdout.strip()
def qmp(up):
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.settimeout(5)
sock.connect('/var/run/qemu-server/9100.qmp')
stream = sock.makefile('rwb', buffering=0)
if 'QMP' not in json.loads(stream.readline()):
raise RuntimeError('Invalid QMP greeting')
for command in ({'execute': 'qmp_capabilities', 'id': 'caps'},
{'execute': 'set_link', 'arguments': {'name': 'net0', 'up': up}, 'id': 'link'}):
stream.write((json.dumps(command) + '\n').encode())
while True:
response = json.loads(stream.readline())
if response.get('id') == command['id']:
if 'error' in response:
raise RuntimeError(f'QMP {command["execute"]}: {response["error"]}')
break
def fields(text):
return dict(line.split(': ', 1) for line in text.splitlines() if ': ' in line)
def verify_router():
config = fields(run('qm', 'config', '9100'))
wan = dict(part.split('=', 1) for part in config.get('net0', '').split(',') if '=' in part)
if (config.get('name') != 'jeannie-sandbox-openwrt' or
config.get('description') != 'jeannie-network-sandbox-v1' or
wan.get('bridge') != 'vmbr0' or wan.get('link_down') != '1'):
raise RuntimeError('Sandbox router identity or disconnected WAN configuration changed')
if run('qm', 'status', '9100') != 'status: running':
raise RuntimeError('Sandbox router is not running')
if not (Path('/sys/class/net/vmbr0/brif') / TAP).exists():
raise RuntimeError('Sandbox WAN tap is not on vmbr0')
def install_guard():
for number, cidr in enumerate(BLOCKED, 10):
run('tc', 'filter', 'add', 'dev', TAP, 'ingress', 'protocol', 'ip',
'pref', str(number), 'flower', 'dst_ip', cidr, 'action', 'drop')
for protocol, pref in (('ip', '100'), ('arp', '101')):
run('tc', 'filter', 'add', 'dev', TAP, 'ingress', 'protocol', protocol,
'pref', pref, 'matchall', 'action', 'pass')
run('tc', 'filter', 'add', 'dev', TAP, 'ingress', 'protocol', 'all',
'pref', '102', 'matchall', 'action', 'drop')
def isolate():
# Disable the host tap first; if QMP fails the guest is still isolated.
run('ip', 'link', 'set', 'dev', TAP, 'down')
qmp(False)
def cleanup():
isolate()
if MARKER.exists():
# A marker is created before installing our qdisc. A failed qdisc
# installation must never cause deletion of someone else's qdisc.
if MARKER.read_text().strip() == 'owned':
run('tc', 'qdisc', 'del', 'dev', TAP, 'clsact')
MARKER.unlink()
def client_connect(ctid, host, port):
pid = run('lxc-info', '-n', str(ctid), '-p', '-H')
if not pid.isdigit() or int(pid) <= 1:
raise RuntimeError(f'Container {ctid} is not running')
code = ('import socket,sys\n'
'try:\n socket.create_connection((sys.argv[1],int(sys.argv[2])),timeout=3).close()\n'
'except OSError as e:\n print("CONNECT_ERROR:",e); sys.exit(1)\n'
'print("CONNECTED")\n')
result = subprocess.run(('nsenter', '-t', pid, '-n', '--', sys.executable, '-c', code,
host, str(port)), capture_output=True, text=True, timeout=8)
if result.returncode == 0 and result.stdout.strip() == 'CONNECTED':
return True, 'connected'
if result.returncode == 1 and result.stdout.startswith('CONNECT_ERROR:'):
return False, result.stdout.strip()
raise RuntimeError(f'Container {ctid} probe failed: {result.stderr.strip()[-300:]}')
def main():
if os.geteuid() != 0 or len(sys.argv) != 2 or sys.argv[1] not in ('probe', 'reset'):
print('Run as root with probe or reset', file=sys.stderr)
return 2
watchdog = None
try:
with open('/run/lock/jeannie-network-sandbox.lock', 'a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
verify_router()
if sys.argv[1] == 'reset':
cleanup()
print('Sandbox WAN isolated; temporary probe guard removed if present.')
return 0
if MARKER.exists():
raise RuntimeError('Previous probe needs cleanup: run jeannie network-sandbox wan-reset')
addresses = json.loads(run('ip', '-j', '-4', 'addr', 'show', 'dev', 'vmbr0'))
host_ip = next((a['local'] for a in addresses[0]['addr_info'] if a.get('scope') == 'global'), None)
if not host_ip:
raise RuntimeError('vmbr0 has no IPv4 address for the positive control')
try:
socket.create_connection((host_ip, 22), timeout=3).close()
except OSError as exc:
raise RuntimeError(f'Host SSH positive control failed: {exc}') from exc
fd = os.open(MARKER, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
os.close(fd)
try:
run('ip', 'link', 'set', 'dev', TAP, 'down')
run('tc', 'qdisc', 'add', 'dev', TAP, 'clsact')
MARKER.write_text('owned\n')
install_guard()
# If this process dies, the detached watchdog shuts the tap after two minutes.
watchdog = subprocess.Popen([sys.executable, '-c',
'import subprocess,time; time.sleep(120); subprocess.run(["ip","link","set","dev","tap9100i0","down"])'],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True, close_fds=True)
qmp(True)
run('ip', 'link', 'set', 'dev', TAP, 'up')
results = {}
deadline = time.monotonic() + 60
for ctid in (9110, 9111):
while True:
ok, detail = client_connect(ctid, '1.1.1.1', 443)
if ok or time.monotonic() >= deadline:
break
time.sleep(3)
if not ok:
raise RuntimeError(f'Client {ctid} internet TCP probe failed: {detail}')
reachable, detail = client_connect(ctid, host_ip, 22)
if reachable:
raise RuntimeError(f'Client {ctid} reached the host SSH port')
results[str(ctid)] = {'internet_tcp_1_1_1_1_443': 'connected',
'host_ssh': detail}
print(json.dumps({'clients': results, 'host_guard_ipv4_destinations': BLOCKED,
'note': 'Sampled TCP checks; not proof for every endpoint or protocol.'}, indent=2))
finally:
cleanup()
if watchdog:
watchdog.terminate()
watchdog.wait(timeout=5)
print('Sandbox WAN disconnected after test.')
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
print(f'Sandbox WAN probe failed: {exc}. WAN cleanup can be retried with ./jeannie network-sandbox wan-reset.', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())

View File

@ -0,0 +1,28 @@
#!/usr/bin/env python3
"""Run the temporary sandbox WAN probe on the Pimox host."""
import os
from pathlib import Path
import subprocess
import sys
def main():
if len(sys.argv) != 2 or sys.argv[1] not in ('probe', 'reset'):
return 2
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')
source = (Path(__file__).resolve().parent / 'network-sandbox-wan-host.py').read_bytes()
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 - ' + sys.argv[1]],
input=source, timeout=180).returncode
except (OSError, subprocess.SubprocessError) as exc:
print(f'Sandbox WAN request failed: {exc}', file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())

View File

@ -0,0 +1,31 @@
import importlib.util
from pathlib import Path
import unittest
from unittest.mock import patch
path = Path(__file__).resolve().parents[2] / 'scripts/network-sandbox-wan-host.py'
spec = importlib.util.spec_from_file_location('sandbox_wan_host', path)
wan = importlib.util.module_from_spec(spec)
spec.loader.exec_module(wan)
class WanGuardTest(unittest.TestCase):
def test_guard_blocks_private_ranges_before_permitting_ipv4(self):
with patch.object(wan, 'run') as run:
wan.install_guard()
calls = [call.args for call in run.call_args_list]
for cidr in wan.BLOCKED:
self.assertTrue(any('dst_ip' in c and cidr in c and 'drop' in c for c in calls))
self.assertEqual(calls[-1][-2:], ('action', 'drop'))
self.assertIn('all', calls[-1])
def test_cleanup_disables_tap_before_qmp(self):
with patch.object(wan, 'run') as run, patch.object(wan, 'qmp') as qmp:
wan.isolate()
run.assert_called_once_with('ip', 'link', 'set', 'dev', wan.TAP, 'down')
qmp.assert_called_once_with(False)
if __name__ == '__main__':
unittest.main()