Files
NODEDC_MISSION_CORE/scripts/qualify_vps_clean_host.py
T

340 lines
14 KiB
Python

#!/usr/bin/env python3
"""Owned server-only clean Ubuntu userspace acceptance in private namespaces.
Requires an official SHA256-verified Ubuntu Server 24.04 root tar and the shipped
installer. Does not install packages on the host or share its network/services.
This qualifies clean userspace, not a provider firewall or a different kernel.
"""
import argparse
import hashlib
import json
import os
import shutil
import subprocess
import tarfile
import time
from pathlib import Path
def run(*argv, **kwargs):
return subprocess.run(argv, check=True, capture_output=True, text=True, **kwargs)
def main():
p = argparse.ArgumentParser()
p.add_argument("--stage", type=Path, required=True)
p.add_argument("--installer", type=Path, required=True)
p.add_argument("--image-sha256", required=True)
p.add_argument("--client", type=Path, required=True)
p.add_argument("--reuse-uninstalled-image", action="store_true")
mode = p.add_mutually_exclusive_group()
mode.add_argument("--migration-export", action="store_true")
mode.add_argument("--migration-import", type=Path)
p.add_argument("--state-sha256")
p.add_argument("--client-credentials", type=Path)
args = p.parse_args()
stage = args.stage.resolve()
if (
os.geteuid() != 0
or stage.parent != Path("/tmp")
or not stage.name.startswith("ndc-vps-clean-")
):
raise ValueError("root and an owned temporary stage required")
os.umask(0o077)
image = stage / "ubuntu-24.04-server-cloudimg-amd64-root.tar.xz"
with image.open("rb") as f:
if hashlib.file_digest(f, "sha256").hexdigest() != args.image_sha256:
raise ValueError("image digest mismatch")
root = stage / "rootfs"
if not args.reuse_uninstalled_image:
if shutil.disk_usage(stage).free < 2 * 1024**3:
raise ValueError("insufficient bounded staging disk")
root.mkdir(mode=0o755)
with tarfile.open(image) as tar:
for member in tar:
if member.name.startswith("/") or ".." in Path(member.name).parts:
raise ValueError("unsafe image path")
run("tar", "-xJf", str(image), "-C", str(root), timeout=120)
elif not root.is_dir():
raise ValueError("uninstalled image root missing")
# The enclosing evidence stage is private, but the guest's / must be
# traversable by its own service accounts. Tar may omit a root entry.
root.chmod(0o755)
assert not (root / "opt/nodedc-mission-vps").exists()
assert not (root / "var/lib/ndc-mission-vps").exists()
shutil.copyfile(args.installer, root / "installer.pyz")
shutil.copyfile(args.client, root / "acceptance-client.py")
if args.migration_import:
shutil.copyfile(args.migration_import, root / "portable-state.tar.gz")
shutil.copyfile(args.client_credentials, root / "acceptance-client.json")
# The following is the container substrate only. Product services, firewall,
# credentials, accounts and application paths are exclusively installer-owned.
script = stage / "init.sh"
script.write_text("""#!/bin/sh
set -eux
mount --make-rprivate /
R="$1"
mount --bind "$R" "$R"
mount -t proc proc "$R/proc"
mount -t sysfs sysfs "$R/sys"
mount -t cgroup2 cgroup2 "$R/sys/fs/cgroup"
mount -t tmpfs -o mode=755 tmpfs "$R/run"
mount -t tmpfs -o mode=755 tmpfs "$R/dev"
touch "$R/dev/console"
mount --bind "$2" "$R/dev/console"
for node in null zero random urandom tty; do
touch "$R/dev/$node"
mount --bind "/dev/$node" "$R/dev/$node"
done
mkdir -p "$R/dev/pts" "$R/dev/shm"
mount -t devpts devpts "$R/dev/pts"
mount -t tmpfs tmpfs "$R/dev/shm"
ln -s /proc/self/fd "$R/dev/fd"
ip link set lo up
hostname ndc-vps-clean
mkdir -p "$R/.old-root"
cd "$R"
pivot_root . .old-root
cd /
umount -l /.old-root
rmdir /.old-root
exec env container=other SYSTEMD_LOG_TARGET=console SYSTEMD_LOG_LEVEL=debug /sbin/init
""")
script.chmod(0o700)
unit = stage.name[:90]
results = {
"utc": time.time(),
"monotonic": time.monotonic(),
"image_sha256": args.image_sha256,
"installer_sha256": hashlib.sha256(args.installer.read_bytes()).hexdigest(),
"scope": "isolated clean Ubuntu userspace; host kernel shared",
}
try:
run(
"systemd-run",
"--quiet",
"--collect",
"--unit",
unit,
"--property=MemoryMax=256M",
"--property=CPUQuota=35%",
"--property=TasksMax=160",
"--property=TimeoutStopSec=5s",
"--property=RuntimeMaxSec=900",
"--property=Delegate=yes",
"--property=StandardOutput=append:" + str(stage / "console.log"),
"--property=StandardError=append:" + str(stage / "console.log"),
"--service-type=exec",
"unshare",
"--mount",
"--pid",
"--fork",
"--kill-child",
"--uts",
"--ipc",
"--net",
"--cgroup",
str(script),
str(root),
str(stage / "console.log"),
)
pid = None
for _ in range(30):
parent = run("systemctl", "show", unit, "--property=MainPID", "--value").stdout.strip()
if parent != "0":
children = Path(f"/proc/{parent}/task/{parent}/children").read_text().split()
if children:
candidate = children[0]
if Path(f"/proc/{candidate}/comm").read_text().strip() == "systemd":
pid = candidate
break
time.sleep(1)
if pid is None:
raise ValueError("isolated systemd did not start")
for namespace in ("mnt", "net", "pid", "uts", "ipc", "cgroup"):
assert os.readlink(f"/proc/{pid}/ns/{namespace}") != os.readlink(
f"/proc/1/ns/{namespace}"
), namespace
def inside(*command, timeout=120):
return run(
"nsenter",
"--target",
pid,
"--mount",
"--uts",
"--ipc",
"--net",
"--pid",
"--cgroup",
"--root",
"--wd",
*command,
timeout=timeout,
)
# Real host OS release, Python and product installation with no apt/pip.
results["os"] = inside("cat", "/etc/os-release").stdout
# A stock cloud image waits for a provider NIC during its first boot.
# This isolated guest deliberately has only loopback; let that existing
# OS wait expire before timing the product installer.
print(json.dumps({"phase": "waiting_for_guest_boot", "utc": time.time()}), flush=True)
for _ in range(90):
jobs = inside("systemctl", "list-jobs", "--no-pager", "--no-legend").stdout
if not jobs.strip():
break
time.sleep(2)
(stage / "boot-jobs.log").write_text(jobs)
print(json.dumps({"phase": "install", "utc": time.time()}), flush=True)
if args.migration_import:
result = inside(
"python3",
"/installer.pyz",
"--import-state",
"/portable-state.tar.gz",
"--sha256",
args.state_sha256,
timeout=240,
)
(stage / "import.stdout").write_text(result.stdout)
results["import"] = json.loads(
inside("python3", "/acceptance-client.py", "check").stdout
)
results["service"] = inside("systemctl", "is-active", "ndc-mission-vps").stdout.strip()
results["enabled"] = inside("systemctl", "is-enabled", "ndc-mission-vps").stdout.strip()
state = root / "var/lib/ndc-mission-vps"
with tarfile.open(args.migration_import) as archive:
for name in ("host.json", "tls.key", "tls.crt", "connect.key"):
assert (
archive.extractfile("state/" + name).read() == (state / name).read_bytes()
)
results["restored_identity_exact"] = True
results["listeners"] = inside("ss", "-lnt").stdout
assert ":19443" in results["listeners"] and ":9922" in results["listeners"]
inside("systemctl", "restart", "ndc-mission-vps")
inside("python3", "/installer.pyz", "--host", "trackers.example.test")
inside("python3", "/acceptance-client.py", "check")
results.update(status="passed", restored_restart_accepted=True)
print(json.dumps(results), flush=True)
return
result = inside("python3", "/installer.pyz", "--host", "trackers.example.test", timeout=240)
(stage / "install.stdout").write_text(result.stdout)
results["service"] = inside("systemctl", "is-active", "ndc-mission-vps").stdout.strip()
results["enabled"] = inside("systemctl", "is-enabled", "ndc-mission-vps").stdout.strip()
results["pairing"] = json.loads(inside("python3", "/acceptance-client.py", "seed").stdout)
before = {
name: hashlib.sha256((root / "var/lib/ndc-mission-vps" / name).read_bytes()).hexdigest()
for name in ("host.json", "tls.crt", "tls.key", "connect.key")
}
result = inside("python3", "/installer.pyz", "--host", "trackers.example.test")
(stage / "repeat.stdout").write_text(result.stdout)
assert "already_current" in result.stdout
after = {
name: hashlib.sha256((root / "var/lib/ndc-mission-vps" / name).read_bytes()).hexdigest()
for name in before
}
assert before == after
results["repeat_preserves_identity"] = True
results["listeners"] = inside("ss", "-lnt").stdout
assert ":19443" in results["listeners"] and ":9922" in results["listeners"]
inside("systemctl", "restart", "ndc-mission-vps")
inside("python3", "/installer.pyz", "--host", "trackers.example.test")
inside("python3", "/acceptance-client.py", "check")
results["restart_accepted"] = True
result = inside("python3", "/installer.pyz", "--host", "trackers.example.test", "--fresh")
(stage / "fresh.stdout").write_text(result.stdout)
backups = list((root / "var/backups/ndc-mission-vps").glob("*/backup.json"))
assert len(backups) == 1
assert (
hashlib.sha256((root / "var/lib/ndc-mission-vps/tls.crt").read_bytes()).hexdigest()
!= before["tls.crt"]
)
backup = "/" + str(backups[0].parent.relative_to(root))
result = inside(
"python3", "/installer.pyz", "--host", "trackers.example.test", "--restore", backup
)
(stage / "restore.stdout").write_text(result.stdout)
for name, digest in before.items():
assert (
hashlib.sha256((root / "var/lib/ndc-mission-vps" / name).read_bytes()).hexdigest()
== digest
)
results["restore"] = json.loads(inside("python3", "/acceptance-client.py", "check").stdout)
results["restore_identity_exact"] = True
if args.migration_export:
result = inside("python3", "/installer.pyz", "--export-state", "/portable-state.tar.gz")
(stage / "export.stdout").write_text(result.stdout)
receipt = json.loads(result.stdout)
assert receipt["status"] == "source_fenced"
inside("systemctl", "start", "ndc-mission-vps")
state = inside(
"systemctl", "show", "ndc-mission-vps", "--property=ActiveState", "--value"
)
assert state.stdout.strip() == "inactive"
# A subsequent installer must not bypass the persistent fence.
try:
inside("python3", "/installer.pyz", "--host", "trackers.example.test")
except subprocess.CalledProcessError:
pass
else:
raise AssertionError("normal installer bypassed source fencing")
results["source_fence_blocks_restart_and_install"] = True
shutil.copyfile(root / "portable-state.tar.gz", stage / "portable-state.private.tar.gz")
shutil.copyfile(
root / "acceptance-client.json", stage / "client-credentials.private.json"
)
results["state_sha256"] = receipt["sha256"]
# Exercise explicit abort before making the final transferable snapshot.
inside("python3", "/installer.pyz", "--resume-source")
inside("python3", "/acceptance-client.py", "check")
inside("python3", "/installer.pyz", "--export-state", "/portable-state-final.tar.gz")
shutil.copyfile(
root / "portable-state-final.tar.gz", stage / "portable-state.private.tar.gz"
)
results["state_sha256"] = hashlib.sha256(
(stage / "portable-state.private.tar.gz").read_bytes()
).hexdigest()
results["explicit_resume_accepted"] = True
results["status"] = "passed"
print(json.dumps(results), flush=True)
except Exception as exc:
if isinstance(exc, (subprocess.CalledProcessError, subprocess.TimeoutExpired)):
for name, value in (("stdout", exc.stdout), ("stderr", exc.stderr)):
(stage / ("failed." + name)).write_bytes(
value.encode() if isinstance(value, str) else value or b""
)
results.update(status="failed", error=type(exc).__name__ + ": " + str(exc))
(stage / "unit.log").write_text(
subprocess.run(
["journalctl", "-u", unit, "--no-pager", "-n", "120"],
capture_output=True,
text=True,
).stdout
)
raise
finally:
try:
subprocess.run(["systemctl", "stop", unit], capture_output=True, timeout=15)
except subprocess.TimeoutExpired:
subprocess.run(
["systemctl", "kill", "--kill-whom=all", "--signal=SIGKILL", unit],
capture_output=True,
timeout=10,
)
(stage / "result.json").write_text(json.dumps(results, indent=2))
print(
json.dumps(
{
"stage": str(stage),
"status": results.get("status"),
"temporary_unit_stopped": True,
}
),
flush=True,
)
if __name__ == "__main__":
main()