mirror: store the tree under names an SMB share can hold

The mirror share refuses ":" in names, ignores case, and lists device
names such as "aux" under a mangled 8.3 name, which rsync would delete as
an unknown file (the real directory). So FreeBSD:<N>:aarch64 is stored
as FreeBSD_<N>_aarch64 and a series' aux repository as aux-repo, in the
staged tree and on the share alike; nginx rewrites the client URLs onto
them, and gwmirror reads and writes through the same mapping.

verify --root, and therefore publish, now fails on any other name the
share cannot store (reserved characters, device names, trailing dot or
space, names differing only in case).

Checked with the real nginx image in podman: a deep verify --url of a
staged fixture passes, aux included, with the live changelog/bogons proxy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jeremy Karst 2026-11-18 14:49:20 -05:00
parent 1ab64f5ba2
commit 5665956249
5 changed files with 198 additions and 16 deletions

View file

@ -69,6 +69,31 @@ under the URL in `/usr/local/etc/pkg/repos/OPNsense.conf`:
`opnsense-update -P` upgrades only the OPNsense repository. The board's
kernel modules must cross the ABI change with it.
### Names on disk
The mirror is stored on an SMB share, which keeps names the Windows way. On
ours (checked 2026-11-18):
- `:` is refused (`NT_STATUS_OBJECT_NAME_INVALID`);
- names are case-insensitive (`case.txt` replaces `Case.txt`);
- device names such as `aux` and `con` are stored but listed under a mangled
8.3 name (`AHY9U3~9`), so rsync would copy them again and then delete the
"unknown" mangled entry, which is the real directory. A file stored that way
cannot even be deleted over SMB.
So two components of the paths above have other names on disk, in the staged
tree and on the share alike:
| URL path | On disk |
|---|---|
| `/FreeBSD:<N>:aarch64/` | `FreeBSD_<N>_aarch64/` |
| `/FreeBSD:<N>:aarch64/<series>/aux/` | `FreeBSD_<N>_aarch64/<series>/aux-repo/` |
The nginx container rewrites the URLs onto them; `gwmirror.py` reads and
writes through the same mapping (`disk_rel`). Every other name is stored as
it is, and `verify --root` (so also `publish`) fails on any name the share
cannot hold: reserved characters, device names, a trailing dot or space, or
two names in a directory that differ only in case.
## Signing keys and trust
- **Private key:** `~/.config/gwmirror/repo.key` on the workstation (RSA
@ -218,7 +243,8 @@ python3 mirror/gwmirror.py verify --url https://opnsense.karsttech.com --series
- every package's path, ABI, size, sha256 and `Latest/` signature;
- the set and image signatures against `keys/fingerprints`;
- that every ELF inside every package and set is aarch64 (firmware
directories excepted).
directories excepted);
- that every name can be stored on the SMB share (see "Names on disk").
Nothing is extracted to disk while verifying.
@ -236,10 +262,24 @@ catalogues). `--deep` downloads and hashes everything.
`rsync -rtL --delay-updates --delete-after`: symlinks become plain files
(SMB keeps none), and clients never see a half-written repository.
The share is mounted on the workstation with the kernel CIFS client (as
root, once; `cifs-utils` installed), owned by the workstation user so rsync
needs no privileges:
```
# /etc/fstab
//<server>/<share> /mnt/opnsense-mirror cifs credentials=/home/code/.config/gwmirror/smb-credentials,uid=code,gid=code,vers=3.0,nofail,_netdev 0 0
```
`~/.config/gwmirror/smb-credentials` (mode 0600) holds `username=` and
`password=` lines. Nothing but the published tree may live at the top of the
share: `--delete-after` removes everything else.
## Serving the mirror
`mirror/server/` holds the stack:
- an unprivileged nginx on a read-only root;
- the URL-to-disk name rewrites (see "Names on disk");
- GET/HEAD only, dotfiles hidden, autoindex on;
- the changelog/bogons proxy;
- `/healthz`.

View file

