#!/usr/bin/env python3 """Exercise every selected HTTP entity over local verified TLS, plus native rsync. Uses loopback and temporary assets only: no RP, network namespace, live origin, system service change or performance measurement. URI Host/SNI remains original. """ from __future__ import annotations import argparse import hashlib from http.client import HTTPResponse from http.server import ThreadingHTTPServer import json import os from pathlib import Path import socket import ssl import subprocess import tempfile import threading import time from urllib.parse import urlsplit from common import file_sha256, read_json from prepare_replay import all_hosts, rsync_tree, tls_assets from replay_bundle import load_manifest from serve import ReplayState, handler_for def verify_server(root: Path, manifest_path: Path, expected_sha256: str) -> dict: manifest = load_manifest(manifest_path, expected_sha256) steps = [] with tempfile.TemporaryDirectory(prefix="rpki188-bundle-service-") as tmp: assets = Path(tmp) assets.chmod(0o755) tls = tls_assets(assets, all_hosts(root / "archive", manifest["origin_hosts"])) context = ssl.create_default_context(cafile=tls["ca"]) for selection in manifest["epochs"]: state = ReplayState(root / "archive", root / "archive" / selection["path"], root / "config/scope.json", manifest_path, expected_sha256) entities, bytes_checked, failures_checked = 0, 0, 0 for scheme in ("http", "https"): rows = [r for r in selection["http_entities"] if urlsplit(r["uri"]).scheme == scheme] for key, status in state.failures.items(): protocol, host, port, path, query = key if protocol == scheme: rows.append({"uri": f"{protocol}://{host}:{port}{path}" + ("?" + query if query else ""), "expected_status": status, "bytes": 0}) if not rows: continue server = ThreadingHTTPServer(("127.0.0.1", 0), handler_for(state, scheme)) if scheme == "https": server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) server_context.load_cert_chain(tls["cert"], tls["key"]) server.socket = server_context.wrap_socket(server.socket, server_side=True) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() try: for row in rows: uri = urlsplit(row["uri"]) sock = socket.create_connection(server.server_address, timeout=30) if scheme == "https": sock = context.wrap_socket(sock, server_hostname=uri.hostname) with sock: target = (uri.path or "/") + (("?" + uri.query) if uri.query else "") sock.sendall(f"GET {target} HTTP/1.1\r\nHost: {uri.netloc}\r\nConnection: close\r\n\r\n".encode("ascii")) response = HTTPResponse(sock) response.begin() if response.status != row.get("expected_status", 200): raise ValueError(f"entity fetch failed: {response.status} {row['uri']}") digest, size = hashlib.sha256(), 0 while chunk := response.read(1024 * 1024): digest.update(chunk) size += len(chunk) if size != row["bytes"] or (response.status == 200 and digest.hexdigest() != row["sha256"]): raise ValueError("served bytes differ from pinned entity") if response.status == 200: entities += 1 else: failures_checked += 1 bytes_checked += size finally: server.shutdown() server.server_close() thread.join(timeout=10) rsync_count = 0 if state.rsync_events: configs = rsync_tree(state, assets / f"rsync-{selection['step']}", {urlsplit(e["uri"]).hostname: "127.0.0.1" for e in state.rsync_events}) for index, original in enumerate(configs): original = Path(original) with socket.socket() as probe: probe.bind(("127.0.0.1", 0)) port = probe.getsockname()[1] config = original.with_name("loopback.conf") lines = original.read_text().splitlines() lines = [f"port = {port}" if line.startswith("port = ") else line for line in lines] # A non-root loopback verifier must inherit its uid/groups; # explicit gid makes rsync call privileged setgroups(). # Production prepared configs still use uid/gid 65534. if os.geteuid() != 0: lines = [line for line in lines if not line.startswith(("uid = ", "gid = "))] config.write_text("\n".join(lines) + "\n") process = subprocess.Popen(["rsync", "--daemon", "--no-detach", "--config", str(config)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) try: deadline = time.monotonic() + 10 while True: if process.poll() is not None: raise RuntimeError(process.stderr.read().decode()) try: with socket.create_connection(("127.0.0.1", port), timeout=1): break except OSError: if time.monotonic() >= deadline: raise time.sleep(.05) modules = original.parent / "modules" for module in modules.iterdir(): target = assets / f"fetched-{selection['step']}-{index}" / module.name target.mkdir(parents=True) transfer = subprocess.run(["rsync", "-r", f"rsync://127.0.0.1:{port}/{module.name}/", str(target)], capture_output=True, timeout=60) if transfer.returncode: raise RuntimeError("loopback rsync failed: " + transfer.stderr.decode(errors="replace")) expected = {str(p.relative_to(module)): file_sha256(p) for p in module.rglob("*") if p.is_file()} actual = {str(p.relative_to(target)): file_sha256(p) for p in target.rglob("*") if p.is_file()} if expected != actual: raise ValueError("native rsync file contents differ") rsync_count += len(actual) finally: process.terminate() process.wait(timeout=10) process.stderr.close() steps.append({"step": selection["step"], "http_entities": entities, "controlled_failures_checked": failures_checked, "served_body_bytes": bytes_checked, "native_rsync_files": rsync_count, "pass": True}) return {"pass": True, "manifest_sha256": expected_sha256, "steps": steps, "https": "local CA chain and original-hostname SNI verification enabled", "new_rp_executions": 0, "performance_measurement": False} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, required=True) parser.add_argument("--manifest", type=Path, required=True) parser.add_argument("--expected-sha256", required=True) args = parser.parse_args() print(json.dumps(verify_server(args.root, args.manifest, args.expected_sha256))) if __name__ == "__main__": main()