my-homelab-configs/scripts/network-sandbox-guests-host.py

184 lines
8.9 KiB
Python

#!/usr/bin/env python3
"""Provision the isolated sandbox guests in the stopped state on Pimox.
The caller supplies CONFIGS and AUTHORIZED_KEY when streaming this program to
the host. Existing VM/container IDs are never adopted or overwritten.
"""
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import urllib.request
import zlib
from pathlib import Path
BASE = Path('/data/jeannie/network-sandbox')
STORAGE = BASE / 'lxc'
OPENWRT = 'openwrt-24.10.6-armsr-armv8-generic-ext4-combined-efi.img.gz'
OPENWRT_URL = 'https://downloads.openwrt.org/releases/24.10.6/targets/armsr/armv8/'
ALPINE = 'alpine-minirootfs-3.22.7-aarch64.tar.gz'
ALPINE_URL = 'https://dl-cdn.alpinelinux.org/alpine/v3.22/releases/aarch64/'
def run(*args, timeout=180):
result = subprocess.run(args, text=True, capture_output=True, timeout=timeout)
if result.returncode:
raise RuntimeError(f'{args[0]} failed: {result.stderr.strip()[-800:]}')
return result.stdout.strip()
def fetch(url, destination):
with urllib.request.urlopen(url, timeout=120) as source, destination.open('wb') as output:
shutil.copyfileobj(source, output)
def verified_download(base, name, checksum_url, directory):
target = directory / name
checksum = directory / (name + '.sha256')
fetch(base + name, target)
fetch(checksum_url, checksum)
match = re.search(r'(?m)^([0-9a-fA-F]{64})\s+[* ]?' + re.escape(name) + r'\s*$', checksum.read_text())
if not match:
raise RuntimeError(f'Official checksum not found for {name}')
digest = hashlib.sha256()
with target.open('rb') as image:
for chunk in iter(lambda: image.read(1024 * 1024), b''):
digest.update(chunk)
if digest.hexdigest() != match.group(1).lower():
raise RuntimeError(f'Checksum mismatch for {name}')
return target
def check_preconditions():
if os.geteuid() != 0:
raise RuntimeError('Host provisioning must run as root')
if run('uname', '-m') != 'aarch64':
raise RuntimeError('Sandbox images require an ARM64 host')
if run('findmnt', '-rn', '-M', '/data', '-o', 'UUID') != '19972338-9757-4f4b-89d7-c202df14a9aa':
raise RuntimeError('/data is not the expected SSD')
if 'rw' not in run('findmnt', '-rn', '-M', '/data', '-o', 'OPTIONS').split(','):
raise RuntimeError('/data is not writable')
for path in (Path('/data/jeannie'), BASE, STORAGE):
if path.is_symlink():
raise RuntimeError(f'Refusing symlink in sandbox storage path: {path}')
if not (STORAGE / '.jeannie-network-sandbox-storage').is_file():
raise RuntimeError('Sandbox storage marker missing; run network-sandbox prepare')
storage_cfg = Path('/etc/pve/storage.cfg').read_text(encoding='utf-8')
blocks = [block for block in storage_cfg.split('\n\n')
if block.splitlines() and block.splitlines()[0].strip() == 'dir: jeannie-sandbox']
if len(blocks) != 1:
raise RuntimeError('Sandbox storage configuration is absent or ambiguous')
values = dict(line.split(None, 1) for line in blocks[0].splitlines()[1:] if len(line.split(None, 1)) == 2)
if values.get('path') != str(STORAGE) or not {'rootdir', 'vztmpl'}.issubset(set(values.get('content', '').split(','))):
raise RuntimeError('Sandbox storage has unexpected path or content types')
bridge = Path('/sys/class/net/vmbr9')
if not (bridge / 'bridge').is_dir() or (bridge / 'ifalias').read_text().strip() != 'jeannie-network-sandbox':
raise RuntimeError('Sandbox bridge is absent or unmarked; run network-sandbox prepare')
if (bridge / 'bridge/vlan_filtering').read_text().strip() != '1' or list((bridge / 'brif').iterdir()):
raise RuntimeError('Sandbox bridge must be VLAN aware and empty before provisioning')
if not Path('/dev/kvm').exists():
raise RuntimeError('/dev/kvm is unavailable')
ids = {str(entry.get('vmid')) for entry in json.loads(run('pvesh', 'get', '/cluster/resources', '--type', 'vm', '--output-format', 'json'))}
occupied = ids.intersection({'9100', '9110', '9111'})
if occupied:
raise RuntimeError('Guest IDs already in use; refusing to adopt or replace: ' + ', '.join(sorted(occupied)))
image_stores = run('pvesm', 'status', '--content', 'images')
if not any(line.split() and line.split()[0] == 'opi5_ssd' and 'active' in line.split() for line in image_stores.splitlines()):
raise RuntimeError('opi5_ssd is not available for the OpenWrt VM disk')
def extract_openwrt_image(archive, image):
"""Extract the verified gzip member; OpenWrt may append image metadata."""
decoder = zlib.decompressobj(16 + zlib.MAX_WBITS)
with archive.open('rb') as source, image.open('wb') as dest:
while not decoder.eof:
chunk = source.read(1024 * 1024)
if not chunk:
raise RuntimeError('OpenWrt gzip stream is truncated')
while chunk and not decoder.eof:
dest.write(decoder.decompress(chunk, 1024 * 1024))
chunk = decoder.unconsumed_tail
def write_router_image(archive, work):
image = work / 'openwrt.img'
extract_openwrt_image(archive, image)
loop = run('losetup', '--find', '--partscan', '--show', str(image))
mountpoint = work / 'root'
mountpoint.mkdir()
mounted = False
try:
partition = Path(loop + 'p2')
if not partition.exists():
raise RuntimeError('OpenWrt root partition did not appear')
run('mount', str(partition), str(mountpoint))
mounted = True
config_dir = mountpoint / 'etc/config'
if not config_dir.is_dir():
raise RuntimeError('OpenWrt image lacks /etc/config')
for name in ('network', 'dhcp', 'firewall'):
(config_dir / name).write_text(CONFIGS[name], encoding='utf-8')
if AUTHORIZED_KEY:
keys = mountpoint / 'etc/dropbear'
keys.mkdir(parents=True, exist_ok=True)
(keys / 'authorized_keys').write_text(AUTHORIZED_KEY.rstrip() + '\n', encoding='utf-8')
(keys / 'authorized_keys').chmod(0o600)
run('sync')
finally:
if mounted:
run('umount', str(mountpoint))
run('losetup', '-d', loop)
return image
def main():
try:
check_preconditions()
BASE.mkdir(parents=True, exist_ok=True)
work = Path(tempfile.mkdtemp(prefix='guest-provision-', dir=str(BASE)))
print(f'Preparing verified guest images in {work}', flush=True)
archive = verified_download(OPENWRT_URL, OPENWRT, OPENWRT_URL + 'sha256sums', work)
alpine = verified_download(ALPINE_URL, ALPINE, ALPINE_URL + ALPINE + '.sha256', work)
image = write_router_image(archive, work)
template_dir = STORAGE / 'template/cache'
template_dir.mkdir(parents=True, exist_ok=True)
template_name = 'alpine-3.22-default_3.22.7_arm64.tar.gz'
template = template_dir / template_name
if template.exists():
raise RuntimeError(f'Template already exists; refusing overwrite: {template}')
shutil.copyfile(alpine, template)
run('qm', 'create', '9100', '--name', 'jeannie-sandbox-openwrt',
'--description', 'jeannie-network-sandbox-v1', '--bios', 'ovmf',
'--cores', '2', '--memory', '512', '--onboot', '0',
'--net0', 'virtio,bridge=vmbr0,link_down=1',
'--net1', 'virtio,bridge=vmbr9,trunks=10;20',
'--ostype', 'l26', '--scsihw', 'virtio-scsi-pci', '--serial0', 'socket')
run('qm', 'set', '9100', '--efidisk0', 'opi5_ssd:1,efitype=4m,pre-enrolled-keys=0')
run('qm', 'importdisk', '9100', str(image), 'opi5_ssd', '--format', 'raw', timeout=900)
cfg = run('qm', 'config', '9100')
match = re.search(r'^unused\d+:\s*(\S+)', cfg, re.MULTILINE)
if not match:
raise RuntimeError('Imported VM disk was not found')
run('qm', 'set', '9100', '--scsi0', match.group(1), '--boot', 'order=scsi0')
for ctid, vlan in ((9110, 10), (9111, 20)):
run('pct', 'create', str(ctid), f'jeannie-sandbox:vztmpl/{template_name}',
'--hostname', f'jeannie-sandbox-client-{vlan}', '--arch', 'arm64',
'--unprivileged', '1', '--cores', '1', '--memory', '256', '--swap', '0',
'--rootfs', 'jeannie-sandbox:2', '--onboot', '0',
'--net0', f'name=eth0,bridge=vmbr9,tag={vlan},ip=dhcp', timeout=600)
print('Created stopped OpenWrt VM 9100 and stopped Alpine containers 9110 and 9111.')
print('WAN remains disconnected. Guests were not started; runtime guard was not changed.')
print(f'Provisioning files retained at {work}')
except (OSError, RuntimeError, KeyError, ValueError, zlib.error, subprocess.SubprocessError) as exc:
print(f'Sandbox guest provisioning failed: {exc}. Existing and partially created resources were preserved.', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())