#!/usr/bin/env python3 """Prepare immutable epoch assets and an isolated pair of network namespaces.""" from __future__ import annotations import argparse import ipaddress import json import os from pathlib import Path import re import shutil import subprocess import urllib.parse from common import atomic_json, file_sha256, read_json from serve import ReplayState def command(*args: str) -> None: subprocess.run(args, check=True, timeout=30, capture_output=True, text=True) def all_hosts(root: Path, extra_hosts: list[str] | None = None) -> list[str]: hosts = set() def add(uri): url = urllib.parse.urlsplit(uri) host = url.hostname if not host: raise ValueError(f"missing host: {uri}") host = host.encode("idna").decode("ascii").lower() if ":" in host: raise ValueError("IPv6 literal URI requires an explicit additional replay mapping") if not re.fullmatch(r"[a-z0-9.-]+", host): raise ValueError(f"unsafe hostname: {host}") hosts.add(host) for host in extra_hosts or []: add("https://" + host + "/") if (root / "registry.json").exists(): for uri in read_json(root / "registry.json"): add(uri) for path in (root / "events").glob("*.json"): add(read_json(path)["uri"]) for path in (root / "observations").glob("*.json"): for ref in read_json(path).get("references", []): add(ref["uri"]) if len(hosts) > 1000: raise ValueError("host mapping count bound") return sorted(hosts) def host_mapping(hosts: list[str]) -> dict[str, str]: result = {} for index, host in enumerate(hosts, 1): try: address = ipaddress.ip_address(host) if address.version != 4 or address.is_loopback or address.is_unspecified or address.is_multicast: raise ValueError("unsupported literal origin address") result[host] = str(address) except ValueError as exc: if re.fullmatch(r"[0-9.]+", host): raise ValueError(f"invalid/unsupported literal address: {host}") from exc result[host] = str(ipaddress.ip_address("10.187.1.0") + index) return result def tls_assets(output: Path, hosts: list[str]) -> dict: tls = output / "tls" tls.mkdir(parents=True, exist_ok=True) host_file = tls / "hosts.json" if host_file.exists(): if read_json(host_file) != hosts: raise ValueError("archive hosts changed after TLS freeze; use a new replay root") return {"ca": str(tls / "ca.pem"), "cert": str(tls / "server.pem"), "key": str(tls / "server.key")} if any(tls.iterdir()): raise ValueError("partial TLS setup exists; inspect it before retrying") san = [] for host in hosts: try: ipaddress.ip_address(host) san.append("IP:" + host) except ValueError: san.append("DNS:" + host) ext = tls / "server.ext" ext.write_text("basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\nsubjectAltName=" + ",".join(san) + "\n") command("openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", str(tls / "ca.key"), "-out", str(tls / "ca.pem"), "-days", "30", "-subj", "/CN=RPKI-187 transport experiment CA", "-addext", "basicConstraints=critical,CA:TRUE", "-addext", "keyUsage=critical,keyCertSign,cRLSign") command("openssl", "req", "-new", "-newkey", "rsa:2048", "-nodes", "-keyout", str(tls / "server.key"), "-out", str(tls / "server.csr"), "-subj", "/CN=RPKI-187 replay") command("openssl", "x509", "-req", "-in", str(tls / "server.csr"), "-CA", str(tls / "ca.pem"), "-CAkey", str(tls / "ca.key"), "-CAcreateserial", "-out", str(tls / "server.pem"), "-days", "30", "-extfile", str(ext)) for key in (tls / "ca.key", tls / "server.key"): key.chmod(0o600) atomic_json(host_file, hosts) return {"ca": str(tls / "ca.pem"), "cert": str(tls / "server.pem"), "key": str(tls / "server.key")} def rsync_tree(state: ReplayState, output: Path, mapping: dict) -> list[str]: views, origins = {}, {} for event in sorted(state.rsync_events, key=lambda e: e["completed_ms"]): parsed_scope = urllib.parse.urlsplit(event["uri"]) scope_parts = parsed_scope.path.lstrip("/").split("/") module = scope_parts[0] if module in ("", ".", "..") or not re.fullmatch(r"[a-zA-Z0-9_.-]+", module): raise ValueError("unsafe/missing rsync scope module") key = (parsed_scope.hostname.lower(), parsed_scope.port or 873) origins.setdefault(key, set()).add(module) (output / f"{key[0]}-{key[1]}" / "modules" / module).mkdir(parents=True, exist_ok=True) if event["kind"] == "view": for uri in list(views): if uri.startswith(event["uri"]): del views[uri] views.update(event["objects"]) for uri, ref in views.items(): parsed = urllib.parse.urlsplit(uri) parts = parsed.path.lstrip("/").split("/") if parsed.scheme != "rsync" or parsed.username or parsed.password or parsed.query or parsed.fragment: raise ValueError("invalid rsync object origin") if len(parts) < 2 or any(p in ("", ".", "..") or "\x00" in p or "\\" in p for p in parts): raise ValueError(f"unsafe rsync publication path: {uri}") hostname, port = parsed.hostname.lower(), parsed.port or 873 key = (hostname, port) root = output / f"{hostname}-{port}" module = parts[0] if not re.fullmatch(r"[a-zA-Z0-9_.-]+", module): raise ValueError("unsafe rsync module name") path = root / "modules" / Path(*parts) path.parent.mkdir(parents=True, exist_ok=True) source = state.archive.blob_path(ref["sha256"]) if source.stat().st_size != ref["size"]: raise ValueError("rsync blob size mismatch") if not path.exists(): # A hard link followed by chmod also changes the archived inode. shutil.copyfile(source, path) path.chmod(0o444) origins.setdefault(key, set()).add(module) configs = [] for (hostname, port), modules in origins.items(): root = output / f"{hostname}-{port}" config = root / "rsyncd.conf" lines = [f"address = {mapping[hostname]}", f"port = {port}", "use chroot = no", "read only = yes", "uid = 65534", "gid = 65534", f"pid file = {root}/rsyncd.pid", f"lock file = {root}/rsyncd.lock", f"log file = {root}/rsyncd.log", "max connections = 16"] for module in sorted(modules): lines += [f"[{module}]", f"path = {root}/modules/{module}"] config.write_text("\n".join(lines) + "\n") configs.append(str(config)) return configs def create_network(mapping: dict) -> None: existing = subprocess.run(["ip", "netns", "list"], capture_output=True, text=True, check=True, timeout=10).stdout names = {line.split()[0] for line in existing.splitlines() if line} if names.intersection({"rp187srv", "rp187rp"}) or Path("/etc/netns/rp187rp").exists(): raise ValueError("experiment namespace/name already exists; inspect before replacing") created = [] try: for name in ("rp187srv", "rp187rp"): command("ip", "netns", "add", name) created.append(name) command("ip", "-n", "rp187srv", "link", "add", "r187s", "type", "veth", "peer", "name", "r187r", "netns", "rp187rp") for name, dev, address in (("rp187srv", "r187s", "10.187.0.1/16"), ("rp187rp", "r187r", "10.187.0.2/16")): command("ip", "-n", name, "addr", "add", address, "dev", dev) command("ip", "-n", name, "link", "set", dev, "up") command("ip", "-n", name, "link", "set", "lo", "up") for address in sorted(set(mapping.values())): if address in ("10.187.0.1", "10.187.0.2"): raise ValueError("literal origin collides with namespace gateway") command("ip", "-n", "rp187srv", "addr", "add", address + "/32", "dev", "lo") if ipaddress.ip_address(address) not in ipaddress.ip_network("10.187.0.0/16"): command("ip", "-n", "rp187rp", "route", "add", address + "/32", "via", "10.187.0.1") folder = Path("/etc/netns/rp187rp") folder.mkdir(parents=True) (folder / "hosts").write_text("127.0.0.1 localhost\n" + "".join(f"{address} {host}\n" for host, address in sorted(mapping.items()))) (folder / "resolv.conf").write_text("nameserver 127.0.0.1\noptions timeout:1 attempts:1\n") except Exception: for name in reversed(created): subprocess.run(["ip", "netns", "delete", name], capture_output=True, timeout=10) if created and Path("/etc/netns/rp187rp").exists(): shutil.rmtree("/etc/netns/rp187rp") raise def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--archive", type=Path, required=True) parser.add_argument("--epoch", type=Path, required=True) parser.add_argument("--scope", type=Path) parser.add_argument("--bundle-manifest", type=Path) parser.add_argument("--bundle-sha256") parser.add_argument("--out", type=Path, required=True) parser.add_argument("--create-network", action="store_true") args = parser.parse_args() if args.scope: from scope import require_closure require_closure(args.archive, args.scope) state = ReplayState(args.archive, args.epoch, args.scope, args.bundle_manifest, args.bundle_sha256) if args.bundle_manifest: from replay_bundle import load_manifest bundle = load_manifest(args.bundle_manifest, args.bundle_sha256) hosts = all_hosts(args.archive, bundle["origin_hosts"]) else: hosts = all_hosts(args.archive) mapping = host_mapping(hosts) args.out.mkdir(parents=True, exist_ok=True) tls = tls_assets(args.out, hosts) epoch_root = args.out / state.epoch_hash if epoch_root.exists(): raise ValueError("epoch assets already exist; reuse their manifest or choose a new output") epoch_root.mkdir() configs = rsync_tree(state, epoch_root / "rsync", mapping) http_ports = sorted({key[2] for key in state.entries if key[0] == "http"}) https_ports = sorted({key[2] for key in state.entries if key[0] == "https"}) http_ports = sorted(set(http_ports) | {key[2] for key in state.failures if key[0] == "http"}) https_ports = sorted(set(https_ports) | {key[2] for key in state.failures if key[0] == "https"}) if set(http_ports).intersection(https_ports): raise ValueError("HTTP and HTTPS share a port; explicit origin-specific listeners required") manifest = {"epoch": state.epoch_hash, "archive": str(args.archive), "epoch_path": str(args.epoch), "hosts": mapping, "tls": tls, "rsync_configs": configs, "http_ports": http_ports, "https_ports": https_ports, "server_namespace": "rp187srv", "rp_namespace": "rp187rp", "server_cpus": "0", "rp_cpus": "1-3"} if args.scope: manifest.update(scope_path=str(args.scope.resolve()), scope_sha256=file_sha256(args.scope)) if args.bundle_manifest: manifest.update(bundle_manifest=str(args.bundle_manifest.resolve()), bundle_sha256=args.bundle_sha256) atomic_json(epoch_root / "replay.json", manifest) if args.create_network: create_network(mapping) print(json.dumps(manifest)) if __name__ == "__main__": main()