opnsense-deps/mirror/gwmirror.py
Jeremy Karst 49db816186 gwmirror publish: refuse to delete a series from the share
publish mirrors the staged tree with rsync --delete-after, and the share
holds the only copy of series that are no longer built (26.1). A staging
tree rebuilt after /scratch was lost, holding only the current series,
would have deleted 26.1 from the live mirror. publish now stops, before
verifying, when the destination has a directory in its top two levels
(an ABI, a series, releases/<series>) that the staged tree lacks; names
are printed quoted. Retiring a series means deleting it from the share
by hand.

RELEASE.md documents the guard and how to restore the staged tree from
the share.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 01:32:15 -05:00

1062 lines
44 KiB
Python

#!/usr/bin/env python3
# Copyright 2026 Karst Tech
# SPDX-License-Identifier: BSD-2-Clause
"""Stage, verify and publish the aarch64 OPNsense update mirror.
stage lay the sets of one build (pulled out of the build VM) into the
mirror tree that OPNsense clients expect
verify check a staged tree (--root) or the live mirror (--url): every
file a client fetches exists, is signed by a trusted key and,
with --deep, hashes correctly and contains only aarch64 ELF files
publish verify a staged tree, then rsync it onto the mirror storage
Only the Python standard library (3.14+, for zstd) and the openssl CLI are
used. Nothing read from a mirror is ever extracted to disk by verify; stage
extracts only our own packages and aux sets, through tarfile's "data" filter.
See RELEASE.md for the layout and the release procedure.
"""
import argparse
import concurrent.futures
import datetime
import hashlib
import http.client
import io
import json
import os
import re
import shutil
import socket
import ssl
import subprocess
import sys
import tarfile
import tempfile
import threading
import urllib.error
import urllib.parse
import urllib.request
ARCH = "aarch64"
EM_AARCH64 = 183
ELF_NAMES = {3: "i386", 40: "arm", 62: "x86-64", 183: "aarch64", 243: "riscv"}
# Firmware for other processors may legitimately be an ELF of another machine, and so
# may the Go toolchain's source tree (lang/go*): test data and the race detector's
# objects for every platform.
ELF_ARCH_EXEMPT = re.compile(r"(^|/)(boot/firmware|firmware)/|^/?usr/local/go[0-9]+/src/")
MAX_SIG = 64 * 1024 # a .sig file (SIGNATURE/CERT/END)
MAX_META = 64 * 1024 # meta.conf
MAX_ARCHIVE = 256 * 1024 * 1024 # packagesite.pkg / data.pkg, compressed
MAX_DOC = 1024 * 1024 * 1024 # packagesite.yaml / data, uncompressed
MAX_UNPACKED = 16 * 1024 ** 3 # all members of one package or set
MAX_MEMBERS = 2_000_000 # members of one package or set
CHUNK = 1024 * 1024
SERIES_RE = re.compile(r"\A\d\d\.\d\Z")
VERSION_RE = re.compile(r"\A\d\d\.\d(\.\d+)?\Z")
DEVICE_RE = re.compile(r"\A[A-Z0-9]+\Z")
ABI_RE = re.compile(r"\AFreeBSD:(\d+):" + ARCH + r"\Z")
REL_PART = re.compile(r"\A[A-Za-z0-9._+~:@,=-]+\Z")
PKG_NAME_RE = re.compile(r"\A[A-Za-z0-9][A-Za-z0-9._+-]*\Z")
PKG_VERSION_RE = re.compile(r"\A[A-Za-z0-9._+,~-]+\Z")
# a catalogue's package checksum: pkg < 2.8 wrote the file's SHA-256 in hex, pkg 2.8
# writes "2$" and its BLAKE2b-512 in pkg's own base32 (libpkg/pkg_checksum.c)
PKG_B32 = "ybndrfg8ejkmcpqxot1uwisza345h769"
PKG_SUM_RE = re.compile(r"\A(?:[0-9a-f]{64}|2\$[" + PKG_B32 + r"]{103})\Z")
META_LINE = re.compile(r'\A\s*([a-z_]+)\s*=\s*(?:"([^"\\]*)"|(\d+))\s*;\s*\Z')
META_NAME = re.compile(r"\A[A-Za-z0-9._-]+\Z")
FP_RE = re.compile(r'\A\s*function:\s*"sha256"\s*\n\s*fingerprint:\s*"([0-9a-f]{64})"\s*\Z')
PACKING_FORMATS = ("tzst", "txz", "tbz", "tgz", "tar")
# --------------------------------------------------------------------------
# Names on disk
# --------------------------------------------------------------------------
# The mirror is published onto an SMB share, which stores names the Windows way:
# case-insensitively, without ":" and the other reserved characters, and with device
# names such as "aux" listed under a mangled 8.3 name (which rsync then deletes as a
# file it does not know). Two components of the URL space therefore have other names
# on disk, in the staged tree and on the share alike: FreeBSD:<N>:aarch64 is stored as
# FreeBSD_<N>_aarch64, and a series' aux repository as aux-repo. The nginx container
# maps the URLs back (mirror/server/mirror.conf.template); every other name must be
# stored as it is, which share_name_problems checks.
DISK_ABI_RE = re.compile(r"\AFreeBSD_(\d+)_" + ARCH + r"\Z")
DISK_AUX = "aux-repo"
SMB_BAD_CHAR = re.compile(r'[\x00-\x1f"*/:<>?\\|]')
SMB_DEVICE = re.compile(r"\A(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9]|CONIN\$|CONOUT\$|CLOCK\$)(\..*)?\Z", re.I)
def disk_rel(rel):
"""Where the mirror path rel is stored, relative to the mirror's root."""
parts = rel.split("/")
m = ABI_RE.match(parts[0])
if m:
parts[0] = f"FreeBSD_{m.group(1)}_{ARCH}"
if len(parts) > 2 and SERIES_RE.match(parts[1]) and parts[2] == "aux":
parts[2] = DISK_AUX
return "/".join(parts)
def abi_of_disk_name(name):
"""The ABI a top-level directory on disk holds (FreeBSD_14_aarch64), or None."""
m = DISK_ABI_RE.match(name)
return f"FreeBSD:{m.group(1)}:{ARCH}" if m else None
def share_name_problems(root):
"""(path, problem) for every name under root an SMB share cannot store as it
is. Dotfiles are skipped: publish never copies them."""
problems = []
for d, dirs, files in os.walk(root):
dirs[:] = sorted(n for n in dirs if not n.startswith("."))
seen = {}
for name in sorted(dirs + [n for n in files if not n.startswith(".")]):
rel = os.path.relpath(os.path.join(d, name), root)
if SMB_BAD_CHAR.search(name) or SMB_DEVICE.match(name) or name.endswith((".", " ")):
problems.append((rel, "name cannot be stored on the SMB share"))
first = seen.setdefault(name.casefold(), name)
if first != name:
problems.append((rel, f"differs from {first} only in case (the share ignores case)"))
return problems
def link_problems(root):
"""(path, problem) for every symlink under root that resolves outside it or
to nothing: publish copies with rsync -L, which would publish the target.
Dotfiles are skipped, as in share_name_problems."""
root = os.path.realpath(root)
problems = []
for d, dirs, files in os.walk(root):
dirs[:] = sorted(n for n in dirs if not n.startswith("."))
for name in sorted(dirs + [n for n in files if not n.startswith(".")]):
path = os.path.join(d, name)
if not os.path.islink(path):
continue
rel = os.path.relpath(path, root)
target = os.path.realpath(path)
if target != root and not target.startswith(root + os.sep):
problems.append((rel, "symlink leads outside the mirror tree"))
elif not os.path.exists(target):
problems.append((rel, "symlink leads nowhere"))
return problems
class VerifyError(Exception):
"""A single verification failure, reported with its location."""
def safe_rel(rel):
"""Return rel if it is a plain relative path, else raise VerifyError."""
parts = rel.split("/")
if not rel or any(p in ("", ".", "..") or not REL_PART.match(p) for p in parts):
raise VerifyError(f"unsafe path {rel!r}")
return rel
def join(prefix, rel):
"""Join a repository prefix ("" or "." for the source root) and a path."""
return rel if prefix in ("", ".") else f"{prefix}/{rel}"
def sha256_stream(fileobj, limit=None):
sha256, _, total = digest_stream(fileobj, limit)
return sha256, total
def digest_stream(fileobj, limit=None):
"""(SHA-256 hex, pkg 2.8 BLAKE2b checksum, size) of a file, read once."""
sha256, blake2 = hashlib.sha256(), hashlib.blake2b(digest_size=64)
total = 0
while chunk := fileobj.read(CHUNK):
total += len(chunk)
if limit is not None and total > limit:
raise VerifyError("file exceeds size limit")
sha256.update(chunk)
blake2.update(chunk)
return sha256.hexdigest(), "2$" + pkg_base32(blake2.digest()), total
def pkg_base32(data):
"""pkg's base32 (pkg_checksum_encode_base32): its alphabet, least significant
bits first, no padding."""
out, remain = [], -1
for i, b in enumerate(data):
step = i % 5
if step == 0:
out.append(PKG_B32[b & 31])
remain = b >> 5
elif step == 1:
x = remain | b << 3
out += [PKG_B32[x & 31], PKG_B32[x >> 5 & 31]]
remain = x >> 10
elif step == 2:
x = remain | b << 1
out.append(PKG_B32[x & 31])
remain = x >> 5
elif step == 3:
x = remain | b << 4
out += [PKG_B32[x & 31], PKG_B32[x >> 5 & 31]]
remain = x >> 10 & 3
else:
x = remain | b << 2
out += [PKG_B32[x & 31], PKG_B32[x >> 5 & 31]]
remain = -1
if remain >= 0:
out.append(PKG_B32[remain])
return "".join(out)
def verify_link_sig(trust, link, sha256, sig, cert):
try:
trust.verify_digest(sha256, sig, cert)
except VerifyError as e:
raise VerifyError(f"{link}.sig: {e}") from None
def pkg_sum(sum_, sha256, blake2):
"""The digest to compare with a catalogue checksum of sum_'s type."""
return blake2 if sum_.startswith("2$") else sha256
# --------------------------------------------------------------------------
# Signatures and trust
# --------------------------------------------------------------------------
def parse_sig(blob):
"""Split a pkg/opnsense-verify .sig file into (signature, cert PEM)."""
if len(blob) > MAX_SIG:
raise VerifyError("signature file too large")
if not blob.startswith(b"SIGNATURE\n"):
raise VerifyError("signature file lacks SIGNATURE header")
marker = blob.find(b"\nCERT\n-----BEGIN PUBLIC KEY-----\n")
if marker < 0:
raise VerifyError("signature file lacks CERT block")
sig = blob[len(b"SIGNATURE\n"):marker]
rest = blob[marker + len(b"\nCERT\n"):]
if not rest.endswith(b"-----END PUBLIC KEY-----\nEND\n"):
raise VerifyError("signature file lacks END trailer")
cert = rest[:-len(b"END\n")]
if cert.count(b"-----BEGIN") != 1 or not 64 <= len(sig) <= 1024:
raise VerifyError("malformed signature file")
return sig, cert
class Trust:
"""Trusted minus revoked fingerprints, read like opnsense-verify does."""
def __init__(self, dirs):
self.trusted, self.revoked = set(), set()
for base in dirs:
for kind, bucket in (("trusted", self.trusted), ("revoked", self.revoked)):
sub = os.path.join(base, kind)
if not os.path.isdir(sub):
continue
for name in sorted(os.listdir(sub)):
with open(os.path.join(sub, name), encoding="ascii") as f:
m = FP_RE.match(f.read(4096))
if not m:
raise ValueError(f"malformed fingerprint file {sub}/{name}")
bucket.add(m.group(1))
if not self.trusted - self.revoked:
raise ValueError(f"no trusted fingerprints in {', '.join(dirs)}")
self._lock = threading.Lock()
self._certs = {}
self._tmp = tempfile.TemporaryDirectory(prefix="gwmirror-")
def close(self):
self._tmp.cleanup()
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()
def cert_file(self, cert):
"""Return a PEM file for a trusted cert, raising if it isn't trusted."""
fp = hashlib.sha256(cert).hexdigest()
if fp in self.revoked:
raise VerifyError(f"signed by revoked key {fp[:16]}")
if fp not in self.trusted:
raise VerifyError(f"signed by untrusted key {fp[:16]}")
with self._lock:
if fp not in self._certs:
path = os.path.join(self._tmp.name, fp + ".pem")
with open(path, "wb") as f:
f.write(cert)
self._certs[fp] = path
return self._certs[fp]
def verify_digest(self, hexdigest, sig, cert):
"""Check sig is the trusted key's RSA-SHA256 over the hex digest."""
pem = self.cert_file(cert)
with tempfile.NamedTemporaryFile(dir=self._tmp.name) as s:
s.write(sig)
s.flush()
r = subprocess.run(
["openssl", "dgst", "-sha256", "-verify", pem, "-signature", s.name],
input=hexdigest.encode("ascii"), capture_output=True)
if r.returncode != 0:
raise VerifyError("bad signature")
# --------------------------------------------------------------------------
# Where mirror files are read from
# --------------------------------------------------------------------------
class DirSource:
"""A staged mirror tree on disk, read by mirror path (see disk_rel)."""
def __init__(self, root):
self.root = os.path.realpath(root)
self.label = self.root
def _path(self, rel):
if rel in ("", "."):
return self.root
path = os.path.realpath(os.path.join(self.root, disk_rel(safe_rel(rel))))
if path != self.root and not path.startswith(self.root + os.sep):
raise VerifyError(f"{rel} resolves outside the mirror")
return path
def exists(self, rel):
try:
return os.path.isfile(self._path(rel))
except VerifyError: # leaves the tree: link_problems names it
return False
def size(self, rel):
try:
return os.path.getsize(self._path(rel))
except FileNotFoundError:
raise VerifyError(f"missing {rel}") from None
def open(self, rel):
try:
return open(self._path(rel), "rb")
except FileNotFoundError:
raise VerifyError(f"missing {rel}") from None
def read(self, rel, limit):
with self.open(rel) as f:
data = f.read(limit + 1)
if len(data) > limit:
raise VerifyError(f"{rel} exceeds size limit")
return data
def listdir(self, rel):
path = self._path(rel)
return sorted(os.listdir(path)) if os.path.isdir(path) else []
def same_file(self, a, b):
try:
return os.path.samefile(self._path(a), self._path(b))
except FileNotFoundError:
return False
class _NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise VerifyError(f"redirect to {newurl} refused")
class HttpSource:
"""The live mirror over HTTPS (HTTP only when explicitly allowed)."""
def __init__(self, base, ca_file=None, allow_http=False, timeout=60):
u = urllib.parse.urlsplit(base)
if u.scheme not in ("https", "http") or not u.hostname or u.query or u.fragment:
raise ValueError(f"bad mirror URL {base!r}")
if u.scheme == "http" and not allow_http:
raise ValueError("plain HTTP needs --allow-http")
self.base = base.rstrip("/")
self.label = self.base
self.scheme, self.host, self.port = u.scheme, u.hostname, u.port
self.timeout = timeout
self.ctx = ssl.create_default_context(cafile=ca_file)
handlers = [_NoRedirect()]
if self.scheme == "https":
handlers.append(urllib.request.HTTPSHandler(context=self.ctx))
self.opener = urllib.request.build_opener(*handlers)
def url(self, rel):
return self.base + "/" + urllib.parse.quote(safe_rel(rel), safe="/:,+@=~")
def _request(self, rel, method):
req = urllib.request.Request(self.url(rel), method=method,
headers={"User-Agent": "gwmirror-verify"})
try:
return self.opener.open(req, timeout=self.timeout)
except urllib.error.HTTPError as e:
e.close()
raise VerifyError(f"{rel}: HTTP {e.code}") from None
except (urllib.error.URLError, OSError, http.client.HTTPException) as e:
raise VerifyError(f"{rel}: {e}") from None
def exists(self, rel):
try:
self._request(rel, "HEAD").close()
return True
except VerifyError:
return False
def size(self, rel):
with self._request(rel, "HEAD") as r:
length = r.headers.get("Content-Length")
if length is None or not length.isdigit():
raise VerifyError(f"{rel}: no Content-Length (opnsense-update -S needs it)")
return int(length)
def open(self, rel):
return self._request(rel, "GET")
def read(self, rel, limit):
with self.open(rel) as r:
data = r.read(limit + 1)
if len(data) > limit:
raise VerifyError(f"{rel} exceeds size limit")
return data
def listdir(self, rel):
return []
def same_file(self, a, b):
return False
def cert_days_left(self):
"""Days until the server certificate expires (TLS verified)."""
with socket.create_connection((self.host, self.port or 443), self.timeout) as raw:
with self.ctx.wrap_socket(raw, server_hostname=self.host) as s:
not_after = s.getpeercert()["notAfter"]
expires = datetime.datetime.fromtimestamp(ssl.cert_time_to_seconds(not_after), datetime.UTC)
return (expires - datetime.datetime.now(datetime.UTC)).total_seconds() / 86400
class _LockedReader:
"""A member of a TarSource: each read seeks the shared file, under its lock."""
def __init__(self, f, lock):
self.f, self.lock = f, lock
def read(self, n=-1):
with self.lock:
return self.f.read(n)
def close(self):
self.f.close()
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()
class TarSource:
"""A packages-*.tar set, read as the repository it unpacks into. Its members
share the set's file object, which every read seeks; verify_repo reads them
from several threads, so reads take turns."""
def __init__(self, fileobj, label):
self.tar = tarfile.open(fileobj=fileobj, mode="r:")
self.lock = threading.Lock()
self.label = label
self.members = {}
for m in self.tar.getmembers():
name = m.name[2:] if m.name.startswith("./") else m.name
if name and name != ".":
self.members[name] = m
if len(self.members) > MAX_MEMBERS:
raise VerifyError(f"{label}: too many members")
def _member(self, rel):
rel = safe_rel(rel)
for _ in range(8):
m = self.members.get(rel)
if m is None:
raise VerifyError(f"missing {rel} in {self.label}")
if m.isreg():
return m
if not m.issym():
raise VerifyError(f"{rel} in {self.label} is not a file")
target = os.path.normpath(os.path.join(os.path.dirname(rel), m.linkname))
if target.startswith("../") or os.path.isabs(target):
raise VerifyError(f"{rel} in {self.label} links outside the set")
rel = target
raise VerifyError(f"{rel} in {self.label}: symlink loop")
def exists(self, rel):
try:
self._member(rel)
return True
except VerifyError:
return False
def size(self, rel):
return self._member(rel).size
def open(self, rel):
return _LockedReader(self.tar.extractfile(self._member(rel)), self.lock)
def read(self, rel, limit):
m = self._member(rel)
if m.size > limit:
raise VerifyError(f"{rel} exceeds size limit")
with self.lock:
return self.tar.extractfile(m).read()
def listdir(self, rel):
prefix = "" if rel in ("", ".") else rel.rstrip("/") + "/"
return sorted({n[len(prefix):].split("/")[0] for n in self.members if n.startswith(prefix)})
def same_file(self, a, b):
try:
return self._member(a) is self._member(b)
except VerifyError:
return False
# --------------------------------------------------------------------------
# Content checks
# --------------------------------------------------------------------------
def scan_tar_elf(fileobj, label, report):
"""Stream a (compressed) tar; report ELF files not built for aarch64."""
total = count = 0
try:
with tarfile.open(fileobj=fileobj, mode="r|*") as tf:
for m in tf:
count += 1
total += max(m.size, 0)
if count > MAX_MEMBERS or total > MAX_UNPACKED:
raise VerifyError("archive exceeds unpacked size or member limit")
if not m.isreg() or m.size < 20:
continue
head = tf.extractfile(m).read(20)
if head[:4] != b"\x7fELF":
continue
order = "little" if head[5] == 1 else "big"
machine = int.from_bytes(head[18:20], order)
if machine != EM_AARCH64 and not ELF_ARCH_EXEMPT.search(m.name):
report.error(label, f"{m.name} is {ELF_NAMES.get(machine, machine)} ELF, not {ARCH}")
except (tarfile.TarError, EOFError, OSError, ValueError) as e:
raise VerifyError(f"unreadable archive: {e}") from None
def read_sig(source, rel):
return parse_sig(source.read(rel, MAX_SIG))
def verify_signed_file(source, rel, trust, report, deep, elf=False):
"""Check rel + rel.sig; with deep also the hash (and ELF contents)."""
try:
sig, cert = read_sig(source, rel + ".sig")
trust.cert_file(cert)
source.size(rel)
if not deep:
return
with source.open(rel) as f:
digest, _ = sha256_stream(f)
trust.verify_digest(digest, sig, cert)
if elf:
with source.open(rel) as f:
scan_tar_elf(f, rel, report)
except VerifyError as e:
report.error(rel, str(e))
def parse_meta(blob):
meta = {}
for line in blob.decode("ascii", "strict").splitlines():
if not line.strip():
continue
m = META_LINE.match(line)
if not m:
raise VerifyError(f"meta.conf: malformed line {line[:60]!r}")
meta[m.group(1)] = m.group(2) if m.group(2) is not None else int(m.group(3))
for key in ("packing_format", "manifests", "manifests_archive", "data"):
if not isinstance(meta.get(key), str) or not META_NAME.match(meta[key]):
raise VerifyError(f"meta.conf: missing or bad {key}")
if meta["packing_format"] not in PACKING_FORMATS:
raise VerifyError(f"meta.conf: unknown packing_format {meta['packing_format']!r}")
return meta
def read_catalogue_doc(source, prefix, archive, doc, packing, trust):
"""Return the signed document from <archive>.pkg after checking it."""
rel = join(prefix, f"{archive}.pkg")
blob = source.read(rel, MAX_ARCHIVE)
alt = join(prefix, f"{archive}.{packing}")
if source.exists(alt) and hashlib.sha256(source.read(alt, MAX_ARCHIVE)).digest() != hashlib.sha256(blob).digest():
raise VerifyError(f"{alt} differs from {rel}")
try:
with tarfile.open(fileobj=io.BytesIO(blob), mode="r:*") as tf:
members = {m.name: m for m in tf.getmembers()}
if set(members) != {doc, doc + ".sig", doc + ".pub"}:
raise VerifyError(f"{rel}: unexpected members {sorted(members)[:5]}")
parts = {}
for name, m in members.items():
if not m.isreg() or m.size > (MAX_DOC if name == doc else MAX_SIG):
raise VerifyError(f"{rel}: bad member {name}")
parts[name] = tf.extractfile(m).read()
except (tarfile.TarError, EOFError, OSError, ValueError) as e:
raise VerifyError(f"{rel}: unreadable: {e}") from None
trust.verify_digest(hashlib.sha256(parts[doc]).hexdigest(), parts[doc + ".sig"], parts[doc + ".pub"])
return parts[doc]
def parse_packages(data_doc, manifests_doc, rel):
"""Return the catalogue entries, which both documents must agree on."""
try:
from_data = json.loads(data_doc)["packages"]
from_lines = [json.loads(line) for line in manifests_doc.splitlines() if line.strip()]
except (ValueError, KeyError, TypeError) as e:
raise VerifyError(f"{rel}: catalogue is not valid JSON: {e}") from None
if not isinstance(from_data, list) or not all(isinstance(p, dict) for p in from_data + from_lines):
raise VerifyError(f"{rel}: catalogue entries are not objects")
def key(p):
return tuple(str(p.get(k)) for k in ("name", "version", "sum", "path"))
if sorted(map(key, from_data)) != sorted(map(key, from_lines)):
raise VerifyError(f"{rel}: data and manifests catalogues disagree")
return from_data
def verify_repo(source, prefix, abi, trust, report, deep, elf, latest=True, label=None):
"""Verify a pkg repository; return its {name: version} catalogue.
With latest, each package also needs its signed Latest/<name>.pkg, which tools
makes for the main repository only (pkg bootstrap and opnsense-update fetch
from there); the aux repository has none, upstream's neither. Results are
reported under label (default: prefix)."""
label = label or prefix
try:
meta = parse_meta(source.read(join(prefix, "meta.conf"), MAX_META))
manifests = read_catalogue_doc(source, prefix, meta["manifests_archive"],
meta["manifests"], meta["packing_format"], trust)
data = read_catalogue_doc(source, prefix, meta["data"], meta["data"],
meta["packing_format"], trust)
packages = parse_packages(data, manifests, prefix)
except VerifyError as e:
report.error(label, str(e))
return {}
major = ABI_RE.match(abi).group(1)
allowed_abi = {abi, f"FreeBSD:{major}:*", "FreeBSD:*:*"}
catalogue, referenced = {}, set()
def check(p):
name, version, path = p.get("name"), p.get("version"), p.get("path")
where = join(prefix, str(path))
if not (isinstance(name, str) and PKG_NAME_RE.match(name)
and isinstance(version, str) and PKG_VERSION_RE.match(version)):
raise VerifyError(f"bad name/version {name!r} {version!r}")
if path != f"All/{name}-{version}.pkg" or p.get("repopath", path) != path:
raise VerifyError(f"{name}: unexpected path {path!r}")
if p.get("abi") not in allowed_abi:
raise VerifyError(f"{name}: ABI {p.get('abi')!r} not in {sorted(allowed_abi)}")
sum_ = p.get("sum")
if not (isinstance(sum_, str) and PKG_SUM_RE.match(sum_)):
raise VerifyError(f"{name}: bad checksum field")
if source.size(where) != p.get("pkgsize"):
raise VerifyError(f"{where}: size differs from catalogue")
link = join(prefix, f"Latest/{name}.pkg")
if latest:
if source.size(link) != p["pkgsize"]:
raise VerifyError(f"{link}: size differs from catalogue")
# tools signs Latest/ links over the file's SHA-256: a SHA-256 catalogue
# checks them without reading the file, a BLAKE2b one only when deep
sig, cert = read_sig(source, link + ".sig")
if sum_.startswith("2$"):
trust.cert_file(cert)
else:
verify_link_sig(trust, link, sum_, sig, cert)
if deep:
with source.open(where) as f:
sha256, blake2, _ = digest_stream(f, MAX_UNPACKED)
if pkg_sum(sum_, sha256, blake2) != sum_:
raise VerifyError(f"{where}: checksum differs from catalogue")
if latest and not source.same_file(where, link):
with source.open(link) as f:
sha256, blake2, _ = digest_stream(f, MAX_UNPACKED)
if pkg_sum(sum_, sha256, blake2) != sum_:
raise VerifyError(f"{link}: checksum differs from catalogue")
if latest and sum_.startswith("2$"):
verify_link_sig(trust, link, sha256, sig, cert)
if elf:
with source.open(where) as f:
scan_tar_elf(f, where, report)
def run(p):
try:
check(p)
except VerifyError as e:
report.error(join(label, str(p.get("path"))), str(e))
for p in packages:
if p.get("name") in catalogue:
report.error(label, f"duplicate package {p.get('name')!r}")
catalogue[p.get("name")] = p.get("version")
referenced.add(f"All/{p.get('name')}-{p.get('version')}.pkg")
with concurrent.futures.ThreadPoolExecutor(max_workers=min(8, os.cpu_count() or 1)) as pool:
list(pool.map(run, packages))
for extra in sorted(set(f"All/{n}" for n in source.listdir(join(prefix, "All"))) - referenced):
report.warn(join(label, extra), "not in the catalogue")
report.ok(f"{label}: {len(packages)} packages")
return catalogue
def release_of(catalogue, where, report):
"""The base/kernel release clients fetch: opnsense-update's version."""
version = catalogue.get("opnsense-update")
if not version:
report.error(where, "catalogue has no opnsense-update package")
return None
return version.split("_")[0]
def verify_series(source, series_dir, trust, upstream, report, deep, device, url_mode):
"""Verify one <ABI>/<series> directory of the mirror."""
abi, series = series_dir.split("/")
elf = deep
catalogue = verify_repo(source, f"{series_dir}/latest", abi, trust, report, deep, elf)
release = release_of(catalogue, f"{series_dir}/latest", report) if catalogue else None
sets = f"{series_dir}/sets"
required = []
if release:
required = [f"base-{release}-{ARCH}.txz", f"kernel-{release}-{ARCH}-{device}.txz"]
listing = source.listdir(sets)
present = [n for n in listing if not n.endswith(".sig")]
for orphan in sorted(n for n in listing if n.endswith(".sig") and n[:-4] not in listing):
report.error(f"{sets}/{orphan}", "signature without its file")
for name in sorted(set(required) | set(present)):
rel = f"{sets}/{name}"
if not source.exists(rel):
report.error(rel, "missing (clients fetch it for this release)")
continue
if name.startswith("base-") and name.endswith(f"-{device}.txz"):
report.error(rel, "base set carries the device suffix; clients fetch it without")
if name.startswith("packages-") and name.endswith(".tar"):
verify_signed_file(source, rel, trust, report, deep)
if deep and not url_mode:
verify_upgrade_set(source, rel, trust, report)
elif re.fullmatch(r"(base|kernel)-.*\.txz", name):
verify_signed_file(source, rel, trust, report, deep, elf=elf)
else:
report.error(rel, "unexpected file in sets/")
if url_mode:
for name in ("changelog.txz", "bogons.txz"):
verify_signed_file(source, f"{sets}/{name}", upstream, report, deep=True)
if source.exists(f"{series_dir}/aux/meta.conf"):
verify_repo(source, f"{series_dir}/aux", abi, trust, report, deep, elf, latest=False)
def verify_upgrade_set(source, rel, trust, report):
"""A packages-*.tar is the repository `opnsense-update -P` installs from."""
try:
with source.open(rel) as f:
inner = TarSource(f, rel)
hint = inner.read(".abi_hint", 256).decode("ascii", "replace").strip()
if not ABI_RE.match(hint):
raise VerifyError(f"bad .abi_hint {hint!r}")
verify_repo(inner, ".", hint, trust, report, deep=True, elf=True, label=rel)
except VerifyError as e:
report.error(rel, str(e))
def verify_releases(source, report, trust, deep):
for series in source.listdir("releases"):
for name in source.listdir(f"releases/{series}"):
if name.endswith(".img.gz"):
verify_signed_file(source, f"releases/{series}/{name}", trust, report, deep)
class Report:
def __init__(self, quiet=False):
self.errors, self.warnings = [], []
self.quiet = quiet
self._lock = threading.Lock()
def _emit(self, bucket, kind, where, msg):
with self._lock:
bucket.append((where, msg))
print(f"{kind} {where}: {msg}", file=sys.stderr if kind != "OK" else sys.stdout)
def error(self, where, msg):
self._emit(self.errors, "ERROR", where, msg)
def warn(self, where, msg):
self._emit(self.warnings, "WARN", where, msg)
def ok(self, msg):
if not self.quiet:
print(f"OK {msg}")
def discover_series(source):
"""The <ABI>/<series> directories of a staged tree."""
found = []
for name in source.listdir("."):
abi = abi_of_disk_name(name)
if abi:
found += [f"{abi}/{s}" for s in source.listdir(abi) if SERIES_RE.match(s)]
return found
def verify(args):
with Trust(args.fingerprints) as trust, Trust(args.upstream_fingerprints) as upstream:
return verify_with(args, trust, upstream)
def verify_with(args, trust, upstream):
report = Report(args.quiet)
if args.root:
source, url_mode, deep = DirSource(args.root), False, not args.shallow
series = args.series or discover_series(source)
for rel, problem in share_name_problems(source.root) + link_problems(source.root):
report.error(rel, problem)
else:
source = HttpSource(args.url, args.ca_file, args.allow_http)
url_mode, deep = True, args.deep
series = args.series
if source.scheme == "https":
try:
days = source.cert_days_left()
if days < args.min_cert_days:
report.error(source.host, f"TLS certificate expires in {days:.1f} days")
else:
report.ok(f"TLS certificate valid for {days:.0f} more days")
except (OSError, ssl.SSLError) as e:
report.error(source.host, f"TLS: {e}")
try:
if source.read("healthz", 1024).strip() != b"ok":
report.error("healthz", "unexpected body")
except VerifyError as e:
report.error("healthz", str(e))
if not series:
report.error(source.label, "no <ABI>/<series> directories to verify")
for s in series:
abi, _, ser = s.partition("/")
if not ABI_RE.match(abi) or not SERIES_RE.match(ser):
report.error(s, "series must look like FreeBSD:14:aarch64/26.1")
continue
try:
verify_series(source, s, trust, upstream, report, deep, args.device, url_mode)
except VerifyError as e:
report.error(s, str(e))
if args.root:
try:
verify_releases(source, report, trust, deep)
except VerifyError as e:
report.error("releases", str(e))
status = "FAILED" if report.errors else "PASSED"
print(f"{status}: {len(report.errors)} errors, {len(report.warnings)} warnings ({source.label})")
return 1 if report.errors else 0
# --------------------------------------------------------------------------
# stage / publish
# --------------------------------------------------------------------------
def _need(path):
if not os.path.isfile(path):
raise SystemExit(f"gwmirror stage: missing {path}")
return path
def _copy_signed(src, dst_dir, dst_name=None):
os.makedirs(dst_dir, exist_ok=True)
name = dst_name or os.path.basename(src)
for suffix in ("", ".sig"):
tmp = os.path.join(dst_dir, f".{name}{suffix}.tmp")
shutil.copyfile(_need(src + suffix), tmp)
os.replace(tmp, os.path.join(dst_dir, name + suffix))
def _extract_repo(tar_path, dest):
"""Unpack a packages/aux set into dest, replacing it as a whole."""
tmp = dest + ".new"
shutil.rmtree(tmp, ignore_errors=True)
os.makedirs(tmp)
with tarfile.open(tar_path, "r:") as tf:
members = [m for m in tf.getmembers()
if not os.path.basename(m.name.rstrip("/")).startswith(".")]
tf.extractall(tmp, members=members, filter="data")
old = dest + ".old"
shutil.rmtree(old, ignore_errors=True)
if os.path.exists(dest):
os.rename(dest, old)
os.rename(tmp, dest)
shutil.rmtree(old, ignore_errors=True)
def _abi_hint(tar_path):
with tarfile.open(tar_path, "r:") as tf:
for name in ("./.abi_hint", ".abi_hint"):
try:
hint = tf.extractfile(name).read(256).decode("ascii").strip()
break
except KeyError:
continue
else:
raise SystemExit(f"gwmirror stage: {tar_path} has no .abi_hint")
if not ABI_RE.match(hint):
raise SystemExit(f"gwmirror stage: bad .abi_hint {hint!r} in {tar_path}")
return hint
def stage(args):
for value, rx, what in ((args.series, SERIES_RE, "series"), (args.version, VERSION_RE, "version"),
(args.device, DEVICE_RE, "device")):
if not rx.match(value):
raise SystemExit(f"gwmirror stage: bad {what} {value!r}")
if not args.version.startswith(args.series):
raise SystemExit("gwmirror stage: version does not belong to series")
v, dev = args.version, args.device
sets_in = os.path.join(args.sets, "sets")
packages = _need(os.path.join(sets_in, f"packages-{v}-{ARCH}.tar"))
kernel = os.path.join(sets_in, f"kernel-{v}-{ARCH}-{dev}.txz")
base = os.path.join(sets_in, f"base-{v}-{ARCH}-{dev}.txz")
if not os.path.exists(base):
base = os.path.join(sets_in, f"base-{v}-{ARCH}.txz")
abi = _abi_hint(packages)
series_dir = os.path.join(args.mirror, disk_rel(f"{abi}/{args.series}"))
base_name = f"base-{v}-{ARCH}.txz"
_copy_signed(base, os.path.join(series_dir, "sets"), base_name)
_copy_signed(kernel, os.path.join(series_dir, "sets"))
_extract_repo(packages, os.path.join(series_dir, "latest"))
aux = os.path.join(sets_in, f"aux-{v}-{ARCH}.tar")
if os.path.exists(aux):
_need(aux + ".sig")
_extract_repo(aux, os.path.join(args.mirror, disk_rel(f"{abi}/{args.series}/aux")))
mint = os.path.join(series_dir, "MINT", v, "latest")
shutil.rmtree(mint, ignore_errors=True)
shutil.copytree(os.path.join(series_dir, "latest"), mint, symlinks=True, copy_function=os.link)
if args.upgrade_from:
if not SERIES_RE.match(args.upgrade_from):
raise SystemExit(f"gwmirror stage: bad --upgrade-from {args.upgrade_from!r}")
old = [d for d in os.listdir(args.mirror) if abi_of_disk_name(d)
and os.path.isdir(os.path.join(args.mirror, d, args.upgrade_from))]
if len(old) != 1:
found = [abi_of_disk_name(d) for d in old]
raise SystemExit(f"gwmirror stage: need exactly one staged series {args.upgrade_from}, found {found}")
old_sets = os.path.join(args.mirror, old[0], args.upgrade_from, "sets")
_copy_signed(packages, old_sets)
_copy_signed(base, old_sets, base_name)
_copy_signed(kernel, old_sets)
image = os.path.join(args.sets, "images", f"OPNsense-{v}-arm-{ARCH}-{dev}.img.gz")
if os.path.exists(image):
rel_dir = os.path.join(args.mirror, "releases", args.series)
_copy_signed(image, rel_dir)
with open(image, "rb") as f:
digest, _ = sha256_stream(f)
with open(os.path.join(rel_dir, os.path.basename(image) + ".sha256"), "w") as f:
f.write(f"{digest} {os.path.basename(image)}\n")
print(f"staged {abi}/{args.series} {v} into {args.mirror}")
return 0
def dropped_dirs(mirror, dest):
"""Directories in the top two levels of dest (FreeBSD_14_aarch64, its 26.1,
releases/26.1) that the staged mirror lacks: publishing would delete them,
and with them a whole series. Dotfiles are skipped, as publish skips them."""
dropped = []
for top in sorted(os.listdir(dest)):
d, m = os.path.join(dest, top), os.path.join(mirror, top)
if top.startswith(".") or not os.path.isdir(d):
continue
if not os.path.isdir(m):
dropped.append(top)
continue
dropped.extend(f"{top}/{sub}" for sub in sorted(os.listdir(d))
if not sub.startswith(".") and os.path.isdir(os.path.join(d, sub))
and not os.path.isdir(os.path.join(m, sub)))
return dropped
def publish(args):
if not os.path.isdir(args.dest):
raise SystemExit(f"gwmirror publish: destination {args.dest} is not a directory")
dropped = dropped_dirs(args.mirror, args.dest)
if dropped:
print(f"gwmirror publish: {', '.join(map(repr, dropped))} in {args.dest} would be deleted: "
"the staged mirror lacks them. Restore them into it (RELEASE.md, \"Restoring the "
"staged mirror\"), or delete them from the destination to retire them. "
"Nothing published", file=sys.stderr)
return 1
vargs = argparse.Namespace(root=args.mirror, url=None, series=None, shallow=False,
fingerprints=args.fingerprints,
upstream_fingerprints=args.upstream_fingerprints,
device=args.device, quiet=True)
if verify(vargs) != 0:
print("gwmirror publish: verification failed, nothing published", file=sys.stderr)
return 1
cmd = ["rsync", "-rtL", "--delay-updates", "--delete-after", "--exclude=.*",
os.path.join(args.mirror, ""), os.path.join(args.dest, "")]
print(" ".join(cmd))
return subprocess.run(cmd).returncode
def main(argv=None):
here = os.path.dirname(os.path.abspath(__file__))
keys = os.path.join(os.path.dirname(here), "keys")
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
sub = p.add_subparsers(dest="cmd", required=True)
def trust_args(sp):
sp.add_argument("--fingerprints", action="append", default=None,
help="dir with trusted/ and revoked/ for our builds (default: keys/fingerprints)")
sp.add_argument("--upstream-fingerprints", action="append", default=None,
help="dir for upstream-signed changelog/bogons (default: keys/upstream)")
sp.add_argument("--device", default="GATEWAY", help="kernel set device suffix")
st = sub.add_parser("stage", help="lay one build's sets into the mirror tree")
st.add_argument("--sets", required=True, help="build output dir containing sets/ and images/")
st.add_argument("--mirror", required=True, help="staged mirror root")
st.add_argument("--series", required=True)
st.add_argument("--version", required=True)
st.add_argument("--device", default="GATEWAY")
st.add_argument("--upgrade-from", help="also offer this build as the major upgrade of that series")
vf = sub.add_parser("verify", help="verify a staged tree or the live mirror")
where = vf.add_mutually_exclusive_group(required=True)
where.add_argument("--root", help="staged mirror root (deep by default)")
where.add_argument("--url", help="mirror base URL (shallow by default)")
vf.add_argument("--series", action="append", help="e.g. FreeBSD:14:aarch64/26.1 (required with --url)")
vf.add_argument("--deep", action="store_true", help="with --url: download and hash everything")
vf.add_argument("--shallow", action="store_true", help="with --root: skip hashing and ELF scan")
vf.add_argument("--min-cert-days", type=float, default=21)
vf.add_argument("--ca-file", help="extra CA bundle for TLS (tests)")
vf.add_argument("--allow-http", action="store_true", help="allow a plain-HTTP --url (local tests)")
vf.add_argument("--quiet", action="store_true", help="print only problems and the summary")
trust_args(vf)
pb = sub.add_parser("publish", help="verify, then rsync the staged tree")
pb.add_argument("--mirror", required=True)
pb.add_argument("--dest", required=True)
trust_args(pb)
args = p.parse_args(argv)
if args.cmd in ("verify", "publish"):
args.fingerprints = args.fingerprints or [os.path.join(keys, "fingerprints")]
args.upstream_fingerprints = args.upstream_fingerprints or [os.path.join(keys, "upstream")]
if not DEVICE_RE.match(args.device):
p.error(f"bad --device {args.device!r}")
if args.cmd == "verify" and args.url and not args.series:
p.error("--url needs at least one --series")
try:
return {"stage": stage, "verify": verify, "publish": publish}[args.cmd](args)
except ValueError as e:
print(f"gwmirror: {e}", file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main())