71 lines
2.8 KiB
Python
71 lines
2.8 KiB
Python
#!/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())
|