@ -64,6 +64,58 @@ FP_RE = re.compile(r'\A\s*function:\s*"sha256"\s*\n\s*fingerprint:\s*"([0-9a-f]{
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
class VerifyError(Exception):
"""A single verification failure, reported with its location."""
@ -170,7 +222,7 @@ class Trust:
# --------------------------------------------------------------------------
class DirSource:
"""A staged mirror tree on disk."""
"""A staged mirror tree on disk, read by mirror path (see disk_rel)."""
def __init__(self, root):
self.root = os.path.realpath(root)
@ -179,7 +231,7 @@ class DirSource:
def _path(self, rel):
if rel in ("", "."):
return self.root
path = os.path.realpath(os.path.join(self.root, safe_rel(rel)))
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
@ -617,9 +669,11 @@ class Report:
def discover_series(source):
"""The <ABI>/<series> directories of a staged tree."""
found = []
for abi in source.listdir("."):
if ABI_RE.match(abi):
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
@ -631,6 +685,8 @@ def verify(args):
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):
report.error(rel, problem)
else:
source = HttpSource(args.url, args.ca_file, args.allow_http)
url_mode, deep = True, args.deep
@ -730,7 +786,7 @@ def stage(args):
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, abi, args.series)
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)
@ -739,7 +795,7 @@ def stage(args):
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(series_dir, "aux"))
_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)
@ -748,10 +804,11 @@ def stage(args):
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_RE.match(d)
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:
raise SystemExit(f"gwmirror stage: need exactly one staged series {args.upgrade_from}, found {old}")
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)

View file

@ -14,7 +14,8 @@
# SMB_ADDRESS required: the SMB server's IP address.
# SMB_SHARE required: the share name, optionally with the folder that
# holds the published tree ("mirrors/opnsense"). Its top level
# contains FreeBSD:14:aarch64/, releases/, ...
# contains FreeBSD_14_aarch64/, releases/, ... (SMB cannot store
# the ":" of the URLs; RELEASE.md, "Names on disk").
# SMB_USERNAME, SMB_PASSWORD required: credentials with read access to the share. The
# password may not contain a comma.
# PUBLISH_PORT optional, default 8080: the host port (see below).

View file

