Add sandbox packet capture reports
Homelab Main / validate (push) Has been cancelled Details
Homelab Main / running-update (push) Has been cancelled Details
Homelab Main / debian-ops (push) Has been cancelled Details

This commit is contained in:
juvenal.diaz 2026-11-06 23:45:31 -06:00
parent 22cb1fd01e
commit 16053cc9f3
5 changed files with 267 additions and 3 deletions

View File

@ -55,6 +55,20 @@ 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.
`./jeannie network-sandbox capture vlan10` captures traffic while the full
isolation suite runs. Choose `vlan10`, `vlan20`, `trunk`, or `wan`; the WAN
choice observes only the sandbox router tap. The Orange Pi must have `tshark`
installed. Captures stop after the suite, 180 seconds, or approximately 20 MiB,
whichever comes first; reaching a limit before the suite ends is reported as an
incomplete capture. Jeannie reports the paths to `traffic.pcapng`, a text
summary with protocol, IPv4 conversation, DNS and TCP retransmission sections,
and capture diagnostics. They are stored in a root-only directory on the
sandbox SSD under `/data/jeannie/network-sandbox/captures/`. Open the capture
in Wireshark after copying it securely if detailed inspection is needed.
Packet captures and reports can contain sensitive traffic: keep them private
and do not commit them. A missing response alone does not identify the
firewall rule that handled a packet.
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.

12
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|isolation-tests|wan-probe|wan-reset} Manage the independent network lab.
network-sandbox {plan|prepare|provision|start|stop|verify|isolation-tests|wan-probe|wan-reset|capture} 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|isolation-tests|wan-probe|wan-reset}" >&2; exit 2; }
[[ $# -le 2 || ( $# -eq 3 && "${2:-}" == capture ) ]] || { echo "Usage: ./jeannie network-sandbox capture {vlan10|vlan20|trunk|wan}" >&2; exit 2; }
case "${2:-plan}" in
plan) python3 "${REPO_ROOT}/scripts/network-sandbox-plan.py" ;;
prepare|provision|start)
@ -830,6 +830,12 @@ case "${1:-}" in
python3 "${REPO_ROOT}/scripts/network-sandbox-isolation.py" || exit 1
python3 "${REPO_ROOT}/scripts/network-sandbox-wan.py" probe
;;
capture)
[[ $# -eq 3 ]] || { echo "Usage: ./jeannie network-sandbox capture {vlan10|vlan20|trunk|wan}" >&2; exit 2; }
record_change_journal "network-sandbox" "$@"
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_capture.py' || exit 1
python3 "${REPO_ROOT}/scripts/network-sandbox-capture.py" "$3"
;;
wan-probe)
record_change_journal "network-sandbox" "$@"
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_wan.py' || exit 1
@ -841,7 +847,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|isolation-tests|wan-probe|wan-reset}" >&2; exit 2 ;;
*) echo "Usage: ./jeannie network-sandbox {plan|prepare|provision|start|stop|verify|isolation-tests|wan-probe|wan-reset|capture}" >&2; exit 2 ;;
esac
;;
nuke)

View File

@ -0,0 +1,139 @@
#!/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())

View File

@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""Capture sandbox traffic while running Jeannie's isolation exercises."""
import base64
import json
import os
from pathlib import Path
import select
import subprocess
import sys
POINTS = ('vlan10', 'vlan20', 'trunk', 'wan')
def main():
if len(sys.argv) != 2 or sys.argv[1] not in POINTS:
print('Choose capture point: vlan10, vlan20, trunk, or wan', file=sys.stderr)
return 2
root = Path(__file__).resolve().parent.parent
source = (root / 'scripts/network-sandbox-capture-host.py').read_bytes()
encoded = base64.b64encode(source).decode('ascii')
remote = f"sudo -n python3 -c 'exec(__import__(\"base64\").b64decode(\"{encoded}\"))' {sys.argv[1]}"
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')
process = None
try:
process = subprocess.Popen(['ssh', '-T', '-i', key, '-o', 'BatchMode=yes',
'-o', 'IdentitiesOnly=yes', '-o', 'ConnectTimeout=10',
'-o', 'StrictHostKeyChecking=accept-new', f'{user}@{host}', remote],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
ready, _, _ = select.select([process.stdout], [], [], 30)
if not ready:
raise RuntimeError('Timed out waiting for capture startup')
line = process.stdout.readline()
if not line:
raise RuntimeError('Capture did not start; see the error above')
info = json.loads(line)
if not info.get('capture_ready'):
raise RuntimeError('Capture startup response was invalid')
print(json.dumps(info), flush=True)
suite = subprocess.run([str(root / 'jeannie'), 'network-sandbox', 'isolation-tests'], timeout=180)
try:
process.stdin.write('stop\n')
process.stdin.flush()
except BrokenPipeError:
pass
output, _ = process.communicate(timeout=150)
if output:
print(output, end='', flush=True)
return int(suite.returncode != 0 or process.returncode != 0)
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
print(f'Sandbox capture failed: {exc}', file=sys.stderr)
return 1
finally:
if process and process.poll() is None:
if process.stdin:
process.stdin.close()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
if __name__ == '__main__':
sys.exit(main())

View File

@ -0,0 +1,35 @@
import importlib.util
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
path = Path(__file__).resolve().parents[2] / 'scripts/network-sandbox-capture-host.py'
spec = importlib.util.spec_from_file_location('sandbox_capture_host', path)
capture = importlib.util.module_from_spec(spec)
spec.loader.exec_module(capture)
class SandboxCaptureTest(unittest.TestCase):
def test_only_dedicated_interfaces_are_allowed(self):
self.assertEqual(capture.PORTS, {'vlan10': ('veth9110i0', 'vmbr9'),
'vlan20': ('veth9111i0', 'vmbr9'),
'trunk': ('tap9100i1', 'vmbr9'),
'wan': ('tap9100i0', 'vmbr0')})
def test_report_marks_failed_sections(self):
success = subprocess.CompletedProcess([], 0, stdout='packets\n', stderr='')
failure = subprocess.CompletedProcess([], 1, stdout='', stderr='filter unavailable')
with tempfile.TemporaryDirectory() as directory, \
patch.object(capture.subprocess, 'run', side_effect=[success, failure, success]):
path = Path(directory) / 'report.txt'
warnings = capture.report('tshark', Path(directory) / 'traffic.pcapng', path, 'vlan10', 'stopped')
self.assertEqual(warnings, ['DNS queries and responses'])
self.assertIn('filter unavailable', path.read_text())
def test_unexpected_filesystem_is_rejected(self):
result = subprocess.CompletedProcess([], 0, stdout='wrong-uuid rw,relatime\n', stderr='')
with patch.object(capture.subprocess, 'run', return_value=result):
with self.assertRaises(RuntimeError):
capture.storage_root()