@ -10,6 +10,16 @@ server {
root /srv/mirror;
charset utf-8;
# The mirror's storage is an SMB share, which cannot hold ":" in a name and
# lists the device name "aux" under a mangled one, so FreeBSD:<N>:aarch64 is
# stored as FreeBSD_<N>_aarch64 and each series' aux repository as aux-repo
# (gwmirror.py, "Names on disk"). Map the paths clients request onto them;
# every location below sees the stored names.
rewrite "^/FreeBSD:(?<diskmajor>[1-9][0-9]):aarch64/(?<diskseries>[0-9]{2}\.[0-9])/aux(?<diskrest>/.*)?$"
/FreeBSD_${diskmajor}_aarch64/${diskseries}/aux-repo${diskrest} last;
rewrite "^/FreeBSD:(?<diskmajor>[1-9][0-9]):aarch64(?<diskrest>/.*)?$"
/FreeBSD_${diskmajor}_aarch64${diskrest} last;
location = /healthz {
access_log off;
default_type text/plain;
@ -21,7 +31,7 @@ server {
# from pkg.opnsense.org's amd64 tree of the same FreeBSD major and series.
# The captures only admit digits and the two file names, so the upstream
# URL cannot be steered anywhere else.
location ~ "^/FreeBSD:(?<abimajor>[1-9][0-9]):aarch64/(?<series>[0-9]{2}\.[0-9])/sets/(?<setfile>(changelog|bogons)\.txz(\.sig)?)$" {
location ~ "^/FreeBSD_(?<abimajor>[1-9][0-9])_aarch64/(?<series>[0-9]{2}\.[0-9])/sets/(?<setfile>(changelog|bogons)\.txz(\.sig)?)$" {
limit_except GET {
deny all;
}

View file

@ -22,12 +22,14 @@ import tarfile
import tempfile
import threading
import unittest
import urllib.parse
from unittest import mock
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import gwmirror as g # noqa: E402
ABI = "FreeBSD:14:aarch64"
DISK_ABI = "FreeBSD_14_aarch64" # its name on disk (gwmirror.disk_rel)
SERIES = "26.1"
VERSION = "26.1.11"
@ -203,7 +205,7 @@ class Base(unittest.TestCase):
code, text = run_main(["stage", "--sets", out, "--mirror", self.mirror,
"--series", SERIES, "--version", build.get("version", VERSION)])
self.assertEqual(code, 0, text)
return os.path.join(self.mirror, ABI, SERIES)
return os.path.join(self.mirror, DISK_ABI, SERIES)
def verify(self, *extra, fps=None):
return run_main(["verify", "--root", self.mirror, "--fingerprints", fps or self.keys.ours,
@ -226,7 +228,8 @@ class StageTest(Base):
latest = os.path.join(d, "latest")
self.assertFalse(any(n.startswith(".") for n in os.listdir(latest)), "dotfiles must not be staged")
self.assertTrue(os.path.islink(os.path.join(latest, "Latest", "opnsense.pkg")))
self.assertTrue(os.path.isfile(os.path.join(d, "aux", "meta.conf")))
self.assertTrue(os.path.isfile(os.path.join(d, "aux-repo", "meta.conf")))
self.assertEqual(sorted(os.listdir(self.mirror)), [DISK_ABI, "releases"])
mint = os.path.join(d, "MINT", VERSION, "latest", "All", f"opnsense-update-{VERSION}.pkg")
self.assertTrue(os.path.samefile(mint, os.path.join(latest, "All", f"opnsense-update-{VERSION}.pkg")))
rel = os.path.join(self.mirror, "releases", SERIES)
@ -250,7 +253,7 @@ class StageTest(Base):
code, text = run_main(["stage", "--sets", out, "--mirror", self.mirror, "--series", "26.7",
"--version", "26.7.9", "--upgrade-from", SERIES])
self.assertEqual(code, 0, text)
old_sets = os.listdir(os.path.join(self.mirror, ABI, SERIES, "sets"))
old_sets = os.listdir(os.path.join(self.mirror, DISK_ABI, SERIES, "sets"))
for name in ("packages-26.7.9-aarch64.tar", "base-26.7.9-aarch64.txz",
"kernel-26.7.9-aarch64-GATEWAY.txz"):
self.assertIn(name, old_sets)
@ -411,7 +414,7 @@ class VerifyRootTest(Base):
self.staged()
bad = os.path.join(self.tmp, "bad")
write_repo(self.keys, bad, GOOD_PACKAGES, abi="FreeBSD:14:amd64")
latest = os.path.join(self.mirror, ABI, SERIES, "latest")
latest = os.path.join(self.mirror, DISK_ABI, SERIES, "latest")
shutil.rmtree(latest)
shutil.copytree(bad, latest, symlinks=True)
self.assertFails("ABI 'FreeBSD:14:amd64' not in")
@ -543,6 +546,11 @@ class _Handler(http.server.SimpleHTTPRequestHandler):
def log_message(self, *a):
pass
def translate_path(self, path):
# mirror paths are stored under other names on disk, as the nginx container maps them
path = urllib.parse.unquote(path.split("?", 1)[0].split("#", 1)[0])
return super().translate_path("/" + g.disk_rel(path.lstrip("/")))
def translate(self):
path = self.path.split("?", 1)[0]
if path == "/healthz":
@ -685,6 +693,62 @@ class VerifyUrlTest(Base):
g.main(["verify", "--url", "https://localhost"])
class DiskNameTest(Base):
def test_disk_rel(self):
for rel, disk in ((f"{ABI}/{SERIES}/latest/meta.conf", f"{DISK_ABI}/{SERIES}/latest/meta.conf"),
(f"{ABI}/{SERIES}/aux/All/x.pkg", f"{DISK_ABI}/{SERIES}/aux-repo/All/x.pkg"),
(f"{ABI}/{SERIES}/aux", f"{DISK_ABI}/{SERIES}/aux-repo"),
("FreeBSD:15:aarch64", "FreeBSD_15_aarch64"),
(f"{ABI}/{SERIES}/latest/aux", f"{DISK_ABI}/{SERIES}/latest/aux"),
(f"{ABI}/MINT/aux", f"{DISK_ABI}/MINT/aux"),
("releases/26.1/aux", "releases/26.1/aux"),
("FreeBSD:14:amd64/26.1/aux", "FreeBSD:14:amd64/26.1/aux"),
("healthz", "healthz")):
self.assertEqual(g.disk_rel(rel), disk, rel)
self.assertEqual(g.abi_of_disk_name(DISK_ABI), ABI)
for name in (ABI, "FreeBSD_14_amd64", "FreeBSD__aarch64", "releases", "FreeBSD_14_aarch64x"):
self.assertIsNone(g.abi_of_disk_name(name), name)
def test_staged_tree_has_portable_names(self):
self.staged()
self.assertEqual(g.share_name_problems(self.mirror), [])
def test_share_name_problems(self):
root = os.path.join(self.tmp, "names")
bad = ["a:b", "aux", "AUX.txt", "con", "Nul.pkg", "com1", "lpt9.x", "a*b", 'q"x', "a<b", "a>b",
"a|b", "a?b", "a\\b", "trail.", "trail ", "ctl\x01"]
good = ["aux-repo", "auxiliary", "console", "a+b,1~2.pkg", "py311-x-1.0_1,1.pkg", "x" * 255,
".hidden:x", "MINT"]
os.makedirs(os.path.join(root, "sub", "Dir"))
for name in bad + good:
open(os.path.join(root, name), "w").close()
open(os.path.join(root, "sub", "dir"), "w").close()
open(os.path.join(root, "sub", "Dir", "aux"), "w").close()
found = dict(g.share_name_problems(root))
for name in bad:
self.assertIn(name, found, name)
for name in good:
self.assertNotIn(name, found, name)
self.assertIn("only in case", found[os.path.join("sub", "dir")])
self.assertIn(os.path.join("sub", "Dir", "aux"), found, "checked in subdirectories")
def test_verify_root_rejects_unportable_names(self):
d = self.staged()
open(os.path.join(d, "latest", "All", "Opnsense-update-1.pkg"), "w").close()
open(os.path.join(d, "latest", "All", "opnsense-update-1.pkg"), "w").close()
self.assertFails("only in case")
def test_verify_root_rejects_unmapped_abi_dir(self):
self.staged()
shutil.copytree(os.path.join(self.mirror, DISK_ABI), os.path.join(self.mirror, ABI))
self.assertFails(f"{ABI}: name cannot be stored")
def test_verify_root_rejects_unmapped_aux_dir(self):
d = self.staged()
os.rename(os.path.join(d, "aux-repo"), os.path.join(d, "aux"))
self.assertFails("aux: name cannot be stored")
class PublishTest(Base):
def test_publish_copies_verified_tree(self):
self.staged()
@ -694,7 +758,7 @@ class PublishTest(Base):
code, text = run_main(["publish", "--mirror", self.mirror, "--dest", dest,
"--fingerprints", self.keys.ours, "--upstream-fingerprints", self.keys.upstream])
self.assertEqual(code, 0, text)
latest = os.path.join(dest, ABI, SERIES, "latest", "Latest", "opnsense.pkg")
latest = os.path.join(dest, DISK_ABI, SERIES, "latest", "Latest", "opnsense.pkg")
self.assertTrue(os.path.isfile(latest) and not os.path.islink(latest), "symlinks become files")
self.assertFalse(os.path.exists(os.path.join(dest, "stale")))
code, text = run_main(["verify", "--root", dest, "--fingerprints", self.keys.ours,
@ -711,6 +775,16 @@ class PublishTest(Base):
self.assertEqual(code, 1, text)
self.assertEqual(os.listdir(dest), [])
def test_publish_refuses_unportable_names(self):
d = self.staged()
open(os.path.join(d, "sets", "con"), "w").close()
dest = os.path.join(self.tmp, "dest")
os.makedirs(dest)
code, text = run_main(["publish", "--mirror", self.mirror, "--dest", dest,
"--fingerprints", self.keys.ours, "--upstream-fingerprints", self.keys.upstream])
self.assertEqual(code, 1, text)
self.assertEqual(os.listdir(dest), [])
def test_publish_needs_existing_dest(self):
self.staged()
with self.assertRaises(SystemExit):