diff --git a/CLAUDE.md b/CLAUDE.md index 6cceaa7..b99a875 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,6 +22,12 @@ session. **Update it as you go.** - `GLACIER_BOOTSTRAP.txt`: `glacier-bootstrap`. Local mode is IMPLEMENTED (ROADMAP 1.3; section 10 says how it differs from the plan); remote mode and `--pin` are still a plan. Open: 9a, 9f. + - `DOCKER_BUILDS.txt`: how to build recipes in Docker (the user's + instructions; keep it current when builds change). + - `BUILD_DESIGN.txt`: building from source (ROADMAP 4.3). Section 1 + = the user's decisions; section 12 = how steps 1-4 came out (DONE + 2026-10-19); section 13 = prefix, kept packages, first recipes; + step 5 (Everest) next. - `REPO_DESIGN.txt`: remote repos + signing (ROADMAP 3.1). Sections 1 and 10 = the user's decisions (TLS library still open); steps 1-4 of section 9 DONE (see "3.1 status"); sections 7, 5 and 6 @@ -74,6 +80,275 @@ flag. `-h` goes to stdout, exit 0; usage errors stay one usage block on stderr, exit 1. repo_alpine.sh checks the help of grepo/gsign/gsha256sum. Backups: `glacier-bootstrap.old2`, `gworld.old`, `tests/repo_alpine.sh.old5`. +2026-10-19: source builds planned as ROADMAP 4.3 (the user's four +decisions are recorded there; the open ones are in ROADMAP 6). +`TESTING.txt` holds the manual test steps; they have not been run yet. +Same day, second session: BUILD_DESIGN.txt written with the user +(every decision in its section 1: builds through gpkg/syspkg -f/-u; +recipe repos named NAME-src; a named package several repos serve is +ASKED about (replaces "first repo wins" for named packages; deps keep +priority); user-namespace sandbox; flat cached layers per scope; +syspkg builds as BUILD_USER; the switches are called TRAITS (not "USE +flags"), per-package files in /etc/glacier/config and +/glacier/usr//config; libconfig recipes; toolchain in extra), and +steps 1-4 implemented: see "Source builds" below. Backups made: +`lib/glacier_cdef.lua.old2`, `lib/gpkg_common.lua.old5`, +`syspkg.old2`, `gpkg.old2`, `Dockerfile.{alpine_root,alpine,arch,debian}.old`, +`tests/installed_alpine.sh.old`, `tests/fetch_alpine.sh.old3`, +`etc/glacier/glacier.conf.old`; Everest `scripts/container.sh.old5`. + +Same day, third session: the user chose (BUILD_DESIGN 1o-1q) that +builds compile for the PREFIX they're linked under, that installed +source builds are KEPT as layers, and that recipes live in +`~/Projects/everest/recipes/extra-src/NAME/`. Done and tested (section +13): recipes for ncurses, vim, less, zstd, lua (all build and run in +Docker), `tests/mkgrcp`, `tests/buildenv`, `run_docker.sh -b`, curl in +Dockerfile.alpine_root, curl -L for sources. Build instructions: +DOCKER_BUILDS.txt. Then, at the user's request: build output on the +terminal by default, `-q`/`--quiet` (gpkg + syspkg, a modifier; +log.c help lists it) to hide it; `-V` no longer controls it. Backups: `lib/gpkg_build.lua.old`/`.old2`, +`lib/build-driver.sh.old`, `lib/gpkg_common.lua.old6`, +`tests/build_alpine.sh.old`/`.old2`, `run_docker.sh.old`, +`Dockerfile.alpine_root.old2`, `gpkg.old3`, `syspkg.old3`, +`lib/gpkg_common.lua.old7`, `lib/gpkg_build.lua.old3`, +`tests/build_alpine.sh.old3`. + +### 2026-10-21 session: STOPPED HERE (user: "save your work and stop") + +The user asked for: (1) the recipe parser to say WHY a recipe is +malformed, (2) the toolchain and build environment baked into the +QEMU live image (their choice over a Docker image of Everest), (3) all +of DOCKER_BUILDS' test steps doable inside the Everest VM. Also done +first: `Dockerfile.alpine_root` has `/app` on PATH (ENV + profile.d) +and `permit nopass glacier as root` (user_layout_alpine.sh resets +doas.conf to the pinned rule first); the user's bash recipe fixed +(`sha256i:` typo, CONFIGURE `--disable-nls --without-bash-malloc`; +backup `recipes/extra-src/bash.recipe.old`, outside the recipe dir). + +DONE and tested (full regression green after each; mutation-checked): +- `gl_recipe_error()` (pkg.h; setter `gl_recipe_set_error` in + recipe.h, internal): every gl_recipe_parse / gl_recipe_read refusal + records a reason (field, entry number, rule; libconfig line + error; + bundle entry at fault), non-printable bytes as '?'; reset on each + call. grepo prints `%s is a bundle with a malformed recipe: REASON.` + (and for unreadable/invalid bundles); gpkg_build prints `ID has a + malformed recipe bundle: REASON.`. recipe_alpine.sh 204 checks. + read_strings takes a `what` description (also used by + gl_conf_build; its own "Malformed FILE." still has no reason: + offered to the user, not done). +- User choice: gpkg builds may stack BASE packages as layers (Everest's + BUILD_ROOT names musl, busybox). `load_indexes` returns the install + list (no base/base-src in user scope, as before) plus `.layers` + (base included); only `layer_plan` reads `.layers`. build_alpine.sh + "gpkg: base packages as build layers". +- User choice: HARDLINKS. They were silently skipped at extraction + (binutils' `ld` -> ld.bfd, gcc's c++ etc. never installed). Now the + library REFUSES a package with a hardlink entry (`Refusing archive + entry 'P': it is a hardlink.`, extract_tree in istoreutils.c), and + gbuild + build-driver.sh turn hardlinks into plain copies before + packing (find -links +1, cp -p, mv). Tests: audit_alpine.sh + "hardlinks", keyring_alpine.sh "gbuild: hardlinks become files", + build_alpine.sh "hardlinks in a build's output". +- keyring_alpine.sh needs NETWORK (its gbuild section `apk add bash`): + with --network none it stops at "apk failed" after 62 checks + (73 in full). Earlier "full regression" runs had that blind spot. +- Everest: binutils `--without-debuginfod`, gcc `--without-zstd` + (they had linked libdebuginfod/libzstd from the Alpine build + container; checked with scanelf over every package: nothing else + missing). gcc package 91 MB (stripped). Template has linux-headers, + binutils, make, gcc (EXTRA_PKGS now ""). `container.sh initramfs` + copies repo/ into T at /srv/everest (root-owned) and rewrites T's + repos.conf urls to file:///srv/everest/REPO. `everest.sh boot` adds + `-virtfs ... mount_tag=everest-repo` (repo/ live, read-only); + scripts/vm-testnet.sh mounts it over /srv/everest and writes + `nameserver 10.0.2.3` (builds download sources). Everything rebuilt + (linux with namespaces/overlay, bootscripts 1.4.0 with _gbuild, + everest-repos 1.1.0, libglacier-ng, glacier-ng, binutils, gcc), + published (serial 2026102103), initramfs made (288 MB gz, 546 MB + unpacked). +- Verified in QEMU (EVEREST_MEM=8192 EVEREST_CPUS=8, driven by a pty + script): kernel has user/pid/net ns + overlay, _gbuild exists, + repos.conf file://, 9p mount, gcc and g++ compile and run. + +### 2026-10-22: builds work in the QEMU image + +- LIVE BOOT on a tmpfs (fixes `Cannot enter the build root: Invalid + argument`: pivot_root(2) refuses the initramfs rootfs). + `scripts/live-init.sh` is packed by `container.sh initramfs` as a + SECOND cpio (gzip appended, not in T, no package) at `/init`: tmpfs + (size=90%) on /.live, `cp -a` of every top-level entry, `exec + switch_root /.live /sbin/init`; on failure it falls back to booting + the initramfs. `everest.sh boot`: `rdinit=/init`, EVEREST_MEM default + 6144. +- gcc ships `usr/bin/cc -> gcc` (container.sh build_gcc AND the + extra-src gcc recipe; zstd's plain Makefile calls cc). gcc 16.2.0 + rebuilt in place. Recipe backup: `recipes/extra-src/gcc.build.old`. +- gsandbox mounts the build overlay with `userxattr` (retried without + on EINVAL, kernels < 5.11). Without it overlayfs in a user namespace + can't set trusted.* xattrs ("failed to set xattr on upper"), so a + layer's directory removed and remade showed the layer's old files. + sandbox_alpine.sh "a layer's directory remade in the root is empty" + (47 checks; mutant without userxattr caught); build_alpine.sh 142 + green. Everest's libglacier-ng rebuilt in place, published, + initramfs remade. +- Verified in QEMU (`scripts/vm-drive.py LOG scripts/vmtests/builds.txt`, + a pty driver: 8 GB, 8 CPUs): / is tmpfs; `syspkg -f vim` (ncurses as + dependency), `syspkg -f less zstd lua bash`, all run; `cc` compiles; + vim `TRAITS = [ "-huge" ]` + `syspkg -u` rebuilds it (Huge -> Normal); + a user's `gpkg -f zstd` (gstore -n as root) builds and links into + /glacier/usr/1000/links; no xattr warnings in dmesg. +- Seen, not changed: `syspkg -u` for a trait change prints `[!] + Reinstalling vim-9.2.1209 (up to date)` before staging the rebuild. +- JOBS is still unset in the image (builds -j1; the test appends + `JOBS = 8;`). Not decided whether the image should set it. +- Backups: Everest `scripts/container.sh.old8`, `everest.sh.old6`; + glacier-ng `tests/sandbox_alpine.sh.old`. Nothing committed. +- Docs not written yet: Everest README (VM build testing: boot, + vm-testnet, syspkg -f, publish + 9p for recipe edits), DOCKER_BUILDS, + ROADMAP 4.3/6, REPO_DESIGN 10a, BUILD_DESIGN (base layers for gpkg, + hardlinks), the CLAUDE.md sections below. + +Backups made this session: glacier-ng `Dockerfile.alpine_root.old3`, +`tests/user_layout_alpine.sh.old`, `lib/glacier_cdef.lua.old3`, +`lib/gpkg_build.lua.old4`/`.old5`, `tests/recipe_alpine.sh.old`, +`lib/gpkg_common.lua.old8`, `tests/build_alpine.sh.old4`, `gbuild.old`, +`lib/build-driver.sh.old2`, `tests/audit_alpine.sh.old2`, +`tests/keyring_alpine.sh.old`; Everest `scripts/container.sh.old7`, +`everest.sh.old5`, `templates/minimal.template.old4`, +`scripts/vm-testnet.sh.old`. Nothing committed. + +### Toolchain + https in base: IN PROGRESS (2026-10-19, fourth session) + +Stopped mid-way at the user's request. The user asked for the +toolchain steps (Phases 1-4 below) and decided: +- **TLS: LibreSSL 4.3.3** (REPO_DESIGN 10a; curl 8.23 dropped BearSSL). + curl 8.23.0, libressl, ca-certificates (curl.se's Mozilla bundle as + `/etc/ssl/cert.pem`, VER 2026.9.25) all in BASE and in the template. +- **gcc-libs in base** (libstdc++, libgcc_s, ...; settles ROADMAP 6's + libgcc question); gcc, binutils, make, linux-headers in extra. +- **BUILD_USER `_gbuild`** (uid/gid 900, in everest-bootscripts 1.4.0). +- **Repo URL `https://pkg.everestlinux.org/REPO`** (base, extra, + extra-src) in everest-repos 1.1.0. The server doesn't exist: tests + serve `~/Projects/everest/repo/` under that name with a throwaway + TEST CA (`testca/`), never shipped: initramfs inside its container + (`serve_local`), `everest.sh boot` to the VM (openssl s_server on + 127.0.0.1:8443, QEMU guestfwd 10.0.2.100:443 via socat; the VM runs + `sh /sys/firmware/qemu_fw_cfg/by_name/opt/everest/testnet/raw` = + `scripts/vm-testnet.sh`: network, hosts entry, CA appended). +- Phases: 1 build the packages, 2 test them as BUILD_ROOT in Docker, + 3 publish + initramfs + QEMU, 4 toolchain as extra-src recipes, + rebuilt with itself (`everest.sh adopt`), republished. + +Done (all in ~/Projects/everest unless said): +- Sources pinned by SHA256 in `container.sh`'s `fetch URL SHA` (cached + in `sources/`), every one checked against upstream's signature: + gcc/binutils/make/ncurses (gnu-keyring), curl (Stenberg's key), + kernel (kernel.org autosigner's sha256sums.asc), LibreSSL (signify), + cacert (curl.se's .sha256); gcc's gmp/mpfr/mpc/isl against + prerequisites.sha512 from the signed gcc tarball. +- `container.sh`: cases libressl, ca-certificates, curl (removes the + image's openssl-dev, installs LibreSSL into the throwaway container, + links against it: checked NEEDED libssl.so.60/libcrypto.so.57), + linux-headers (`make headers` + copy .h: headers_install needs + rsync), binutils (2.47.0: VER must be X.Y.Z), make (CFLAGS -std=gnu17: + 4.4.1 isn't C23-clean), gcc|gcc-libs (`build_gcc`: one build, two + packages; triple `x86_64-everest-linux-musl`, `t-linux64` sed so no + lib64, `--disable-bootstrap`, `--with-local-prefix=/glacier/sys/links`; + binutils `--with-lib-path=/usr/lib:/glacier/sys/links/lib`); linux + config adds NAMESPACES/USER_NS/PID_NS/IPC_NS/UTS_NS/NET_NS/OVERLAY_FS/ + FW_CFG_SYSFS; glacier-ng installs Everest's own + `pkgsrc/glacier-ng/etc/glacier/glacier.conf` (BUILD_ROOT = musl, + busybox, linux-headers, binutils, gcc, make; BUILD_USER _gbuild); + `adopt DIR`, `publish` (template + EXTRA_PKGS routed by manifest + PKG_REPO; extra-src = mkgrcp of recipes/extra-src; grepo with + everest-2026), `testca`, `serve_local`. `everest.sh`: PACKAGES + extended, `publish`, `adopt DIR` (MOUNT= extra mount in + `in_container`), `boot` (EVEREST_MEM default 2048, EVEREST_CPUS 2, + serves repo/ when repo/ and testca/ exist). Dockerfile.build: curl, + openssl. Template: libressl, ca-certificates, curl, gcc-libs, + bootscripts 1.4.0, everest-repos 1.1.0. +- Recipes `recipes/extra-src/{binutils,gcc,make,linux-headers}` (all + nine recipes parse: mkgrcp + grepo OK). Toolchain recipes use + `--prefix=/usr` and install into DESTDIR/usr on purpose (they are + build layers, which sit at /usr), so the driver leaves them alone. +- BUILT and signed in pkgs/: libressl 4.3.3, ca-certificates + 2026.9.25, curl 8.23.0, binutils 2.47.0, gcc 16.2.0, gcc-libs 16.2.0. + +NOT done / next, in order: +1. Rebuild (container.sh already fixed, not yet run): `make`, + `linux-headers` (both failed: C23, rsync), `binutils` and `gcc` + (now `install-strip`: gcc's package was 785 MB unstripped; libcc1 + moved out of gcc-libs). Then `linux` (new config; pkgs/ still has + the 2026-10-06 build), `everest-bootscripts` (1.4.0), + `everest-repos` (1.1.0), `libglacier-ng` and `glacier-ng` (4.0.0 in + place: this session's -q, prefix, kept packages, Everest + glacier.conf). Background script: scratchpad `blogs/run.sh` (lost + with the session; it just loops `./everest.sh build P`). +2. Phase 2: `./everest.sh publish`, then the Docker test written in + the session, saved as `scripts/toolchain-test.sh` (its header says + how to run it) (glacier-alpine_root, -b options, repo/ mounted at + /srv/everest as file:// repos keyed everest-2026, BUILD_ROOT = the + Everest toolchain, `syspkg -q -f vim less zstd lua`). Unknown yet: + whether the real musl package (top-level `lib/ld-musl...`) stacks + with gsandbox's skeleton (`/lib -> usr/lib`) as a layer. +3. Phase 3: `everest.sh initramfs` (bootstrap syncs from serve_local), + boot with EVEREST_MEM=6144, vm-testnet, `syspkg -y`, + `syspkg -f gcc binutils make`, `gcc hello.c`, `syspkg -f vim`. +4. Phase 4: build the 4 toolchain recipes with the stage-1 toolchain + (in Docker; `-fO`, answer "2" for extra-src), copy + `/glacier/sys/build/packages/extra@*.gpkg` out, `everest.sh adopt + DIR` (stage-1 files move to pkgs/stage1/), publish, re-test. +5. Docs: Everest README (new packages/commands), REPO_DESIGN 10a, + ROADMAP 4.3/6, DOCKER_BUILDS (Everest toolchain), this section. + +Backups (Everest): `scripts/container.sh.old6`, `everest.sh.old4`, +`Dockerfile.build.old2`, `templates/minimal.template.old3`, +`README.md.old4` (README not edited yet), +`pkgsrc/everest-bootscripts/accounts.old/{passwd,group,shadow}`, +`pkgsrc/everest-repos/repos.conf.old`. New files: `scripts/vm-testnet.sh`, `scripts/toolchain-test.sh`, +`pkgsrc/glacier-ng/etc/glacier/glacier.conf`, `sources/` (cache). + +### Source builds (2026-10-19) + +- Formats (libglacier-ng): recipe = libconfig (`gl_recipe_parse`, + strict); bundle `NAME-VER.grcp` (`gl_recipe_read`, src/recipe.c); + `-src` indexes (`gl_index_parse` by REPO suffix); `PKG_TRAITS` in + manifests; `gl_conf_build` (glacier.conf / user / per-package build + settings, unknown keys INVALID: glacier.conf's allowed keys are now + KEEP_OLD, TRAITS, CFLAGS, CXXFLAGS, LDFLAGS, JOBS, BUILD_USER, + BUILD_ROOT, when a build reads it). `grepo -r X-src`. +- `gsandbox` (src/gsandbox.c, installed to lib/glacier beside the .so's, + copied to /app/lib/glacier by every Dockerfile): `-X` extract a layer + (`gl_extract_files`, the install's own extraction, now + `extract_tree()`), `-R` run a build in user/mount/net/pid/ipc/uts + namespaces (root needs `-u USER`, refuses uid 0). +- glacier-ng: `lib/gpkg_build.lua` (traits, settings, layers, the + build), `lib/build-driver.sh` (runs inside), gpkg_common's `choose`, + `confirm_builds`, `.glacier-src` marker (`gl_set_pkg_src` / + `gl_pkg_src`), machine key (`/etc/glacier/keys/local.pub`, + `/glacier/sys/keys/local.sec`; base-src needs "local" in base's keys). + syspkg checks gsandbox + driver ownership only when a build is planned. +- PREFIX (env, driver): `/usr` for base, else `ctx.links_path`; the + driver installs into `DESTDIR$PREFIX`, moves it to `usr/`, and links + `$PREFIX -> /usr` inside the sandbox. Kept packages: + `/build/packages/REPO@NAME-VER.gpkg` (`M.keep`, `M.prune_kept` + after every commit, `M.kept` for `layer_plan`: built, then kept, then + binary). +- Docker builds: `./run_docker.sh -b Dockerfile.alpine_root`, then + `/app/tests/buildenv` (rerun after editing a recipe), then + `syspkg -f vim`. The recipe tree is mounted at `/recipes`. +- Tests: `recipe_alpine.sh` (117), `sandbox_alpine.sh` (47), + `build_alpine.sh` (137); 10 + 7 C and 27 Lua/driver mutants, all + caught. + `tests/mkroot` packs Alpine packages (`-r` with deps) as a .gpkg. + Sandbox suites need `--security-opt seccomp=unconfined --security-opt + apparmor=unconfined --security-opt systempaths=unconfined` and a tmpfs + (overlayfs can't sit on Docker's own overlay root): see each header. +- Everest: NOT rebuilt with this yet (container.sh's glacier-ng install + list already names gpkg_build.lua + build-driver.sh; libglacier-ng's + `make install` puts gsandbox in usr/lib/glacier). No toolchain + packages, and the kernel config's user namespaces are unchecked. + ### Bootstrap repositories (2026-10-07) The user chose: the config comes from a NEW base package @@ -670,19 +945,20 @@ deleted after commit. A base package fetched this way needs no `.sig` `-O`; `-u` and dependency upgrades don't. gpkg never fetches from base. **Package symlinks** are extracted verbatim and linked like files. -Hardlink, device and fifo entries are skipped. `add_to_archive` (used by +Device and fifo entries are skipped; a hardlink entry refuses the +whole package (2026-10-21; packers store hardlinks as files). `add_to_archive` (used by backups and `gstore -b`) archives symlinks. ## CLIs (glacier-ng) | Tool | Flags | Runs as | |---|---|---| -| `gpkg` | `-l FILE...` `-f NAME...` `-u [NAME...]` `-x NAME...` `-y` `-O` `-S` `-V` `-h` `-v` | the user; per-user scope only, NEVER constructs `GL_SCOPE_SYS` | -| `syspkg` | `-n` `-l FILE...` `-f NAME...` `-u [NAME...]` `-x NAME...` `-y` `-O` `-S` `-V` `-R DIR` `--strict` `-h` `-v` | root via doas; `-h`/`-v` without root | +| `gpkg` | `-l FILE...` `-f NAME...` `-u [NAME...]` `-x NAME...` `-y` `-O` `-S` `-V` `-q` `-h` `-v` | the user; per-user scope only, NEVER constructs `GL_SCOPE_SYS` | +| `syspkg` | `-n` `-l FILE...` `-f NAME...` `-u [NAME...]` `-x NAME...` `-y` `-O` `-S` `-V` `-q` `-R DIR` `--strict` `-h` `-v` | root via doas; `-h`/`-v` without root | | `gstore` | `-n [UID]` `-b UID OUTFILE` `-x UID` `-s` (refuses: not implemented) `-V` `-h` `-v` | `-n` needs root (direct, or `doas gstore -n` for yourself) | | `glacier-bootstrap` | `-d PKGDIR TEMPLATE TARGET` `-n` `-t` `-V` `-h` `-v` | the user; borrows root only for `doas syspkg` / `doas chroot` | -- **gpkg:** modifiers `-O`/`-S`/`-V` are applied in a pre-pass, so their +- **gpkg:** modifiers `-O`/`-S`/`-V`/`-q` are applied in a pre-pass, so their position doesn't matter (`-lO` == `-Ol`). It finds its user via `/proc/self/loginuid`, falling back to `getuid()`. Unknown flags are refused (`[x] Unknown option: -R`); gpkg has no `-R`/`--strict`. @@ -808,7 +1084,8 @@ GNU `tar` is required: the hostile-archive fixtures use `tar --append`. |---|---| | `sign_alpine.sh` | `alpine:latest` with `/libsrc` and `/t.sh` mounted | | `syspkg_alpine.sh`, `overwrite_alpine.sh` | `alpine:latest` with `/src`, `/libsrc` and `/t.sh` mounted (see each header); `overwrite_alpine.sh` runs both as-is and with `--tmpfs /glacier:exec` | -| `verify_alpine.sh`, `user_layout_alpine.sh`, `upgrade_alpine.sh`, `sys_perms_alpine.sh`, `deps_alpine.sh`, `sysroot_alpine.sh`, `root_alpine.sh`, `bootstrap_alpine.sh`, `installed_alpine.sh`, `keyring_alpine.sh`, `repo_alpine.sh`, `audit_alpine.sh`, `fetch_alpine.sh` | `glacier-alpine_root` | +| `verify_alpine.sh`, `user_layout_alpine.sh`, `upgrade_alpine.sh`, `sys_perms_alpine.sh`, `deps_alpine.sh`, `sysroot_alpine.sh`, `root_alpine.sh`, `bootstrap_alpine.sh`, `installed_alpine.sh`, `keyring_alpine.sh`, `repo_alpine.sh`, `audit_alpine.sh`, `fetch_alpine.sh`, `recipe_alpine.sh` | `glacier-alpine_root` | +| `sandbox_alpine.sh` (`--tmpfs /work:exec`), `build_alpine.sh` (`--tmpfs /glacier:exec,mode=755`) | `glacier-alpine_root` with `--security-opt seccomp=unconfined --security-opt apparmor=unconfined --security-opt systempaths=unconfined` (user namespaces, overlayfs, /proc) | Build the `glacier-alpine_root` image with: ```sh @@ -838,7 +1115,8 @@ in `./run_docker.sh Dockerfile.alpine_root` using it; for an image, changes) into the scratchpad, break the defence there, then `docker build -f Dockerfile.alpine_root --build-context libglacier=COPY -t glacier-mut .` from the (copied) glacier-ng and run the suite against -`glacier-mut`; delete the image after. Docker tags must be lowercase. A +`glacier-mut`; delete the image after. Docker tags must be lowercase +(a mutant named `L1` failed to build for that reason, 2026-10-19). A mutation that doesn't compile under `-Werror` proves nothing: rewrite it so it compiles. Watch for checks that pass for the wrong reason (e.g. a refusal caused by a missing directory instead of the defence). In shell @@ -852,8 +1130,10 @@ mutate a Lua CLI without rebuilding, bind-mount the mutated file over `/app/NAME` (`-v $PWD/mut:/app/glacier-bootstrap:ro`). **Full regression** = the FFI suite + `syspkg_alpine.sh` + -`overwrite_alpine.sh` (both ways) + `sign_alpine.sh` + the thirteen `glacier-alpine_root` -suites, all in parallel; the two output-based suites (`syspkg_alpine`, +`overwrite_alpine.sh` (both ways) + `sign_alpine.sh` + the sixteen `glacier-alpine_root` +suites, all in parallel (a script doing all of it, kept in the session +scratchpad, is easy to rewrite from this list; count only `^FAIL:` +lines, several suites print `FAILURES: 0`); the two output-based suites (`syspkg_alpine`, `user_layout_alpine`) have no PASS lines, so grep their output for `Unknown|traceback|failed|GL_` instead (only `--bogus` is expected). @@ -863,7 +1143,9 @@ and `debian` default to user `glacier` (uid 1000, in wheel); `alpine_root` defaults to root. All of them have: - root-owned `/app`; - no `/glacier` until `gstore -n` / `syspkg -n`; -- the doas rule plus `permit nopass glacier`; +- the doas rule plus `permit nopass glacier` (`as root` in alpine_root, + 2026-10-21; user_layout_alpine.sh resets doas.conf to the pinned rule + first); alpine_root also has `/app` on PATH (ENV + profile.d); - `/etc/profile.d/glacier.sh` putting `/glacier/usr//links/bin` then `/glacier/sys/links/bin` on `PATH` (and `lib` on `LD_LIBRARY_PATH`) unconditionally, since `/glacier` only appears after login (fixed diff --git a/GLACIER_BOOTSTRAP.txt b/GLACIER_BOOTSTRAP.txt deleted file mode 100644 index 428fd76..0000000 --- a/GLACIER_BOOTSTRAP.txt +++ /dev/null @@ -1,359 +0,0 @@ -+--------------------------------------------+ -| glacier-bootstrap | -+--------------------------------------------+ - -STATUS: LOCAL MODE IMPLEMENTED 2026-10-06 (glacier-ng/glacier-bootstrap, -tests/bootstrap_alpine.sh; see section 10 for how it differs from the -plan below). Remote mode (-r) and the pinning helper are still a plan. -Section 9 lists the decisions still open. - -glacier-bootstrap takes a template index and builds a chrootable -Everest system in a target directory, from either a local directory of -packages or a remote repository. It is the "glacier-bootstrap -TEMPLATE_INDEX TARGET" tool named in SECURITY_DESIGN.txt section 10, and -the `syspkg --root` step of IMAGE_DESIGN.txt's pipeline. - -Companion documents: IMAGE_DESIGN.txt (why images are bootstrap OUTPUT, -the sysroot library change), SECURITY_DESIGN.txt (refusal matrix, -syspkg's privilege model), PACKAGE_SCOPES.txt (link routing). - - -+--------------------------------------------+ -| 1. What it does | -+--------------------------------------------+ - - glacier-bootstrap [-n] [-t] (-d PKGDIR | -r URL) TEMPLATE TARGET - - -d PKGDIR packages come from a local directory (gbuild/gworld - output: NAME-VER.gpkg plus NAME-VER.gpkg.sha256) - -r URL packages come from a remote repository (section 5) - -n dry run: parse, resolve, fetch, verify, print the plan; - never touch TARGET - -t after installing, smoke-test: chroot TARGET /bin/sh -c true - -Sequence: - - 1. parse TEMPLATE (section 3) - 2. resolve: check the package list is complete (section 4) - 3. fetch into a private cache; verify every hash (section 5) - 4. doas syspkg --root TARGET -n create the tree - 5. doas syspkg --root TARGET --strict -l PKG... ONE transaction - 6. doas syspkg --root TARGET -y TARGET's indexes - 7. optional smoke test (-t) - -Step 5 is one transaction on purpose: TARGET ends up either the whole -system or an empty tree, never half a system. - - -+--------------------------------------------+ -| 2. Trust and privilege | -+--------------------------------------------+ - -glacier-bootstrap NEVER WRITES INTO TARGET ITSELF. Every byte under -TARGET goes through `doas syspkg --root TARGET`. - - - SECURITY_DESIGN.txt section 5: syspkg owns ALL system-scope - mutation, "one tool to secure, one tool to audit." A bootstrapper - that extracted packages itself would be the second, unaudited entry - point that section warns about. - - glacier-bootstrap runs UNPRIVILEGED. Parsing, resolving, fetching and - verifying need no root, so it needs no third copy of the hardened - root-loading preamble (syspkg and gstore already carry it; CLAUDE.md - flags the duplication). Root is borrowed only for the two syspkg - calls. - - Its own verification is early-fail, for good error messages. syspkg's - is authoritative: syspkg re-hashes every file at the moment it - reads it (refusal matrix, SECURITY_DESIGN section 4). So a file - swapped in the cache between bootstrap's check and syspkg's read is - caught. The cache is the invoking user's (0700). The only party who - could swap files there is the person who can already run doas - syspkg. - -Where trust comes from, per source: - - local (-d) The sidecar next to each .gpkg, same as syspkg today. - INTEGRITY ONLY, which is all the current tree offers - anywhere. - - remote, pinned The TEMPLATE pins each package's sha256 (section 3). - glacier-bootstrap writes the sidecar FROM THE PIN, not - from anything the server sent. So syspkg's existing - "sidecar matches file" check enforces the template's - hash, with no syspkg change needed. The server is an - untrusted blob store. Authenticity is exactly as good - as the template file's, which you hold locally and can - review or diff. - - remote, signed Later: a signed repo index (the agreed next major item - after the checkpoints). Only then may a template name a - remote package without a pin. - - remote, unpinned and unsigned: REFUSED. A .gpkg and its .sha256 - fetched from the same server prove nothing (SECURITY_DESIGN section 1: - the hash travelling with the file). - - -+--------------------------------------------+ -| 3. Template index format | -+--------------------------------------------+ - -Extends IMAGE_DESIGN.txt section 5's KEY=value proposal with one line -per package, so packages can carry pins: - - # templates/minimal.template - NAME=minimal - PKG=filesystem 1.0.0 - PKG=musl 1.2.5 sha256:3a5f... - PKG=busybox 1.37.0 sha256:91c0... - - - Exact versions only, no ranges. A template describes ONE system, - reproducibly. - - A pin is optional for -d (if present, it must ALSO match the - sidecar) and required for -r until signed repos exist. - - Strict parsing: unknown keys, a duplicate PKG name, a malformed pin - and an empty package list are all hard errors. SYS_PROFILE is an - unknown key (9b): nothing could check it until manifests record a - profile (ROADMAP 3.3). Remember gworld bug - 10: a field silently never parsing, with a default that looks right. - - A `glacier-bootstrap --pin PKGDIR TEMPLATE` helper that fills pins in - from local sidecars is the obvious way to produce a pinned template - from a gworld build. Pinning then becomes a review step, not - hand-copying hex. - - -+--------------------------------------------+ -| 4. Resolution | -+--------------------------------------------+ - -Manifests already carry PKG_DEPS and PKG_CONFS (name + version), and -libglacier parses both into gl_pkg_t. Nothing consumes them today, and -every existing package leaves them empty. (IMAGE_DESIGN.txt section 5 -says glacier has no runtime deps at all. The format exists; the use -doesn't.) - -Recommendation: CHECK, don't auto-resolve. - - - Every PKG_DEPS entry of every listed package must itself be listed, - at that version or later (decided 2026-10-06: the ROADMAP 2.3 rule, so - the template check and syspkg's commit check agree). Otherwise error: - "base::busybox requires musl >= 1.2.5, which the template does not - list." / "..., but the template lists 1.2.4." - - No two listed packages may conflict (PKG_CONFS). - - Each manifest's PKG_NAME/PKG_VER must match its template line. This - catches a mis-named file in -d mode, where there may be no pin. - -Why not pull dependencies in automatically: anything auto-added would be -an unpinned package the template's author never reviewed, which defeats -the trust model in section 2. Closure resolution can come with signed -repos. - -SYS_PROFILE can't be checked against packages yet: manifests don't -record which profile they were built under (open item in CLAUDE.md). -Once they do, a mismatched package is a resolution error. - - -+--------------------------------------------+ -| 5. Package sources | -+--------------------------------------------+ - -LOCAL (-d PKGDIR): a flat directory, exactly what gbuild emits — -NAME-VER.gpkg, NAME-VER.gpkg.sha256. No index file. The template's -package list says what to take from the directory. - -REMOTE (-r URL): the same flat layout over HTTPS: - - URL/NAME-VER.gpkg - - - Fetch by shelling out to curl (`--proto =https --fail`), the same - way gbuild shells out to git and tar, into - $XDG_CACHE_HOME/glacier-bootstrap/ (0700) under a temporary name. - Hash it, and only then rename it into place. - - Server-provided .sha256 files are never consulted (section 2). - - Cache hits are re-hashed against the pin on every run. The cache is - a download optimization, not a trusted store. - - Later, with signing: URL/repo.idx plus its signature, listing name, - version, repo and hash. The fetch path stays the same. - - -+--------------------------------------------+ -| 6. What "chrootable" requires | -+--------------------------------------------+ - -Found while planning, by reading the code and the packages in pkgs/. -Each one is a hard blocker for `chroot TARGET /bin/sh` working at all, -independent of glacier-bootstrap itself: - - a. [FIXED 2026-10-04 — extraction + linking, with both defenses - below; tests/test_package_symlinks.lua] SYMLINKS IN PACKAGES ARE - DROPPED. The extraction loop in - gl_install_pkg handles only AE_IFDIR and AE_IFREG (istoreutils.c); - symlink entries never reach the store. gl_link_pkg likewise links - only regular files. Real packages need symlinks: - - musl ships lib/ld-musl-x86_64.so.1 -> /usr/lib/libc.so. That is - the dynamic loader every musl binary asks the kernel for. It is - currently never installed; Alpine-based tests passed only - because Alpine provides its own. - - shared-library soname links (libz.so.1 -> libz.so.1.3.1); - - busybox applets. - Fix: extract symlink entries verbatim into the store, and link - them like regular files. SECURITY TRAP to design around: an archive - shipping `x -> /etc` followed by `x/passwd` writes through the - symlink, as root, into the real /etc (classic tar-slip via - symlink). Extraction must never write through a symlink: create - symlinks only after every regular file, and/or refuse any entry - whose parent path is a symlink in the store. - - b. [DONE 2026-10-04 — gl_create_fs_tree, run by syspkg -n; takes a - root prefix ready for --root; tests/test_fs_tree.lua] NO TOP-LEVEL - TREE. Base packages link only under /usr - (PACKAGE_SCOPES section 3), and a leading "usr/" is the only prefix - stripped. So musl's lib/ld-musl... would land at /usr/lib, while - PT_INTERP says /lib/ld-musl-x86_64.so.1. TARGET needs merged /usr: - /bin -> usr/bin /lib -> usr/lib /sbin -> usr/bin - plus the mountpoints and dirs nothing ships: /dev /proc /sys /tmp - (1777) /run /var /root /home /etc. No package can provide these - under the current link rules (everything base goes under /usr). - Recommendation: `syspkg -n` creates this skeleton as part of - system init (under --root, and on a real system). Creating the - system's skeleton is system-scope mutation, so it belongs to - syspkg, not to the bootstrapper. - - c. [DONE 2026-10-04 — decision 9c, option 1; tests/test_config_files.lua] - /etc HAS NO STORY. A base package's etc/passwd would link to - /usr/etc/passwd. And config files can't simply be symlinks into - the store anyway: editing them would modify the store and break - its hashes. This needs its own decision (section 9c). For the first - chroot milestone, the skeleton step can write a minimal - /etc/passwd and /etc/group (root only), and /etc/profile. - - d. NO SHELL. The only packages that exist are musl, kilo and sbase, - and sbase is coreutils with no sh. A busybox (or mksh/dash) recipe - in base is needed. - - e. REPO TIERS. sbase's manifest says PKG_REPO = "core", which is not - a tier (base / extra / community). Under system scope it would link - into /glacier/sys/links, not /usr/bin. Rebuild it as base. - - f. [sidecars generated for the existing archives 2026-10-04] NO - SIDECARS. None of pkgs/*.gpkg has a .sha256. They were built - before checkpoint 2. Rebuild them with the current gbuild. - - -+--------------------------------------------+ -| 7. Prerequisites, in order | -+--------------------------------------------+ - - 1. [DONE] Hash verification at install time (SECURITY_DESIGN - section 4). Pins mean nothing until syspkg actually checks sidecars. - 2. [DONE] Symlink extraction + linking, with the write-through-symlink - defense (6a). Needed for anything to run. - 3. [DONE 2026-10-05] sysroot in the library (IMAGE_DESIGN section 3), plus the "host - /usr and /glacier untouched" test. - 4. [DONE 2026-10-05, as -R/--root] syspkg --root DIR (IMAGE_DESIGN section 4), --strict (any link - refusal fails the transaction), and the skeleton on -n (6b) [the - skeleton is DONE; --root and --strict are not]. - 5. [DONE: ~/Projects/everest builds musl, busybox, linux and - everest-bootscripts, all base, with sidecars.] Packages: busybox - recipe (base), sbase rebuilt as base, every - package rebuilt with sidecars (6d-f). - 6. [DONE 2026-10-06: Everest's `everest.sh initramfs` now builds its - tree this way, and the result boots in QEMU.] glacier-bootstrap, - local mode. - MILESTONE: `glacier-bootstrap -t -d pkgs templates/minimal.template - /mnt/everest` succeeds, `chroot /mnt/everest /bin/sh` gives a - working shell, and the host is byte-identical before and after. - 7. Remote mode with pinned templates, plus the --pin helper. - 8. Signed repo index (separate design pass), then unpinned remote. - -1 and 2 are independent and can go in either order. 3 and 4 are the -bulk of the library/syspkg work. 6 itself is small: it's mostly -orchestration over things that have to exist anyway. - - -+--------------------------------------------+ -| 8. Implementation shape | -+--------------------------------------------+ - - - LuaJIT, in glacier-ng, alongside gworld. It shares gworld's - KEY=value parsing (factor that into lib/ rather than copy it), and - reads manifests through libglacier's existing parser via FFI, so - PKG_DEPS etc. parse exactly the way syspkg will see them. - - Unprivileged, so the CWD-relative require convention is fine here. - - Shells out to: curl (remote), doas syspkg, chroot (for -t, via doas). - - Exit codes distinguish parse / resolve / fetch / verify / install - failure, so an image build script can tell them apart. - - -+--------------------------------------------+ -| 9. Open decisions | -+--------------------------------------------+ - - a. IMAGE_DESIGN.txt section 9a still stands: images are bootstrap - OUTPUT, never install INPUT. Everything here assumes yes. - b. DECIDED 2026-10-06: NAME= plus one `PKG=name version [sha256:hex]` - per package; no SYS_PROFILE until manifests record one (section 3). - c. DECIDED 2026-10-04: option 1, copy on install, .new on conflict. - Implemented in istoreutils.c (install_config / prune_config): a - system-scope package's top-level etc/ is copied into /etc, never - linked. An admin-modified, admin-deleted or not-glacier-installed - file is never overwritten; package changes to it are offered once - as FILE.new. Unmodified files are updated in place and removed with - their package. User scope still links etc/ as before (open). - d. DECIDED 2026-10-04: syspkg -n creates the top-level tree itself - (6b). Implemented as gl_create_fs_tree(root, verbose), called by - gl_init_sys before the index is written. - e. DECIDED 2026-10-05: automatic closure, once there is a source to - resolve from (remote repos, ROADMAP 3.1). Until then a missing - dependency refuses; the resolver is written so 3.1 plugs in. The - index already records auto vs explicit installs (ROADMAP 2.3). - Section 4's template check still applies to bootstrap: a template - lists what it installs. - f. Pinning helper: part of glacier-bootstrap (--pin) or of gworld - (which already knows what it just built). - - -+--------------------------------------------+ -| 10. As implemented (local mode, 2026-10-06)| -+--------------------------------------------+ - - glacier-bootstrap [-hvntV] -d PKGDIR TEMPLATE TARGET - -Where it differs from, or adds to, sections 1-8: - - - syspkg is the one on the caller's PATH (decided 2026-10-06), - resolved to an absolute path first and run through doas, or - directly when already root. -t runs `doas chroot`. - - Order: parse, then verify, then resolve. Manifests are read only - from VERIFIED copies: each PKGDIR/NAME-VER.gpkg is copied into a - private mktemp -d while being hashed, checked against its sidecar and - the pin, and given a sidecar written from that hash. syspkg is handed - the copies, so a pin binds syspkg too, and a file swapped in PKGDIR - later is never read. The copies are removed on every exit. - - TARGET must be absolute, not /, and pass gl_check_sysroot (checked - read-only up front). It must be fresh, or initialised by syspkg -n - with nothing installed: then -n is skipped, so a run declined at - syspkg's prompt can simply be repeated. TARGET with packages is - refused. - - syspkg's prompt is passed through (it's the review step). It exits 0 - when declined, so afterwards TARGET's index is read (it's world- - readable) and every template package must be listed. - - Every problem in a phase is reported before failing. Exit status: - 1 usage or target, 2 template, 3 verification, 4 resolution, - 5 installation, 6 smoke test, 7 repositories. - - Repositories (2026-10-07; the user: bootstrap must leave a - semi-functional system, so it configures repositories, pacstrap - style). The configuration comes from a PACKAGE in the template - (Everest: everest-repos, shipping /etc/glacier/repos.conf and - keys/*.pub), so bootstrap still never writes into TARGET. After the - install check, if TARGET's repos.conf gives any repository a url, - it runs `syspkg -R TARGET -y`: syspkg reads TARGET's OWN keyring - under -R for repository operations (REPO_DESIGN section 6, "Keyrings - under -R"), fetches into TARGET/glacier/sys/repos, and so sets - TARGET's rollback floor at build time. A failed fetch: exit 7, - TARGET stays installed, no "Bootstrapped" line. No repos.conf, or - no url: `[!] No remote repositories are configured in TARGET.` and - exit 0. Copying the host's repos.conf (pacstrap's mirrorlist copy) - is left out for now (user, 2026-10-07). - - Its own lib/ is found from its realpath (package.path and ffi.load), - not the current directory; no root-ownership checks (unprivileged). - - Not implemented: -r (remote) and --pin (9f still open). diff --git a/IMAGE_DESIGN.txt b/IMAGE_DESIGN.txt deleted file mode 100644 index 0648e88..0000000 --- a/IMAGE_DESIGN.txt +++ /dev/null @@ -1,293 +0,0 @@ -+--------------------------------------------+ -| Building Everest system images | -+--------------------------------------------+ - -STATUS: PROPOSAL. Nothing here is implemented, and the items in -section 9 are decisions still to be made, not settled ones. This is the -"dedicated design pass" SECURITY_DESIGN.txt section 10 says the -installer needs, started from the build side rather than the install -side. - -Companion documents: SECURITY_DESIGN.txt (refusal matrix, syspkg -privilege model, section 10's installer reference material), -PACKAGE_SCOPES.txt (symlink routing, why /usr is shared territory). - - -+--------------------------------------------+ -| 0. Why now | -+--------------------------------------------+ - -The first real `syspkg -l musl` (Alpine container, 2026-10-04) worked -exactly as designed, and showed why testing on a foreign distro has -run out of road: Alpine's own musl-dev already owns 231 of the paths -musl links into /usr, so every one was refused, and the -O/--overwrite -flag had to be added just to make musl's files the live ones. - -In a system glacier builds itself, /usr starts empty. No conflicts, no -need for -O, and every file in /usr is a glacier symlink by -construction. That is the actual target. Every test so far has run -against a host distro's /usr instead. - - -+--------------------------------------------+ -| 1. What "system image" means here | -+--------------------------------------------+ - -SECURITY_DESIGN.txt section 10 records that the old "system image -tarball" idea was DISCARDED in favor of package-list-driven -bootstrapping (glacier-bootstrap TEMPLATE_INDEX TARGET). This proposal -does not bring it back. The distinction: - - REJECTED an image as the INPUT to an install: a prebuilt rootfs - tarball unpacked onto the target. Files arrive without - passing through syspkg, so nothing in it is under the - integrity guarantee. - - PROPOSED an image as the OUTPUT of a bootstrap: a target root - built entirely by `syspkg` installing a defined package - list, every package through the normal verified path. - Packing that directory (tarball, OCI, disk image) is just - shipping a result, not a second way of producing one. - -So "build a system image" = "run the bootstrap against a directory, -then optionally pack it". The bootstrap is the thing being designed; -the packing formats are thin (section 6). - -DECISION NEEDED (9a): confirm this reading of section 10. - - -+--------------------------------------------+ -| 2. Pipeline | -+--------------------------------------------+ - - image definition (section 5: profile + package list) - | - gworld -P PROFILE build every recipe the image needs - | -> pkgs/*.gpkg + *.gpkg.sha256 - syspkg --root T -n create T/glacier/sys/... - | - syspkg --root T -l PKG... install the package list into T - | (base -> T/usr, others -> - | T/glacier/sys/links) - finalize T /etc skeleton, doas.conf, etc. - | - pack T dir | rootfs tarball | OCI | disk - -Everything above already exists except `--root` (section 3/4), the -image definition (section 5), finalize, and pack. - -The bootstrapping-the-bootstrapper problem (PACKAGE_SCOPES.txt section -6) mostly dissolves: syspkg, libglacier-ng, luajit and the rest of the -glacier tooling are just base-repo packages in the list. The build -host's syspkg installs them into T through the same verified path as -everything else. The trust edge moves from "whatever lays syspkg down" -to "the build host's syspkg". That's an honest edge, but a much smaller -and more auditable one than an unverified bootstrap step. - - -+--------------------------------------------+ -| 3. Library prerequisite: install root | -+--------------------------------------------+ - -Every path in the library is a hardcoded absolute path today: -pkg.c's gl_root/gl_sys*/gl_usr*, transaction.c's GL_*_BASE and -GL_*_INDEX/STORE/LINKS macros, derive_base_paths, the stage and old -paths in init/commit, the fsync_dir list, GL_BASE_LINKS_DEST ("/usr"). -ctx->root_path exists but is always "/glacier" and nothing reads it as -a prefix. - -Building into T needs TWO distinct roots, and conflating them is the -dangerous mistake: - - install root where bytes are written: T (e.g. /mnt/everest) - runtime root what the paths mean once the / - image is booted / chrooted - -Symlink TARGETS must use runtime paths (/glacier/sys/store/...), or the -image breaks the moment it's booted. Every FILESYSTEM OPERATION must -use install-root paths (T/glacier/sys/store/..., T/usr/...). - -The specific trap: prune_stale_links decides a glacier symlink is stale -by stat()ing through it. For an absolute target, that resolves against -the HOST's filesystem, not T. That would prune live links because the -host doesn't have the package, or worse, keep stale ones because it -does. is_glacier_symlink is fine: it only compares the readlink() -string against the runtime store prefix. But every "does the target -exist" check has to become "does T + target exist". The same goes for -restore_displaced and for anything else that follows a link. - -Shape (ACCEPTED 2026-10-05): - - - The library refuses a sysroot other than "/" for GL_SCOPE_USR - contexts. Only system scope may target another root, for every - caller, not just the CLIs (section 4). - - gl_context_t gains `char sysroot[PATH_MAX]` ("" == "/"; appended - at the end, matched in lib/glacier_cdef.lua and - tests/glacier_ffi.lua). - - New gl_init_live_context_at / gl_init_stage_context_at / - gl_init_sys_at taking a sysroot. The existing functions become - wrappers passing "/", so every current caller is unchanged. - - One helper, gl_at(ctx, runtime_path, out), used for EVERY - filesystem operation. Runtime paths stay what's stored and compared. - AS BUILT (2026-10-05): the reverse, same effect. The context stores - INSTALL paths, used for every filesystem operation unchanged, and - gl_runtime_path() translates only where runtime meaning matters - (link targets, is_glacier_symlink, .displaced keys); gl_at() checks - a link's target during prune. A missed translation then lands in T, - never on the host. - - GL_BASE_LINKS_DEST resolves to sysroot + "/usr". Never the host's - /usr when a sysroot is set. - -The non-negotiable test: an image build must leave the host's /usr and -/glacier byte-for-byte untouched. That is a test assertion, not a code -review item. Same class of bug as the old gl_relink_store wipe: a path -assumption quietly stops holding. - - -+--------------------------------------------+ -| 4. syspkg --root | -+--------------------------------------------+ - -syspkg gains `-r/--root DIR`, which selects the *_at init variants. -gpkg/gstore do NOT get it. Per-user scope has no business in an image -build, and section 5 of SECURITY_DESIGN.txt keeps those tools from ever -reaching system scope. - -Privilege: still root via doas, still no setuid. New trust check, same -reasoning as syspkg's existing self-check: DIR and every ancestor must -be root-owned and not group/world-writable. A root process writing into -a user-controlled tree is a symlink-swap away from writing somewhere -else entirely (replace T/usr with a symlink to the host's /usr between -two syscalls). Same refusal style, same message format. - -The hash refusal matrix applies unchanged. Everything in an image is -either base (always refuse unverified) or system scope (always refuse -unverified), so an image build can only ever contain packages with -valid sidecars. That's the property we want; it means section 2's -gworld step must produce sidecars for everything (gbuild already does). - - -+--------------------------------------------+ -| 5. Image definition = template index | -+--------------------------------------------+ - -SECURITY_DESIGN.txt section 10 noted that the old guide's "template -index" questions (32-bit libs? which libc? SELinux? init system?) are -the same axes SYS_PROFILE already encodes. Proposal: a template index -IS a profile plus an explicit package list, in the same KEY=value -format the recipe parser already reads: - - # images/minimal.image - NAME=minimal - SYS_PROFILE=x86_64-musl - PKGS=musl busybox luajit libarchive zlib libconfig libglacier-ng glacier-ng doas - RECIPES=recipes/ - -No runtime dependency resolution yet. Manifests DO carry PKG_DEPS and -PKG_CONFS, and libglacier parses them, but nothing consumes them and -every package leaves them empty. (DEPS in recipes is build ordering.) -So the list is explicit and complete. GLACIER_BOOTSTRAP.txt section 4 -proposes checking it against PKG_DEPS rather than auto-resolving. - -Remember gworld bug 10: a field that silently never parses and falls -back to a plausible default. Unknown keys and an empty PKGS must be -hard errors. - - -+--------------------------------------------+ -| 6. Output formats | -+--------------------------------------------+ - -In order of usefulness right now: - - a. Directory. What the pipeline produces anyway. chroot-able - immediately, which is the first milestone (section 8). - - b. Rootfs tarball -> `docker import`. Replaces the Alpine-based test - Dockerfiles with a real Everest userland. Ends the glibc-vs-musl - .so mismatch and the missing-linux-headers class of problem, - because the test environment is Everest. Every syspkg/gpkg test - then runs against a /usr glacier built. - - c. Bootable disk image (kernel, bootloader, partition layout per the - old guide's /boot + optional separate /glacier partition). Later, - and blocked on there being kernel/bootloader recipes at all. - -Reproducibility, so two builds of the same definition can be compared: -index files are named by wall-clock time (make_index_name), and tar -records mtimes and ownership. Honour SOURCE_DATE_EPOCH in -make_index_name, and pack with sorted entries, clamped mtimes and -numeric root:root ownership. - - -+--------------------------------------------+ -| 7. Building without a host /usr | -+--------------------------------------------+ - -Consequences of /usr starting empty that the design has to own: - - - Strict linking. In an image build, any "Refusing to overwrite - non-glacier path" means two packages in the list conflict, or - finalize wrote somewhere it shouldn't. It should FAIL the build, not - warn (an image-build flag on the library, or syspkg treating the - warning count as an error under --root). -O must never be used in - an image build; with an empty /usr it has nothing legitimate to do. - - Paths the system needs that no package ships: /etc (passwd, group, - doas.conf), /dev /proc /sys mountpoints, /tmp, /var. Either a `base` - package (e.g. `filesystem`, Arch's approach) or the finalize step. - Recommendation: a package, so it's verified and owned like - everything else. Finalize then shrinks to things that genuinely - vary per image (hostname, users). - - /bin, /lib, /sbin. PACKAGE_SCOPES routes base to /usr only. Either - the filesystem package ships /bin -> usr/bin style merged-usr - symlinks, or every #! /bin/sh breaks. Recommendation: merged /usr, - shipped by the filesystem package. - - -+--------------------------------------------+ -| 8. Milestones | -+--------------------------------------------+ - - 1. [DONE 2026-10-05] sysroot in the library (section 3), plus the - host-untouched test (glacier-ng/tests/sysroot_alpine.sh). Implemented - with INSTALL paths in the context and runtime translation where a - path's meaning matters; see CLAUDE.md "Install root / sysroot". - No CLI changes, testable through FFI alone. - 2. [DONE 2026-10-05] syspkg --root (section 4), with the root-owned-target - check, as -R/--root (implies --strict). glacier-ng/tests/root_alpine.sh. - 3. A `filesystem` base package (section 7). - 4. images/minimal.image + a driver script (gworld -> syspkg --root - -> finalize). Milestone: `chroot T /bin/sh` works, and - `chroot T syspkg -l` installs a package from inside. - 5. Tarball + `docker import`; switch the test suite to run on it. - 6. Disk images: blocked on kernel/bootloader recipes and on the - installer side of section 10 (partitioning, the separate /glacier - partition question). - -Hash verification at install time (SECURITY_DESIGN.txt section 4) -should land before or alongside milestone 2. An image build is -"base-repo packages, the strictest tier" by definition, so it's the -first real consumer of the refusal matrix. - - -+--------------------------------------------+ -| 9. Open decisions | -+--------------------------------------------+ - - a. Section 1's reading of SECURITY_DESIGN section 10: images as - bootstrap OUTPUT are fine, images as install INPUT stay rejected. - b. Template index format: the KEY=value file in section 5, or - something else. - c. `filesystem` package vs finalize script for /etc and friends, and - merged /usr (section 7). - d. Build privilege: building as real root inside a throwaway - container (works today), or rootless via user namespaces (unshare - -r) later. Rootless changes nothing in section 4's checks, since - inside the namespace the tree IS root-owned, but it does need the - packing step to write numeric root ownership regardless of who - built it. - e. Whether the image's own index/store should be built with the - image's final paths only, or also carry provenance: which - SYS_PROFILE and which image definition produced it. CLAUDE.md - already lists "manifests don't record SYS_PROFILE" as open. An - image is where that gap starts to hurt. diff --git a/Makefile b/Makefile index 1bb07b6..52bfee7 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,8 @@ include config.mk -.PHONY: all prepare log log_test pkg transaction istoreutils install clean static libglacier.a install_static libglacier-ng sha256 gsha256sum libglacier_verify gsign grepo +.PHONY: all prepare log log_test pkg transaction istoreutils install clean static libglacier.a install_static libglacier-ng sha256 gsha256sum libglacier_verify gsign grepo gsandbox -all: prepare log log_test pkg transaction istoreutils sha256 libglacier_verify gsha256sum gsign grepo +all: prepare log log_test pkg transaction istoreutils sha256 libglacier_verify gsha256sum gsign grepo gsandbox @echo "libglacier-ng has finished building" static: prepare log_static pkg_static istoreutils_static libglacier.a @@ -16,13 +16,15 @@ pkg_static: istoreutils_static: pkg_static $(CC) $(CFLAGS) -c src/istoreutils.c -o build/lib/tmp/istoreutils.o $(CC) $(CFLAGS) -c src/deps.c -o build/lib/tmp/deps.o + $(CC) $(CFLAGS) -c src/recipe.c -o build/lib/tmp/recipe.o libglacier.a: ar rcs build/lib/libglacier.a \ build/lib/tmp/log.o \ build/lib/tmp/pkg.o \ build/lib/tmp/istoreutils.o \ - build/lib/tmp/deps.o + build/lib/tmp/deps.o \ + build/lib/tmp/recipe.o prepare: mkdir -p build @@ -61,9 +63,16 @@ gsign: prepare # from source like gsign, so it needs no rpath to the shared objects. grepo: prepare $(CC) $(CFLAGS) src/grepo.c src/sign.c src/sha256.c src/log.c src/pkg.c \ - src/istoreutils.c src/deps.c src/transaction.c $(MONOCYPHER) \ + src/istoreutils.c src/deps.c src/recipe.c src/transaction.c $(MONOCYPHER) \ -larchive -lconfig -o build/bin/grepo +# gsandbox runs builds (BUILD_DESIGN.txt section 6). Not a maintainer +# tool: gpkg/syspkg run it, so it is installed beside the libraries. +gsandbox: prepare + $(CC) $(CFLAGS) src/gsandbox.c src/log.c src/pkg.c src/istoreutils.c \ + src/deps.c src/recipe.c src/transaction.c \ + -larchive -lconfig -o build/bin/gsandbox + transaction: log istoreutils $(CC) $(CFLAGS) -shared -fPIC src/transaction.c \ -Lbuild/lib/shared -lglacier_istoreutils -lglacier_log \ @@ -71,7 +80,7 @@ transaction: log istoreutils -o build/lib/shared/libglacier_transaction.so istoreutils: pkg - $(CC) $(CFLAGS) -shared -fPIC src/istoreutils.c src/deps.c \ + $(CC) $(CFLAGS) -shared -fPIC src/istoreutils.c src/deps.c src/recipe.c \ -Lbuild/lib/shared -lglacier_log -lglacier_pkg -larchive \ -Wl,-rpath,'$$ORIGIN' \ -o build/lib/shared/libglacier_istoreutils.so @@ -85,7 +94,7 @@ pkg: libglacier-ng: prepare $(CC) $(CFLAGS) -shared -fPIC \ src/log.c src/pkg.c src/transaction.c src/istoreutils.c src/deps.c \ - -larchive -lconfig \ + src/recipe.c -larchive -lconfig \ -o build/lib/shared/libglacier-ng.so install: @@ -98,6 +107,7 @@ install: install build/bin/gsha256sum $(PREFIX)/bin/ -m 755 install build/bin/gsign $(PREFIX)/bin/ -m 755 install build/bin/grepo $(PREFIX)/bin/ -m 755 + install build/bin/gsandbox $(PREFIX)/lib/glacier/ -m 755 install_static: mkdir -p $(PREFIX)/lib/glacier diff --git a/PACKAGE_SCOPES.txt b/PACKAGE_SCOPES.txt deleted file mode 100644 index 03daac9..0000000 --- a/PACKAGE_SCOPES.txt +++ /dev/null @@ -1,199 +0,0 @@ -+------------------------------------+ -| Package scopes and symlink routing | -+------------------------------------+ - -This document records the design decisions behind how glacier packages -are scoped, how their repo determines where their symlinks land, and -what "boot-critical" means in this system. It exists because these -rules aren't obvious from reading the code alone, and getting them -wrong (particularly the symlink-placement rule) has real consequences -up to and including destroying a live /usr. - - -+------------------------------------+ -| 1. The two scopes | -+------------------------------------+ - -USR (GL_SCOPE_USR) - Per-uid packages. Everything a uid's transactions touch lives - under ONE directory that uid owns: - /glacier/usr//{index,store,links,stage,old,lock} - /glacier/usr itself is root-owned (0755) and each /glacier/usr/ - is owned by that uid (0700), so every create/rename/lock a - transaction does happens inside the user's own directory — no shared - writable parent, so no uid can create or squat another's. Root - creates each one: `gstore -n UID` directly, or a user for themselves - via a doas rule pinned to `gstore -n` (see gstore's header). The - library refuses a base that isn't a real directory owned by its uid - with no group/other bits, or whose /glacier/usr is loosened. - Symlinks always land under /glacier/usr//links/{bin,...}. - There is no base-repo exception for USR scope. Nothing installed - under a per-user scope is ever considered part of the base system, - so nothing here ever touches /usr. - -SYS (GL_SCOPE_SYS) - System-wide packages, not owned by any particular uid: - /glacier/sys/{index,store,links,stage,old,lock} - Symlink destination depends on the package's repo (see section 3). - Root-owned and world-READABLE, like /usr: index/store/links, the - store's repo/name/version dirs and implicit parent dirs are 0755, - index files 0644 (gl_scope_dir_mode / gl_scope_file_mode). /usr's - links point into the store, so every user must be able to traverse - it, and user-scope dependency checks read the system index. The - modes are applied explicitly, not left to syspkg's umask. The lock - stays 0600; .displaced, .etc-state and backup/ stay 0700. - Requires root. gpkg enforces this via geteuid() before it will - even attempt a system-scope operation. - - -+------------------------------------+ -| 2. Repo semantics | -+------------------------------------+ - -A package's repo (PKG_REPO in its manifest) is not just a label for -organizing the store — under system scope, it is the one thing that -decides where that package's activation symlinks physically land. - - base - Packages that make up a minimal working system. ALL packages - in this repo are considered boot-critical BY DEFINITION — this - is a repo-level classification, not a per-package flag. A - package doesn't have to be individually essential for booting - to count; if it's filed under base, it's treated as part of - the base system, full stop. - - extra - Software that may be important but is not necessary to run - Everest, nor to install it. - - community - Everything else. - - NOTE: extra and community are currently NOT distinguished by the - library itself — both simply mean "not base," and both route to - the same default system-scope links location. If they need to - diverge further later (different confirmation prompts, different - trust handling, whatever), that is a deliberate future change, not - something already implemented. - - -+------------------------------------+ -| 3. Symlink placement rule | -+------------------------------------+ - - scope == USR -> /glacier/usr//links - scope == SYS && repo == "base" -> /usr (*) - scope == SYS && repo != "base" -> /glacier/sys/links - scope == SYS, package path etc/... -> COPIED into /etc (any repo; - config, not linked — see below) - -(*) This is the base-system exception. Packages that are part of the - minimal working system get their symlinks placed directly into - /usr/bin, /usr/lib, etc. — real FHS locations — so that anything - with a hardcoded path (init scripts, systemd units, shebang lines) - works without needing glacier-aware PATH setup. - - Everything an operator installs under system scope that ISN'T - part of the base system stays isolated under /glacier/sys/links, - same as it always has. The base system is the exception to the - norm, not the other way around. - -Config files are the exception to linking. Editing a symlink into the -store would edit the store itself, so a system-scope package's etc/ is -copied into /etc instead. glacier keeps a record of the last version -each package offered (/.etc-state/). A file the admin changed, -deleted, or that glacier never installed is never overwritten; package -changes to it arrive once as FILE.new. Unchanged files are updated in -place and removed with their package (pacman-style). - -This decision is made per-package, at the point where a package's repo -is actually known (inside gl_link_pkg / gl_unlink_pkg / the walk loop -in gl_relink_store) — NOT baked into the context at creation time. -gl_context_t's links_path field always holds the DEFAULT destination -for that scope; the /usr override is computed separately per package. - - -+------------------------------------+ -| 4. Why /usr as a target is safe | -+------------------------------------+ - -/usr is not glacier-exclusive territory the way /glacier/sys/links is. -It holds plenty of content glacier has no business touching. Every -place that reads or writes into a links destination therefore treats -that destination as "possibly shared, not owned": - - - is_glacier_symlink(path, store_prefix) is the single source of - truth for "did glacier itself create this." It reports true only - if `path` is a symlink whose target lives under the relevant - store path. Anything else — a real file, a directory, a foreign - symlink pointing somewhere else entirely — is never touched. - - - gl_link_pkg refuses to overwrite an existing path unless - is_glacier_symlink says it's safe to replace. It will not clobber - a foreign file that happens to occupy the same path. - - - gl_relink_store no longer wipes and rebuilds its links directory - wholesale (that was safe only when the target was glacier-only - territory). It prunes ONLY stale symlinks glacier itself created - (identified via is_glacier_symlink, removed only if their store - target no longer exists) and leaves everything else alone. - - - A single system-scope relink pass prunes BOTH possible - destinations (/glacier/sys/links and /usr), since it can't know in - advance whether any base-repo packages are involved without - checking both. - - - The stage tree's links directory is no longer hardlink-seeded at - all. It was always unused (gl_link_pkg only ever runs against a - LIVE context; gl_relink_store always builds its own fresh live - context rather than touching a staged one) — and now that live - links_path can be /usr, seeding it would mean hardlinking the - entire /usr tree on every staged system transaction, and risking - EXDEV outright if /usr and the stage area are on different - filesystems. - - -+------------------------------------+ -| 5. Updating base-system packages | -+------------------------------------+ - -Base-repo packages are tracked in the system index like anything else, -and updating them works exactly the same way updating any other -package does — same staged transaction, same commit/rollback. No -separate mechanism was built for this, because none was needed: - - gpkg -s newmusl.gpkg - -...updates musl in place under system scope, symlinks and all, -whether it was originally installed by a bootstrap tool or by a normal -`gpkg -s` call later. There is no meaningful distinction between -"how it originally got there" and "how you update it." - -Replacing something as fundamental as libc on a LIVE running system is -safe under this model specifically because of POSIX unlink semantics: -a process that already has a shared object open keeps working off the -old inode even after the symlink swap happens. Only newly-spawned -processes after the swap see the new version. This falls directly out -of the atomic-rename commit design already in place — nothing extra -was added to make it work. - - -+------------------------------------+ -| 6. Open items | -+------------------------------------+ - - - grootstrap has not been rebuilt against this design yet. The - simplification this design enables: once gpkg/gstore themselves - exist on the target (still a bootstrapping problem that needs - solving separately), EVERY package — base included — can go - through the same `gpkg -s -l` path. There is no longer a need for - a separate raw-extraction special-case for base packages - specifically; the repo alone routes them to /usr correctly. - - - extra vs community currently behave identically (see section 2). - Whether they should diverge, and how, is undecided. - - - The bootstrapping-a-bootstrapper problem (getting gpkg/gstore onto - a target filesystem before there's a working package manager to - install them with) is still unsolved and orthogonal to everything - in this document. diff --git a/REPO_DESIGN.txt b/REPO_DESIGN.txt deleted file mode 100644 index eea4b82..0000000 --- a/REPO_DESIGN.txt +++ /dev/null @@ -1,446 +0,0 @@ -+--------------------------------------------+ -| Remote repositories and signing | -+--------------------------------------------+ - -STATUS: DESIGN, 2026-10-06. ROADMAP 3.1. Steps 1 (Ed25519, signify -formats, gsign), 2 (keyring, the local base rule, gbuild -k, -bootstrap carrying .sig, Everest's key) and 3 (grepo, the index, -refresh with -y) of section 9 DONE 2026-10-06, step 4 (-f, -u, -dependency closure, the cache) DONE 2026-10-07; sections 7, 5 and 6 -say how they came out. Step 5 next. See CLAUDE.md. -Sections 1 and 10 are decided; the only open item is 10a's TLS library. - -Adds AUTHENTICITY to glacier: SECURITY_DESIGN.txt section 1 deferred it -to "a future phase, tied to remote-repo support". This is that phase. -It also unblocks gpkg/syspkg -f (ROADMAP 2.2), -u (2.1), automatic -dependency closure (2.3) and glacier-bootstrap -r (GLACIER_BOOTSTRAP -section 5), and closes Finding 1 of SECURITY_REVIEW_2026-07-16.md (a -manifest that says PKG_REPO = "base" gets linked into /usr). - -Companion documents: SECURITY_DESIGN.txt (integrity, refusal matrix), -PACKAGE_SCOPES.txt (repo routing), GLACIER_BOOTSTRAP.txt (pins). - - -+--------------------------------------------+ -| 1. Decisions (the user, 2026-10-06) | -+--------------------------------------------+ - - a. Signatures: Ed25519, vendored (Monocypher's Ed25519 variant, which - brings its own SHA-512), compiled into the private - libglacier_verify.so next to sha256. Key and signature files are - signify-compatible, so OpenBSD's signify can make and check them - too. No new base dependency. - b. What is signed: one INDEX per repository (repo.idx + repo.idx.sig), - listing every package it serves with its sha256. Packages are - verified through the hash in the signed index, i.e. through the - existing sha256 path. The index has a serial; a client refuses an - index older than the last one it accepted (rollback). - c. Local base packages: once signing exists, `syspkg -l FILE` of a - package whose manifest says base requires a signature by a key - trusted for base. extra/community local installs stay - sidecar-only (integrity). Manual installation keeps working: a - builder makes a key and root adds it to the keyring. - d. Users may add their own repositories and keys, for their own scope - only (gpkg). Never read by syspkg. - - -+--------------------------------------------+ -| 2. Keys and signatures (proposal) | -+--------------------------------------------+ - -signify's formats, byte for byte (two lines: "untrusted comment: ..." -then base64): - - public key "Ed" | keynum[8] | pubkey[32] - signature "Ed" | keynum[8] | sig[64] - secret key "Ed" | "BK" | rounds[4] | salt[16] | checksum[8] | - keynum[8] | seckey[64] - - - keynum is a random 8-byte key id; a signature names the key that - made it, so verification picks the key by keynum and never tries - every key in the keyring. - - Signing is pure Ed25519 over the WHOLE message, as signify does. So - we never sign a .gpkg directly (it would have to be read into memory - whole). What gets signed is small: - - a repository's repo.idx; - - a local package's SIDECAR (NAME-VER.gpkg.sha256, the one line - "sha256:"), as NAME-VER.gpkg.sha256.sig. Checking the - sidecar against the file is the existing path; the signature - makes the sidecar authentic. `signify -V -p KEY -m X.sha256` - checks the same file. - - Secret keys: glacier's tools read and write only UNENCRYPTED secret - keys (rounds = 0, what `signify -G -n` makes): passphrase support - needs bcrypt_pbkdf, which is more vendored crypto for a build-host - convenience. A passphrase-protected key works by signing with - signify itself (10b). - -New tool `gsign` (C, built with gsha256sum; a build/maintainer tool, -later in "glacier-tools", never in base): - - gsign -G -p KEY.pub -s KEY.sec [-c COMMENT] make a keypair - gsign -S -s KEY.sec -m FILE [-x SIGFILE] sign (default FILE.sig) - gsign -V -p KEY.pub -m FILE [-x SIGFILE] verify - -gbuild gains `-k KEY.sec`: sign the sidecar it writes. - - -+--------------------------------------------+ -| 3. Keyring and repository configuration | -+--------------------------------------------+ - -System (root-owned; syspkg applies its trust checks to these files and -every ancestor, like its own lib/): - - /etc/glacier/keys/NAME.pub - /etc/glacier/repos.conf - -repos.conf (libconfig, like glacier.conf): - - repos = ( - { name = "base"; url = "https://pkg.example.org/base"; - keys = [ "everest-2026" ]; }, - { name = "extra"; url = "https://pkg.example.org/extra"; - keys = [ "everest-2026" ]; } - ); - - - A key is trusted ONLY for the repos that list it. That binding is - what makes "base" mean something: the base index must be signed by a - key listed for base, and a local base package's sidecar likewise. - Several keys per repo allow rotation (old and new side by side). - - Order = priority, when one name is served by several repos. - - name follows the gl_valid_pkg_ident rules. url is https:// or - file:// (local mirrors, tests); http:// is refused. - - url is optional: an entry without one only says which keys are - trusted for that repo, for a system installed and kept up by hand - from signed local files (section 7). - - Missing file = no remote repositories; -f/-u then refuse in one - line. No defaults, as with KEEP_OLD. - -User (gpkg only): - - ~/.config/glacier/repos.conf ($XDG_CONFIG_HOME) - ~/.config/glacier/keys/NAME.pub - - - Merged AFTER the system list (lower priority). - - A user repo named "base", or named like a system repo, is refused. - - System keys are trusted for system repos only; a user's keys for the - user's repos only. - - -+--------------------------------------------+ -| 4. The index | -+--------------------------------------------+ - -URL/repo.idx and URL/repo.idx.sig. libconfig, parsed only AFTER its -signature checks: - - REPO = "base"; - SERIAL = 2026100601L; # strictly increases with each publish - VALID_UNTIL = 1761955200L; # unix time; required (10c) - PKGS = ( - { NAME = "musl"; VER = "1.2.5"; FILE = "musl-1.2.5.gpkg"; - SHA256 = "sha256:3a5f..."; SIZE = 812345L; - DEPS = (); CONFS = (); }, - ... - ); - - - REPO must equal the configured name the index was fetched for. - - Every version a repo serves is listed (so a pinned or older version - can still be fetched by -f NAME=VER later). - - DEPS/CONFS repeat the manifest's, so dependency closure can be - planned before downloading anything. After download, the manifest - must match the entry (NAME, VER, PKG_REPO = REPO, DEPS, CONFS): - a mismatch refuses the package. That is the Finding 1 rule for - remote packages: a package is "base" because the base index lists - it AND it says so, never because it says so. - - FILE is a bare file name (gl_valid_pkg_ident rules plus ".gpkg"): - no paths, no URLs. - -New tool `grepo` (maintainer side, glacier-tools): `grepo -s KEY.sec --r REPO DIR` reads every NAME-VER.gpkg in DIR (manifests, hashes), -writes DIR/repo.idx with SERIAL = the previous one + 1 (or the date -form), and signs it. The server is then any static file host. - - -+--------------------------------------------+ -| 5. Client state and fetching | -+--------------------------------------------+ - -Inside each scope's base directory (one more entry beside index, store, -...; same ownership and modes as the rest): - - /repos/REPO.idx, REPO.idx.sig the last ACCEPTED index - /cache/REPO/FILE downloaded packages - -Refresh (every -f / -u; indexes are small; 10d): - 1. curl --proto =https --proto-redir =https --fail (or a file:// copy) - URL/repo.idx and .sig into a temporary file in /repos/. - 2. Verify the signature with a key listed for that repo (by keynum). - 3. Parse. REPO must match. SERIAL must be > the stored one, or equal - with identical bytes. VALID_UNTIL must be in the future. - 4. rename() over the stored copy (never written in place: bug 25). -Any failure keeps the old index and refuses the operation in one line: - [x] Index for extra is older than the one already accepted. - -Fetch: download FILE into the cache under a temporary name, hash it -while downloading, rename into place only if the hash matches the -index, then write the sidecar FROM THE INDEX and hand the cached file -to the existing install path (which re-hashes it, as today). The cache -is a download optimization, not a trusted store: a cache hit is hashed -again. - - As implemented (2026-10-06, step 3; the user chose a refresh flag, - the date-form SERIAL and grepo in C): - - grepo is C (src/grepo.c, libglacier-ng; built from source like - gsign, installed to bin; not in base): `grepo -s KEY.sec -r REPO - [-n SERIAL] [-e DAYS] DIR`. SERIAL = max(previous + 1, today (UTC) - * 100 + 1), e.g. 2026100601; -n must still be above the previous - one. VALID_UNTIL = now + DAYS (default 30, 1..3650). Packages are - sorted by file name; each must be a regular file, its manifest must - say REPO and its name must be NAME-VER.gpkg (VER as the store names - versions, "%d.%d.%d"). An existing DIR/repo.idx must be a - well-formed index of REPO (its SERIAL is the previous one). It is - written to a mkstemp file, signed, and both renamed into place, the - .sig first. - - The index format is section 4's, with DEPS and CONFS as lists of - { NAME = "x"; VER = "1.0.0"; } (the manifest's PKG_DEPS shape). - gl_index_parse (pkg.c) takes the BYTES the signature was checked - over, never a path, and is strict: exactly REPO, SERIAL > 0, - VALID_UNTIL > 0, PKGS; each package exactly NAME, VER, FILE, SHA256, - SIZE >= 0, DEPS, CONFS; FILE must be exactly "NAME-VER.gpkg"; SHA256 - "sha256:" + 64 lowercase hex; no NAME + VER twice. A NUL or an '@' - anywhere is refused before libconfig sees it ('@include'). - GL_INDEX_ERR_REPO when REPO is not the repo it was fetched for. - - `syspkg -y` / `gpkg -y` (--refresh) refresh every repos.conf entry - with a url and stop (decision 10d still holds for -f/-u). gpkg - reads the SYSTEM repos.conf and keyring until step 6 (user repos), - and stores into the user's base. No repos.conf, or no entry with a - url: `[x] No remote repositories are configured.` (exit 1). - - /repos is made by gl_scope_state_dir (transaction.c): the - base must be the scope's; repos is created with the scope's mode - (0755 root / 0700 uid) and refused unless it is a real directory - with exactly that owner and mode. Files are 0644 / 0600. -y holds - the scope's lock (gl_begin_transaction on a live context); under - -R the indexes go under the install root, checked with the install - root's OWN keyring (DIR/etc/glacier; changed 2026-10-07, see - "Keyrings under -R" below). - - file:// is read directly (absolute paths only); https:// goes - through `curl -sf --proto =https --proto-redir =https`. 64 MiB at - most (GL_SIGN_MAX_MSG). Every repo is tried; exit 1 if any failed. - - One line per repo: - [✓] Index for base: serial 2026100601, 11 packages. - [i] Index for base is up to date: serial 2026100601. - [x] Cannot fetch the index for base. (a missing .sig too) - [x] Index for base is not signed by a key trusted for base. - [x] Malformed index for base. - [x] Index fetched for base is the index of another repository. - [x] Index for base is older than the one already accepted. - [x] Index for base has the serial of the one already accepted, but other contents. - [x] Index for base has expired. - [x] Malformed /glacier/sys/repos/base.idx. (left for the admin) - - The accepted copy is trusted by where it lives (root's or the - user's private repos dir): it is parsed for its SERIAL, not - re-verified. - - Test: glacier-ng/tests/repo_alpine.sh (103 checks; 18 mutants, 12 C - and 6 Lua, all caught). - - -+--------------------------------------------+ -| 6. -f, -u and dependency closure | -+--------------------------------------------+ - - -f NAME... (ROADMAP 2.2): like -l, with the file found by name in the - accepted indexes (highest version, first repo by priority). Missing - dependencies are added automatically (ROADMAP 2.3's closure): the - highest version satisfying the minimum, recorded `auto`. The - summary lists them, marked as dependencies. Conflicts and every - 2.3 check run as today, before the prompt. - -u (ROADMAP 2.1): every installed package whose repo is configured and - whose index has a higher version is replaced, as -lO does (backups, - KEEP_OLD). Packages from repos not configured are left alone. - `-u NAME...` limits it to those names. - syspkg -f/-u fetch only from system repos; gpkg -f/-u from system and - the user's repos. Base is still refused in user scope (library rule). - - As implemented (2026-10-07, step 4; M.fetch / M.upgrade in - glacier-ng/lib/gpkg_common.lua). The user decided three details: - - Which repo: the FIRST repo by repos.conf order that serves NAME, at - its highest version. A lower-priority repo never wins by publishing - a bigger version. -u stays within the installed package's repo. - - A dependency installed at too old a version is UPGRADED in the same - transaction from its own repo (backed up per KEEP_OLD, like -lO), - keeping its auto/explicit mark; the summary shows - "old -> new (dependency)". - - Cache: downloads stay in /cache/REPO while a run is declined - or refused; the files a commit installed are deleted after it. - The rest: - - Every -f/-u runs -y's refresh first; if any repo fails, the - operation is refused (decision 10d). The accepted indexes are then - read from /repos (gl_index_parse again; trusted by location). - - Closure: for each planned package, each DEPS entry of its INDEX - entry is met by a planned package, an installed one at >= VER - (this scope; for a user, the system's index too), else upgraded (an - installed one too old) or added (pick(): first repo serving it, - recorded auto). What can't be met is left to gl_check_plan, which - prints the 2.3 refusal. The summary marks additions - "(dependency)". - - Download: gl_scope_cache_dir (transaction.c) makes and checks - /cache and /cache/REPO as gl_scope_state_dir checks - repos (owner, exact mode, not a symlink). A cached file whose hash - matches the index is reused; otherwise file:// is read, https:// - goes through `curl -sf --proto =https --proto-redir =https` on a - pipe; at most SIZE + 1 bytes are ever read, hashed on the way, into - a dot-named temporary, renamed into place only if size and hash - match. 0644 / 0600. - - No sidecar is written: the index's sha256 is handed to - verify_and_copy directly (its `vouched` argument), which re-hashes - while copying into the private dir, as for -l. A base package needs - no .sig of its own: the base index vouches for it. - - The copy's manifest (library-read) must say exactly what the index - entry says: NAME, VER, PKG_REPO = the repo, DEPS and CONFS (same - order, "NAME MAJ.MIN.PAT"). Else, and for a bad hash or size: - [x] extra::evil 1.0.0 does not match its index. - and the cached file is deleted. Nothing to download: - [x] Cannot fetch extra::foo 1.0.0. - No repo serves a name: - [x] foo is not in any repository. - - -f of a name installed at another version needs -O (as -l); - dependency upgrades and -u don't (meta.may_replace). -O still also - means displacing foreign files. - - -u [NAME...]: a named package not installed, or whose repo has no - url, is refused (`[x] foo is not installed.` / `[x] community::foo - is not in any configured repository.`); plain -u skips the latter. - Nothing newer: `[✓] Nothing to do.`, exit 0. - - gpkg: user scope never fetches from base (base indexes are not even - considered, so `[x] core is not in any repository.`); the system's - repos.conf until step 6; indexes and cache in the user's base. - - syspkg -R DIR -f/-u: indexes and cache under DIR, DIR's keyring. - - Keyrings under -R (decided 2026-10-07, for glacier-bootstrap - configuring the system's repositories): -y, -f and -u read - DIR/etc/glacier/repos.conf and DIR/etc/glacier/keys, with the same - trust checks, plus: each file's real path must lie inside DIR - (`[x] Refusing P: it resolves outside DIR.`), so a symlink in DIR - can't make the host's file stand in for DIR's. The indexes are DIR's - state and DIR checks them with its own keys from then on, and a host - with no glacier configuration can still bootstrap. A local `-R -l` - base package's .sig is still checked with the HOST's keyring (section - 7). Tests: repo_alpine.sh / fetch_alpine.sh give the image its own - keyring; bootstrap_alpine.sh sections 14-16. - - Test: glacier-ng/tests/fetch_alpine.sh (84 checks; 16 Lua mutants - and 1 C mutant, all caught except the download-level hash check, - which is EQUIVALENT: the private copy's re-hash refuses the same - package and the mismatch path deletes the cached file. Kept as - defence in depth: a bad download never sits in the cache under its - final name). - - Known gap: a run killed mid-download leaves its dot-named temporary - in the cache (never read; the next fetch writes its own). - - -+--------------------------------------------+ -| 7. Local installs (decision 1c) | -+--------------------------------------------+ - - syspkg -l FILE, manifest says base: - FILE.sha256 must match (as today) AND FILE.sha256.sig must verify - with a key listed for base in repos.conf. Otherwise: - [x] base::musl is not signed by a key trusted for base. - syspkg -l, other repos; gpkg -l: unchanged (sidecar only). - glacier-bootstrap -d: carries each package's .sig into its private - copies, so syspkg -R checks it. The keyring checked is the HOST's - /etc/glacier (the build host's trust, as KEEP_OLD is today). - Consequence for ~/Projects/everest: it needs a key; container.sh signs - every base package (gbuild -k); the build host's /etc/glacier/keys and - repos.conf list it. The image ships the PUBLIC key and a repos.conf so - the installed system trusts its own base (since 2026-10-07 in the - everest-repos package, split out of everest-bootscripts). - - As implemented (2026-10-06, step 2): - - The repo is the one the LIBRARY reads from the verified copy - (gl_read_pkg_manifest, as gl_install_pkg), never gpkg_common's - pattern-matching read_manifest_fields: a manifest comment - `# PKG_REPO = "extra"` would make that one say extra. - - The sidecar is read ONCE; those bytes are both what the copy's hash - is checked against and what the signature is checked over. So - glacier-bootstrap copies the sidecar's bytes as read (it used to - write a new one from the hash) next to the .sig. - - The key is the one, among those listed for base, whose keynum the - signature names. Any other problem with the signature (missing, - malformed, other bytes, other key) is the one-line refusal above, - before the prompt; one refused package refuses the batch. - - repos.conf is read by gl_conf_repo_keys (pkg.c), strictly: `repos` - is the only setting; each entry has name, keys and optionally url, - nothing else; names and key names follow gl_valid_pkg_ident; a - duplicate name, or a url other than https://X or file://X, is - refused. Any of that: `[x] Malformed /etc/glacier/repos.conf.` - - repos.conf and each listed key, every ancestor of them and of their - real paths, must be root-owned and not group/world-writable: - `[x] Refusing F: P is not root-owned, or is group/world-writable.` - A listed key that is missing (`Cannot read F.`) or not a public key - (`Malformed F.`) stops the run: the admin's configuration is at - fault, not the package. Read only if some package is base. - - gbuild -k KEY.sec signs the sidecar (gsign from $GSIGN_BIN, - build/bin, or PATH), trying the key before building; a build - without -k removes a stale .sig. tests/mkpkg -k likewise. - - Test images (Dockerfile.*) carry a TEST key, glacier-test, listed for - base, its secret at /root/glacier-test.sec. tests/keyring_alpine.sh - covers this section (17 mutants, all caught). - - KEEP_OLD backups are re-packed from the store, so a base backup has - no signature: `syspkg -lO` refuses it until the restore interface - exists (decision 10f). - - -+--------------------------------------------+ -| 8. Where the checks live | -+--------------------------------------------+ - -Signature verification is C (libglacier_verify.so). The POLICY (which -key for which repo, the base rule, rollback state) lives in the CLIs' -shared module, like hash verification today, so a third-party caller of -gl_install_pkg still isn't checked. ROADMAP 3.2 (move verification into -the library) now covers signatures too. - - -+--------------------------------------------+ -| 9. Order of work | -+--------------------------------------------+ - - 1. Vendored Ed25519 + signify formats in libglacier_verify.so; gsign; - tests including interop with signify (Alpine's `signify` package) - and hostile inputs (bad base64, wrong keynum, truncated files). - 2. Keyring + repos.conf + the local base rule (section 7); gbuild -k; - glacier-bootstrap carries .sig; Everest gets a key. - 3. Index: grepo; refresh, verify, rollback state. DONE 2026-10-06 - (section 5, "As implemented"; syspkg/gpkg -y). - 4. -f with closure; then -u. DONE 2026-10-07 (section 6, "As - implemented"). - 5. glacier-bootstrap -r against an index (pins stay optional extra - assurance). - 6. User repos. -Each step is tested in Docker (file:// repos need no network) and -mutation-checked, as usual. - - -+--------------------------------------------+ -| 10. Decisions on the details (2026-10-06) | -+--------------------------------------------+ - - a. Fetching on Everest: curl plus one TLS library in base. Signatures - make packages authentic regardless; TLS also hides WHAT is fetched - and stops a network attacker serving a stale (still valid) index. - STILL OPEN: which TLS library (BearSSL or LibreSSL); decide when - packaging it. Until then, everything is built and tested with - file:// repos and Alpine's curl. - b. No encrypted secret keys in gsign (no bcrypt_pbkdf). A - passphrase-protected key signs with signify itself. - c. VALID_UNTIL is REQUIRED; an expired index is refused. The - maintainer sets the lifetime; grepo defaults to 30 days. - d. Indexes are refreshed on every -f / -u. Offline, they refuse. - e. Everest's SECRET key lives outside the project tree: - ~/.config/everest/keys/everest-2026.sec (EVEREST_KEYS), made by - `everest.sh keygen`, mounted read-only into the build container. - The public key ships in everest-bootscripts (/etc/glacier/keys). - f. Base backups (KEEP_OLD) are refused by `syspkg -lO` for want of a - signature; accepted for now. The restore interface (KEEP_OLD's - "later") can trust backups glacier made in its root-owned backup - dir. diff --git a/ROADMAP.txt b/ROADMAP.txt deleted file mode 100644 index b05a16a..0000000 --- a/ROADMAP.txt +++ /dev/null @@ -1,351 +0,0 @@ -+--------------------------------------------+ -| Glacier roadmap | -+--------------------------------------------+ - -What's left to build, in priority order. Status as of 2026-10-07. -Design detail lives in the companion docs; this file says WHAT and in -what order, and links to WHERE: - - SECURITY_DESIGN.txt integrity, scope separation, refusal matrix - PACKAGE_SCOPES.txt layout, link routing, /etc config handling - IMAGE_DESIGN.txt system images as bootstrap output, sysroot - REPO_DESIGN.txt remote repositories, signing, keyring - GLACIER_BOOTSTRAP.txt glacier-bootstrap plan, prerequisites, decisions - -Mark an item [DONE yyyy-mm-dd] rather than deleting it, so the history -stays readable. CLAUDE.md "Known open items" tracks small bugs; this -file tracks work. - - -+--------------------------------------------+ -| 1. Install Everest with glacier alone | -+--------------------------------------------+ - -The critical path: from "QEMU boots an initramfs assembled by a script" -(~/Projects/everest) to "glacier installs a system". - - 1.1 [DONE 2026-10-05: see CLAUDE.md "Install root / sysroot" and - tests/sysroot_alpine.sh.] - sysroot in the library (IMAGE_DESIGN section 3). Every path is - hardcoded to /glacier and /usr. Needs separate install-root - (where bytes are written) and runtime-root (what symlink targets - say). The trap: prune_stale_links follows absolute links, so a - naive prefix would judge the image's links against the HOST's - filesystem. Required test: an image build leaves the host's /usr - and /glacier byte-identical. - - 1.2 [DONE 2026-10-05: -R/--root, strict by default under -R, --strict.] - syspkg --root DIR (refuses unless DIR and its ancestors are - root-owned and not group/world-writable) and --strict (any link - refusal fails the transaction; an image's /usr starts empty). - gl_create_fs_tree already takes a root prefix. - - 1.3 [DONE 2026-10-06: glacier-ng/glacier-bootstrap, GLACIER_BOOTSTRAP - section 10; Everest's initramfs is built with it and boots.] - glacier-bootstrap, local mode (GLACIER_BOOTSTRAP.txt sections 1-6). - Template index -> resolve -> verify -> syspkg --root, one - transaction. Never writes into TARGET itself. - [DONE 2026-10-07: repositories. TARGET's repos.conf + keys come - from a package (Everest: everest-repos); bootstrap then runs - syspkg -R TARGET -y, which reads TARGET's own keyring; exit 7 on - a failed fetch. GLACIER_BOOTSTRAP section 10. Later, maybe: an - opt-in copy of the host's repos.conf (pacstrap's mirrorlist).] - - 1.4 [DONE 2026-10-06: built by ~/Projects/everest/scripts/container.sh, - in templates/minimal.template, boot-verified in QEMU; full - regression passes.] - Packages for glacier itself, so an installed system can manage - itself: luajit, libarchive (+ zlib), libconfig, libglacier-ng, - glacier-ng (syspkg, gpkg, gstore), doas. - Decided 2026-10-06: - - base: luajit, zlib, libarchive, libconfig, libglacier-ng, - glacier-ng. extra: doas (replaceable, e.g. by sudo). - - glacier-ng ships syspkg, gpkg and gstore only. glacier-bootstrap, - gbuild, gworld and gsha256sum become a later "glacier-tools" - package in extra (after the release, which brings a real - install Makefile). - - everest-bootscripts ships /etc/doas.conf: `permit :wheel`, plus - `permit nopass :wheel as root cmd /usr/bin/gstore args -n`. - - Layout: scripts + lib/ in usr/lib/glacier-ng/, usr/bin/{syspkg, - gpkg,gstore} symlink into it (realpath lands in the store, lib/ - beside it); gpkg moves to the same real-path loading. - As built: zlib 1.3.2, libarchive 3.8.9 (gzip + tar only; every - other codec, crypto library and front-end disabled), libconfig - 1.8.2 (no C++), luajit 2.1.1788856981 (commit c6ffc141), - libglacier-ng 4.0.0, glacier-ng 4.0.0, doas 6.8.2 (OpenDoas, no - PAM, no timestamp). The doas.conf rule is given for both `cmd - gstore` and `cmd /usr/bin/gstore`: OpenDoas matches what was typed. - luajit is linked -static-libgcc, since Everest ships no libgcc_s - (see section 6). - - 1.5 [DEFERRED 2026-10-06 by the user: manual installation is one of - Everest's main features, so the installer comes later. 3.1 is - next.] - [2026-10-07, the user: a manual install works from a live Everest - system or any Linux host; the live system is the preferred, - officially supported way. The user is trying the first disk - install (QEMU) themselves.] - The installer. Undesigned; needs its own design session - (SECURITY_DESIGN section 10). Partitioning, a bootloader or an - EFI-stub kernel on the ESP, copying the kernel there (a symlink - won't do on FAT), a disk image. - - Already done on this path: hash verification, package symlinks, the - merged-/usr tree on syspkg -n, /etc config handling, a QEMU-bootable - musl + busybox + linux + everest-bootscripts set. - - -+--------------------------------------------+ -| 2. Package-manager features | -+--------------------------------------------+ - - 2.1 UPGRADES. Spec (2026-10-04): - - Replacing an installed version is `-lO` (local file) — plain - -l refuses ("extra::foo 1.0.0 is already installed.", nothing - more). [DONE 2026-10-04] - - The replaced version is BACKED UP: its files compressed into - /backup///-.gpkg + .sha256, a - complete installable package (saved manifest included). - KEEP_OLD in glacier.conf = how many backups to keep per - package (0 = none). No default: glacier.conf ships with - KEEP_OLD = 1, and an operation that would replace a version - refuses if it's missing or invalid. [DONE 2026-10-04] - - A restore interface for backups: later. (A backup can already - be reinstalled with -lO.) - - `gpkg -u` / `syspkg -u` = upgrade from a REMOTE repository; - waits for 3.1, like -f. [DONE 2026-10-07: REPO_DESIGN - section 6, "As implemented".] - - /etc follows the existing config rules regardless. - - 2.2 [DONE 2026-10-07: REPO_DESIGN section 6, "As implemented".] - gpkg -f / syspkg -f: MERGE. Spec (2026-10-04): exactly like -l, - except the package comes from a remote repository by name - instead of from a local file. Same summary, verification, scope - rules and transaction. Depends on 3.1 (remote repositories + - signing): until then there is nothing safe to fetch from. - - 2.3 Dependencies. [DONE 2026-10-05; automatic closure DONE - 2026-10-07 with -f/-u (REPO_DESIGN section 6).] Spec (2026-10-05), all three checks in one pass, no override flag, - every problem reported (one line each) before failing: - - A dependency's PKG_VER is a MINIMUM (installed >= PKG_VER). - Matched by name, any repo. - - A user package's dependency may be met by system scope or the - user's own scope. syspkg -x checks system-scope dependents - only. - - Conflicts: both directions (new lists installed, or installed - lists new), by name; PKG_VER is ignored. - - Missing dependencies REFUSE until 3.1; then automatic closure - (GLACIER_BOOTSTRAP 9e). - - Index records auto vs explicit now: /.glacier-auto in the - store, index line repo::name::version::auto|explicit. - - Messages: - extra::foo requires bar >= 1.2.0, which is not installed. - Removing base::musl breaks extra::foo. - extra::foo conflicts with extra::bar. - - install: refuse if a dependency isn't installed (or in the - same transaction); - - REMOVE: refuse to remove a package others depend on. Today - nothing stops `syspkg -x musl` from breaking every binary on - the system. Highest-value item in this section; - - conflicts: refuse to install a package that conflicts with - an installed one. - 9e DECIDED 2026-10-05: automatic closure, after 3.1 (see above). - - 2.4 Queries: list installed packages, show a package's details, find - which package owns a file. The index has the data; no CLI shows it. - - 2.5 Rollback. Every commit moves the previous state to old/ and then - deletes it. Keep it (or the last N), plus a command to return to - it. Interacts with 2.1's KEEP_OLD. - - 2.6 [DONE 2026-10-05: refused in every scope, before the prompt and at - commit (deps.c check_collisions).] - File conflicts between packages: two packages shipping the same - path — whichever links last silently wins. Detect and refuse. - - 2.7 glacier.conf parsing. [DONE 2026-10-04 for integers: - gl_conf_get_int, no defaults, missing/unreadable/wrong-type are - distinct errors.] Still open: rejecting UNKNOWN keys (CLAUDE.md bug - 10's lesson — a misspelled KEEP_OLD currently reads as "not set", - which at least fails loudly). - - 2.8 gstore: -s (sync) is a stub; there's no restore command although - gstore -b's output tells you to run -r (gl_restore_istore exists). - - 2.9 User-scope config files: user packages still link etc/ into a - links tree that's rebuilt on every commit. - - 2.10 Hardlink entries in package archives are skipped at extraction. - - -+--------------------------------------------+ -| 3. Security | -+--------------------------------------------+ - - 3.1 Remote repositories + signing (authenticity, keyring). The agreed - next major item. Design: REPO_DESIGN.txt (2026-10-06; decisions in - sections 1 and 10, order of work section 9). [IN PROGRESS - 2026-10-06: steps 1 and 2 DONE (gsign; the local base rule, - repos.conf + keyring, gbuild -k, bootstrap carries .sig, Everest - signs with everest-2026) and 3 (grepo; the signed index; - syspkg/gpkg -y refresh with rollback state) DONE; step 4 (-f with - closure, -u, the cache) DONE 2026-10-07; step 5 (glacier- - bootstrap -r) next, then 6 (user repos).] Unblocks remote - glacier-bootstrap. Until then, GLACIER_BOOTSTRAP's pinned - templates are the safe bridge for remote fetches. - - 3.2 Hash verification lives in the CLIs' shared module. A third-party - tool calling gl_install_pkg directly isn't verified. Consider - moving it into the library, like the base-in-user-scope refusal. - - 3.3 Manifests don't record the SYS_PROFILE they were built under, so a - package built for the wrong target can't be detected. - - 3.4 gstore -n accepts UIDs with no passwd entry (pre-provisions a - directory nobody owns yet; a typo creates a stray one). - - -+--------------------------------------------+ -| 4. Build tooling | -+--------------------------------------------+ - - 4.1 gbuild system profiles (-P ARCH-LIBC[-FEATURE...]) and gworld's - SYS_PROFILE recipe field. CLAUDE.md described both as done; neither - exists in the tree (only one gbuild, in glacier-ng). Today the - target libc is decided by where gbuild runs (~/Projects/everest - builds in Alpine for musl). - [2026-10-07, the user: Everest will run under glibc as well as - musl, so profiles are a real requirement, not a nicety. The - libc is picked at install time (Gentoo/Void style), one per - system. Open: how packages are kept apart (section 6).] - - 4.2 Move ~/Projects/everest's per-package gbuild commands into gworld - recipes once 4.1 lands. - - -+--------------------------------------------+ -| 5. Performance (not urgent) | -+--------------------------------------------+ - - 5.1 gl_relink_store / gl_rebuild_index rescan the whole store on every - commit. Fine at current scale; a dirty set is the fix. - - -+--------------------------------------------+ -| 6. Decisions waiting | -+--------------------------------------------+ - - - Images are only ever bootstrap OUTPUT (IMAGE_DESIGN 9a / - GLACIER_BOOTSTRAP 9a). - - Where the pinning helper lives (GLACIER_BOOTSTRAP 9f). - - 2.1's open questions a-d (upgrade backups). - - extra vs community: should they ever behave differently? - - The installer (1.5), deferred. - - libgcc (1.4): luajit is built with -static-libgcc because Everest - has no libgcc_s. Claude's call, not yet reviewed; the alternative is - a GCC runtime package in base, which later C++/unwinding packages - would need anyway. - - glibc and musl (4.1): DECIDED 2026-10-07 that the user picks the - libc at install time, like Gentoo's profiles / Void's glibc and musl - ISOs; one libc per system. Still open: how packages are kept apart - (Claude recommends both per-libc repos, as Void, AND a libc field in - manifest + index that the library refuses on a mismatch with the - system's recorded libc). - - -+--------------------------------------------+ -| 7. Done | -+--------------------------------------------+ - - [DONE 2026-10-07] -f and -u from repositories (3.1 step 4; 2.1's -u, - 2.2, 2.3's closure): first repo serving a name wins; missing deps - added auto, too-old ones upgraded; downloads in /cache/REPO, - hashed against the signed index, manifest must match the entry, - deleted after commit. tests/fetch_alpine.sh (84 checks, 17 mutants). - - [DONE 2026-10-06] Packages for glacier itself (1.4): zlib, libarchive, - libconfig, luajit, libglacier-ng, glacier-ng in base, doas in extra; - everest-bootscripts 1.1.0 ships /etc/doas.conf. Everest's initramfs - installs all 11 packages; in QEMU, syspkg/gpkg run from the store, - syspkg -x musl is refused (dependents), a wheel user runs doas - gstore -n without a password, then gpkg -l. gpkg loads lib/ from its - realpath. tests/installed_alpine.sh (30 checks) installs glacier in - that layout and runs it from the store. Found on the way: gbuild's - clone warning broke builds from a commit hash (CLAUDE.md bug 28); - syspkg/gstore never checked the ancestors of libglacier-ng's store - dir, which the installed .so's live in (bug 29; both mutations - caught). - [DONE 2026-10-07] glacier-bootstrap configures repositories (1.3): - syspkg -R's -y/-f/-u use TARGET's own repos.conf and keys (each - file's real path must stay inside TARGET); bootstrap runs - syspkg -R T -y when T's repos.conf gives a url (exit 7 on failure, - a warning when none does). Everest: new base package everest-repos - 1.0.0 (/etc/glacier/repos.conf + everest-2026.pub), moved out of - everest-bootscripts (now 1.3.0). bootstrap_alpine.sh 100 checks - (6 mutants, all caught); repo/fetch suites updated; full regression - green; Everest rebuilt and booted. - [DONE 2026-10-06] glacier-bootstrap, local mode (1.3): template - (NAME=, PKG=name ver [sha256:pin]; strict), verified private copies - handed to syspkg -R in one transaction, template-level dependency / - conflict / name checks, -n, -t. tests/bootstrap_alpine.sh (77 - checks, 11 mutations caught). ~/Projects/everest's initramfs is now - a glacier-installed system (templates/minimal.template), booted in - QEMU: /glacier/sys, merged-/usr links into the store, /etc copied, - a non-root user runs busybox. - - [DONE 2026-10-05] syspkg -R/--root DIR + --strict (1.2) and file - collisions (2.6): gl_check_sysroot (root-owned, non-symlink, not - group/world-writable, every ancestor), ctx->strict (a would-be link - refusal fails the transaction before the prompt and at commit; -O - still displaces), two packages shipping one path refused in every - scope. tests/root_alpine.sh (50 checks, 7 mutations caught). gpkg - silently ignored unknown flags (CLAUDE.md bug 27). - [DONE 2026-10-05] sysroot in the library (1.1): *_at contexts and - gl_init_sys_at, install paths in the context with runtime translation - at link/prune/displace, /usr and /etc under the sysroot, user scope - refuses one. tests/sysroot_alpine.sh (33 checks, 8 mutations caught). - Found on the way: live-context removal deleted foreign files - (CLAUDE.md bug 26). - [DONE 2026-10-05] Dependencies and conflicts (2.3): src/deps.c - (gl_check_plan before the prompt; gl_check_txn enforced by - gl_commit_transaction; live-context installs/removals checked inside - gl_install_pkg/gl_remove_pkg), index field 4 auto|explicit + - .glacier-auto + gl_set_pkg_auto, gl_read_pkg_manifest split out of - gl_install_pkg. tests/deps_alpine.sh (41 checks, 8 mutations caught). - Found on the way: the live index was rewritten through a seeded - hardlink (CLAUDE.md bug 25), tests/test_index_abort.lua. - [DONE 2026-10-05] System scope world-readable (found while specifying - 2.3): /glacier/sys was root 0700 throughout, so non-root users could - run nothing syspkg installed. Dirs 0755 / index 0644, and created - modes no longer depend on the umask. tests/sys_perms_alpine.sh. - - [DONE 2026-10-04] Version replacement + backups (2.1): -lO replaces, - KEEP_OLD backups, gl_backup_pkg / gl_prune_backups / gl_conf_get_int, - the manifest saved in the store (.glacier-manifest), add_to_archive - learns symlinks (gstore -b silently dropped them too), gpkg modifier - flags (-O -S -V) order-independent so `gpkg -lO` works. - tests/upgrade_alpine.sh (29 checks). - [DONE 2026-10-04] Correctness batch: - - gbuild: autotools detected before a bare Makefile (bug 8 had - regressed); --cross-prefix fixed (its option-table key was - misspelled); -v/--version print the version as documented, with - --verbose for verbose output. - - gpkg -x: summary resolved from the index (was "unknown::pkg - 0.0.0"); a package that isn't installed fails before the prompt. - - gpkg: precise refusal for a missing / squatted / loosened user - directory (was "No index found"), via gl_usr_base_status. - - gpkg -h lists -l and -S; -f/-u described by the 2.1/2.2 specs. - - Up-to-date reinstall logs once. - - Link conflicts reported once, by the package that has them, not - again on every later system commit (.glacier-fresh marker). - - A failed extraction no longer leaves a half-extracted version dir - (in a live context, every retry then said "already installed"). - - Dead old-layout code removed from pkg.c (gl_prepare_pkgdir and the - gl_usr_* / gl_sys_* dir_t constants). - - tests/glacier_ffi.lua is a wrapper over lib/glacier_cdef.lua; its - own copy had already drifted (missing GL_INSTALL_ERR_SCOPE). - - Dockerfile.arch / .debian moved to the per-uid layout (root-owned - /app, libglacier-ng built from source, the gstore -n doas rule). - [DONE 2026-10-04] Hash verification; package symlinks; per-uid user - layout + doas gstore -n; syspkg -n top-level tree; /etc config - handling (copy + .new); -O/--overwrite; everest-bootscripts. diff --git a/SECURITY_DESIGN.txt b/SECURITY_DESIGN.txt deleted file mode 100644 index a56ef01..0000000 --- a/SECURITY_DESIGN.txt +++ /dev/null @@ -1,401 +0,0 @@ -+--------------------------------------------+ -| Package integrity & scope security | -+--------------------------------------------+ - -This document records design decisions made in one planning session, -covering package integrity verification and the hard separation -between per-user and system-scope package tools. NONE OF THIS IS -IMPLEMENTED YET. It exists so implementation can start from a settled -plan instead of re-deriving it. - -Companion document: PACKAGE_SCOPES.txt (repo/scope symlink routing — -referenced but not repeated here). - - -+--------------------------------------------+ -| 1. Scope of this phase | -+--------------------------------------------+ - -Two different guarantees are in play, and they are NOT the same thing: - - integrity - has this file been corrupted or altered - authenticity - did this actually come from who it claims to be - -A hash alone only ever proves integrity. If the hash travels with the -file from the same untrusted source, tampering both together defeats -it. This phase is INTEGRITY ONLY. Authenticity (signing, a trusted -keyring) is a deliberate future phase, tied to remote-repo support — -not being designed in detail now, but a few choices below are made to -stay cheap to extend into later. -[2026-10-06: that phase is REPO_DESIGN.txt. Its first part is in: a -base package installed with syspkg -l needs a signed sidecar -(REPO_DESIGN section 7).] - -Everest is a security-focused distro (this is also *why* per-user -package isolation exists in the first place). Two sides of the CIA -triad — confidentiality is out of scope here, but integrity and -(eventually) authenticity are both treated as first-class, not -best-effort. - - -+--------------------------------------------+ -| 2. Hash algorithm: SHA-256 | -+--------------------------------------------+ - -Decision: SHA-256, not SHA-512. - -Rationale (SHA-512 was seriously considered, not dismissed by default): - - SHA-512's usual advantage (faster on 64-bit CPUs, due to 64-bit - word operations) does not hold across this project's actual - target set. Everest explicitly supports multiple architectures - via SYS_PROFILE, including 32-bit ones — on a 32-bit target, - SHA-512 is SLOWER than SHA-256 (64-bit math has to be emulated). - - SHA-256's 128-bit collision resistance is not a meaningful - weakness for this use case. There is no realistic attack path - where 128 bits is the bottleneck for "did this archive get - corrupted or tampered with." - - SHA-256 is what every comparable tool already defaults to (apk, - pacman, dpkg), and is the simpler implementation to vendor and - audit (smaller constant tables, no 64-bit rotates). - -Escape hatch, explicitly kept open: hash values are namespaced as -"sha256:", never a bare hex string, specifically so a future -algorithm change is additive, not a format migration. "sha256 can -always be added to base if needed" — i.e. if the vendored -implementation is ever found lacking, the fallback is depending on a -real sha256sum binary once one exists in the base repo, not a redesign -of the sidecar format. - - -+--------------------------------------------+ -| 3. What gets hashed, and how | -+--------------------------------------------+ - -WHAT: whole-archive only, for now. Per-file hashing (and the -eventual `gpkg --verify`-style installed-file audit it would enable) -is explicitly deferred, not rejected. - -WHERE: a sidecar file next to the .gpkg — - - musl-1.2.5.gpkg - musl-1.2.5.gpkg.sha256 <- contains exactly: sha256: - -Sidecar was chosen over embedding in the manifest specifically because -a whole-archive hash cannot cleanly be embedded inside the file it is -hashing without excluding the hash field itself from the computation. -This also generalizes naturally to a future remote repo index that -just lists hashes for everything it serves. - -IMPLEMENTATION SHAPE: one shared vendored implementation, compiled -two different ways, so there is exactly one place the algorithm -itself is ever implemented: - - - src/sha256.c / src/sha256.h - Streaming API (init/update/final), not just "hash this file" — - chosen now specifically so per-file hashing later reuses the - same primitive without a rewrite. - - - gpkg / syspkg side: - Compiled into a PRIVATE .so (no public header, not part of the - split-library public API surface). Loaded directly via FFI from - gpkg_common.lua (see section 6). Private for now because this is - new, unaudited code; promoting it to a real public - libglacier_crypto.so is the natural path once per-file hashing - is built and the API has proven itself. - - - gbuild side: - Compiled into a tiny standalone CLI helper, `gsha256sum FILE`, - printing `sha256:` to stdout. gbuild shells out to it the - same way it already shells out to git/tar/make. This keeps - gbuild from depending on the host having sha256sum or openssl - installed, while still not needing gbuild to link against the - private .so directly (gbuild is a bash script, not something - that can drive FFI). - - gbuild change: after producing the .gpkg archive, hash it with - gsha256sum and write the sidecar alongside it. This is not optional - groundwork — the moment verification is turned on, EVERYTHING - becomes a "missing sidecar" failure until this exists, so the two - changes (gbuild writes sidecars / gpkg+syspkg check them) ship as - ONE atomic change, not sequential phases. - - -+--------------------------------------------+ -| 4. Refusal policy | -+--------------------------------------------+ - -Missing sidecar and hash mismatch are treated IDENTICALLY. There is no -soft "unverified, proceed anyway by default" tier — absence of proof -is treated the same as proof of tampering. - - repo == "base" -> ALWAYS refuse. No flag, no - scope, no exception. Ever. - scope == SYS (via syspkg) -> ALWAYS refuse, for ANY repo, - including extra/community. - No flag overrides this. - scope == USR && repo != base -> refuse by default. The ONLY - place a bypass flag could ever - apply, once one exists. - -No bypass flag exists yet. One may be added later, but ONLY for the -USR-scope/non-base case above — never for base, never for system -scope, regardless of how the flag is invoked. - -Net effect, stated as a real security property: there is no flag -combination, present or future, that can install a corrupted base -package or a corrupted system-scope package. - -HOOK POINT: gpkg's read_manifest_fields already resolves a package's -repo before any transaction machinery runs (it's needed for the -existing confirmation summary). Verification belongs right there, -before gl_init_stage_context is ever called. A failure aborts that -package the same way any other install error already does today — no -new failure-handling pattern needed. - - -+--------------------------------------------+ -| 5. Tool separation: gpkg / gstore / syspkg | -+--------------------------------------------+ - -gpkg and gstore are BOTH strictly per-user tools. Neither has, or will -ever have, any code path into GL_SCOPE_SYS. This is a reversal of -earlier work in this project (gpkg briefly gained a -s/--system flag -and gstore briefly gained -N/--new-system) — both need to come back -out. Recorded here explicitly so it isn't missed during -implementation: removing capability that already exists in the -current tree, not just "don't add it." - -syspkg is a new, separate binary — the SOLE tool with any system-scope -capability at all: install, remove, AND store creation/init (what -gstore -N used to do). One tool to secure, one tool to audit, one -place the privilege boundary has to be enforced. - -Why store creation belongs in syspkg and not "the installer calling -gl_init_sys() directly": that would create a second, independent, -unaudited entry point into system-scope mutation — the exact problem -already solved for install/remove. syspkg owning ALL system-scope -mutation, with nothing else able to touch it, is the actual point. - -gstore's existing UID bounds-check behavior (hard-refuses < 1000, even -under doas, even as UID 0) is confirmed already working correctly and -is being preserved exactly as-is — gstore stays permanently -user-scope-only; the fix is removing -N, not touching the bounds -check. - -LATER AMENDMENT: `gstore -n` does run as root — it creates -/glacier/usr/ inside a root-owned parent (PACKAGE_SCOPES.txt -section 1). Still user scope only. Root runs it with an explicit UID; a -user runs it for themselves through a doas rule pinned to exactly -`-n`, which is what stops them naming another UID (same boundary as -section 6). Being root-run, gstore follows syspkg's loading rules -(pinned paths, -E, root-ownership checks). - - -+--------------------------------------------+ -| 6. syspkg privilege model | -+--------------------------------------------+ - -syspkg is always run as root. It is invoked via doas (or sudo) — -NEVER made setuid. This was an explicit rejected alternative, not an -unconsidered default: - -A setuid LuaJIT interpreter is a real anti-pattern. It would inherit -environment variables, library search paths, and require() resolution -from whatever untrusted shell invoked it — all of which become -privilege-escalation surface the instant the process is running as -root. This is the same class of problem that has made setuid -scripts (shell, Perl, anything with a runtime) a long-standing -security no-go. - -syspkg's own responsibility is limited to checking geteuid() == 0 and -refusing otherwise. The actual privilege boundary is enforced by doas -— a hardened, audited, purpose-built tool for exactly this — not -reimplemented inside syspkg itself. - -LATER AMENDMENT (loading, as built): syspkg and gstore run under -`luajit -E`, and pin package.path and every ffi.load to their own -realpath's lib/. Before loading anything as root, each file they load -(every .lua, every .so, including those pulled in through $ORIGIN) and -lib/ itself must be root-owned and not group/world-writable, and so -must every ancestor of the script's realpath AND of each loaded file's -realpath. The second set matters once installed: lib/glacier is a -symlink to /usr/lib/glacier, whose entries link into libglacier-ng's -store directory, a tree the script's own ancestors never reach -(2026-10-06, CLAUDE.md bug 29). - - -+--------------------------------------------+ -| 7. Shared code: gpkg_common.lua | -+--------------------------------------------+ - -gpkg and syspkg need nearly identical machinery: manifest reading, the -summary/confirmation prompt, staged-transaction handling -(gl_init_stage_context -> install/remove loop -> commit/abort), and -the hash-verification check from section 4. All of that lives in -lib/gpkg_common.lua, required by both. - -What stays DISTINCT per-binary: - - Which scope each one is even capable of requesting. gpkg's code - simply never constructs a GL_SCOPE_SYS context — not "doesn't - expose a flag for it," does not have the capability in its code - path at all. - - The privilege model (only syspkg is ever invoked with elevation). - -This split means the refusal matrix in section 4 lives ONCE in the -shared module — it does not need to be written twice or kept in sync -across two files. syspkg is simply the only caller that can ever -reach the scope == SYS branch of it. - -This decision exists partly because of history in this project: a -previously-duplicated ffi.cdef block across three files caused a real, -hard-to-diagnose bug. Not repeating that shape here on purpose. - - -+--------------------------------------------+ -| 8. Base repo cannot install to USR | -+--------------------------------------------+ - -A package in the base repo can NEVER be installed under GL_SCOPE_USR -(per-user scope). This is very unlikely to be attempted in practice, -but is being hardcoded as a real invariant anyway, not left as an -assumption. - -ENFORCEMENT LEVEL: the library itself (gl_install_pkg), not any CLI. -scope == GL_SCOPE_USR && repo == GL_BASE_REPO refuses unconditionally, -regardless of which caller asked for it. - -Rationale: the whole point of the split-.so architecture is that a -third-party tool can be built directly against libglacier-ng without -going through gpkg/syspkg at all. A rule that only one CLI happens to -respect is not a real guarantee. This must be a property of the -package system itself. - - -+--------------------------------------------+ -| 9. syspkg self-update | -+--------------------------------------------+ - -syspkg will itself ship as a base-repo package (it has to, to be part -of the minimal system) and therefore has to be able to update itself -while running. Resolved the same way the earlier libc-live-update -question was resolved (see PACKAGE_SCOPES.txt section 5): POSIX -unlink() semantics already make this safe — a running process keeps -its old inode open even after the symlink swap, only newly-spawned -processes see the new version. No special self-replace mechanism -needed; this falls directly out of the existing atomic-rename commit -design. - - -+--------------------------------------------+ -| 10. Open: the installer / grootstrap | -+--------------------------------------------+ - -STATUS: genuinely undecided, not just unimplemented. The actual -process of installing Everest end-to-end is, in the author's own -words, "kind of elusive" right now. grootstrap's rework is explicitly -BLOCKED on this getting its own dedicated design pass — not something -to force an answer on tonight. - -What IS clear: - - grootstrap (or whatever the installer turns out to be) cannot be - correctly rebuilt until syspkg, gpkg_common.lua, and hash - verification all exist — every package a bootstrap installs is - base-repo, the strictest tier, so the installer is the FIRST real - consumer of all three at once. - - Whatever places syspkg itself onto a target filesystem, before - syspkg exists there to enforce anything, is definitionally outside - the "corrupted base package can never install" guarantee. This is - an honest edge, not a flaw — it only closes once the installer's - actual shape is designed. Live/install media is presumably the - root of trust at that point (if you trust what you booted from, - you trust what it lays down) — but this has not been decided, only - named as the shape of the problem. - -REFERENCE MATERIAL (from an old installation guide at -everestlinux.org/install, read only through its "Syncing the Build -Environment" section — earlier material only, deliberately not -consulting anything past that point. Describes a previous, -possibly-outdated vision of the install process; treat as INPUT to the -future design pass, not as decisions already made. No system image -tarball concept appears anywhere in this range — that idea is -discarded entirely, not merely unmentioned): - - - "system mountpoint" — a target directory (example used: - /mnt/everest, with a SYS_MNT env var pointing at it) that the new - system's root gets built at, kept separate from the host doing the - building. Conceptually the same thing grootstrap's TARGET_DIR - already is. - - - Partition layout described around that mountpoint: an EFI system - partition at .../boot, an OPTIONAL dedicated partition for - /glacier itself (suggested minimum 15 GB), an optional /home - partition, and the remainder as root. The optional standalone - glacier partition is worth noting specifically — it implies - /glacier was originally conceived as something that could be its - own filesystem, separate from root, not necessarily just a - directory tree living on the root filesystem. Not a decision, - just a detail worth not losing. - - - "template index" — a named, downloadable list of packages - defining what a given install should contain (the guide's own - words: "provides a list of packages which can be merged into a - build environment, thereby creating a semi-functional system"). - The guide frames CHOOSING a template index around a specific set - of questions: does the install need 32-bit libraries, will it run - proprietary software that can't be recompiled, does it need a - specific C library for the hardware, is SELinux wanted, is a - non-default init system wanted. Those are essentially the exact - axes SYS_PROFILE already encodes (ARCH-LIBC[-FEATURE...]) — this - is a real correspondence, not a coincidence to ignore. Worth - deciding whether a template index simply IS a SYS_PROFILE plus a - recipes/ set under current design, or a separate downstream - concept (e.g. a pre-resolved list of already-built package - references to fetch, rather than a list of things to build from - source). The guide also warns that switching template - indexes/profiles after install requires rebuilding most of the - system — consistent with SYS_PROFILE being a foundational, - not-meant-to-change-casually choice in the current design too. - - - "glacier-bootstrap PATH_TO_TEMPLATE_INDEX /mnt/everest" — a - referenced (possibly not-yet-existing-in-current-form) tool - described as taking "the specified template index, and - bootstrap[ping] a system at the specified directory, using the - packages listed within the template index as a guide." This is - package-list-driven bootstrapping, not image-based — it lines up - with what grootstrap is already trying to be (extract/install a - defined set of packages into a target directory), not with - anything tarball-shaped. - -None of the above is a decision. It's what exists to react to when the -installer gets its own design session — scoped deliberately to only -the early, environment-setup half of the old guide for now. - - -+--------------------------------------------+ -| 11. Build order for tomorrow | -+--------------------------------------------+ - -Dependency order, not necessarily literal implementation order within -a day, but grootstrap specifically cannot start until the first three -exist: - - 1. src/sha256.c / src/sha256.h (no dependencies) - 2. gsha256sum CLI (needs 1) - 3. private hash .so for gpkg/syspkg (needs 1) - 4. gbuild: write sidecar on build (needs 2) - 5. lib/gpkg_common.lua (shared logic extraction) - 6. gl_install_pkg: base->USR refusal (library-level, needs nothing - above, can happen any time) - 7. gpkg: remove -s/--system entirely (needs 5, to not duplicate - logic while trimming it) - 8. gstore: remove -N/--new-system entirely - 9. syspkg: new binary — install/remove/init under GL_SCOPE_SYS, - doas-only, no setuid (needs 1, 3, 5) - 10. grootstrap rework BLOCKED — needs 4, 9, AND a - separate installer design - pass (section 10). Do not - start until that exists. - -Verify-downloads-from-remote-repos (authenticity, signing, keyring) -is the explicitly agreed NEXT major item after everything above is -implemented — not part of this phase. diff --git a/SECURITY_REVIEW_2026-07-16.md b/SECURITY_REVIEW_2026-07-16.md deleted file mode 100644 index d21ba06..0000000 --- a/SECURITY_REVIEW_2026-07-16.md +++ /dev/null @@ -1,136 +0,0 @@ -# Security Review — libglacier-ng (dev branch, working tree) - -Date: 2026-07-16 -Scope: uncommitted working-tree changes (Makefile, config.mk, src/common.h, -src/istoreutils.{c,h}, new src/transaction.{c,h}). The `dev` branch had no -new commits vs. `origin/dev`, so the actual diff under review is the -unstaged/untracked working-tree state. - -All three findings below share one root cause: package manifests -(`PKG_NAME` / `PKG_REPO`, read from `manifest.gpm.cfg` inside the `.gpkg` -archive being installed) are fully attacker-controlled and are never -validated anywhere in the codebase. A full-repo search for -`signature|verify|trusted|checksum|sha256|gpg|allowlist` returned zero -hits — there is no package authenticity or provenance check at all. - -This PR's changes (`GL_SCOPE_SYS` / `gl_init_sys`, and the new -`GL_BASE_REPO` → `/usr` symlink routing) newly plug that untrusted data -into root-privileged, system-wide install paths, which is what escalates -these from "attacker writes into their own store" to "attacker writes as -root, or shadows real `/usr` binaries." - ---- - -## Finding 1 — Authorization bypass via self-declared "base" repo - -* **File:** `src/istoreutils.c:742` (also `:859`, `:1404`) -* **Severity:** High -* **Category:** `authorization-bypass` -* **Confidence:** High -* **Status (2026-10-06):** closed for local installs by recommendation - (b): `syspkg -l` of a package whose manifest says base requires its - sidecar signed by a key `/etc/glacier/repos.conf` lists for base - (REPO_DESIGN.txt section 7); user scope refuses base outright. Remote - packages get (a) with the signed index (REPO_DESIGN section 4). Still - open for a third-party caller of `gl_install_pkg` (ROADMAP 3.2). - -**Description:** System-scope symlink placement into `/usr` is gated only -by a package's manifest self-declaring `PKG_REPO="base"`. There is no -check that the package actually originated from a trusted/vetted base -repository — the classification is just a string the package author -wrote into their own manifest. - -**Exploit scenario:** An operator runs `gpkg -s malicious.gpkg` (a -normal, documented system-scope install per `PACKAGE_SCOPES.txt`) on a -package whose `manifest.gpm.cfg` the attacker fully controls. Setting -`PKG_REPO="base"` causes `gl_link_pkg` (istoreutils.c:742) and -`gl_relink_store` (istoreutils.c:1404) to route the package's symlinks -into `GL_BASE_LINKS_DEST` (`/usr`) instead of the isolated -`/glacier/sys/links` tree — the same privileged, real-FHS locations init -scripts, systemd units, and shebang lines trust. Combined with Finding 3 -(unsanitized `PKG_NAME`), the attacker can target specific paths such as -`/usr/bin/sudo`. - -**Recommendation:** Don't trust the manifest's self-declared repo for -privilege routing. Either (a) determine repo/trust from the source the -package was fetched from (signed repo metadata, not embedded manifest -fields), or (b) require a separate signature/checksum check before a -package is allowed to claim `base` classification and land in `/usr`. - ---- - -## Finding 2 — Tar-slip path traversal during archive extraction - -* **File:** `src/istoreutils.c:1242` (loop starting ~1234, `dest_path` built at 1249) -* **Severity:** High -* **Category:** `path-traversal` -* **Confidence:** High - -**Description:** `gl_install_pkg` extracts the package tar with a -hand-rolled `open()`/`mkdir()` loop instead of libarchive's -`archive_write_disk` (which offers `ARCHIVE_EXTRACT_SECURE_NODOTDOT` / -`SECURE_SYMLINKS` protections). The per-entry relative path (`rel_path`, -istoreutils.c:1242) is taken directly from the tar entry name after -stripping a known prefix, and is concatenated into `dest_path` via -`snprintf` with no rejection of `..` segments or absolute paths. - -**Exploit scenario:** Because the strip prefix is -`"-/files/"` and `pkg_name` is itself attacker-controlled -(pulled verbatim from the manifest, no validation), the attacker fully -controls the prefix match and can name a tar entry -`"-/files/../../../../etc/cron.d/pwn"`. After prefix -stripping this becomes `../../../../etc/cron.d/pwn`, written wherever the -installing process can write. This code path is reachable for both -per-uid and (newly, via this PR) root-privileged system-scope installs, -so the same bug now yields root-level arbitrary file write. - -**Recommendation:** Reject any entry path containing `..` components or a -leading `/` before extraction, or switch to `archive_write_disk` with -`ARCHIVE_EXTRACT_SECURE_NODOTDOT | ARCHIVE_EXTRACT_SECURE_SYMLINKS | -ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS` set. - ---- - -## Finding 3 — Path traversal via unsanitized PKG_NAME / PKG_REPO in store paths - -* **File:** `src/istoreutils.c:1196` (manifest parsing: `src/pkg.c:149,153`) -* **Severity:** Medium–High -* **Category:** `path-traversal` -* **Confidence:** High - -**Description:** `gl_gpm2gpkg` (`pkg.c:149,153`) reads `PKG_NAME` and -`PKG_REPO` straight out of the archive's manifest config with -`config_lookup_string` + `strdup`, no validation. `gl_install_pkg` then -builds the package's store directory as `"%s/%s/%s"` from -`ctx->store_path`, `pkg.pkg_repo`, `pkg.pkg_name` (istoreutils.c:1196) -and `mkdir -p`s it. - -**Exploit scenario:** A manifest with `PKG_REPO="../../../../tmp"` (or a -`PKG_NAME` containing `../` segments) causes the package directory — -and, via the extraction loop right after (Finding 2), arbitrary files — -to be created outside `ctx->store_path` entirely. Previously this only -affected a single user's own per-uid store; with this PR's new -`GL_SCOPE_SYS` (`ctx->store_path == "/glacier/sys/store"`, root-owned), -the same bug now lets an untrusted package write anywhere root can -write. - -**Recommendation:** Validate `PKG_NAME` and `PKG_REPO` against an -allowlist pattern (e.g. `^[A-Za-z0-9._-]+$`) immediately after parsing -in `gl_gpm2gpkg`, rejecting the manifest outright if either field -contains `/`, `..`, or is empty. - ---- - -## Note — unrelated working-tree cleanup - -The working tree also contains what look like leftover failed-patch -artifacts, not part of the reviewed logic but worth cleaning up before -committing: - -``` -istoreutils.c.diff -istoreutils.h.diff -src/istoreutils.c.back -src/istoreutils.c.rej -src/istoreutils.h.back -``` diff --git a/SECURITY_REVIEW_2026-10-06.md b/SECURITY_REVIEW_2026-10-06.md deleted file mode 100644 index 2911d07..0000000 --- a/SECURITY_REVIEW_2026-10-06.md +++ /dev/null @@ -1,62 +0,0 @@ -# Security review, 2026-10-06 - -Scope: every active source file in libglacier-ng (`src/*.c`, `src/*.h`, -not the vendored Monocypher, not the unbuilt early prototypes) and -glacier-ng (`gpkg`, `syspkg`, `gstore`, `glacier-bootstrap`, `gbuild`, -`gworld`, `lib/*.lua`, `tests/mkpkg`, the Dockerfiles). Read line by line; -findings confirmed by running them in Docker where possible; each fix -has a regression test, mutation-checked unless noted. - -Tests: `glacier-ng/tests/audit_alpine.sh` (shell, `glacier-alpine_root`) -and `glacier-ng/tests/test_abort_unlocked.lua` (FFI suite). - -## Findings and fixes - -| # | Severity | Where | Finding | Fix | Test | -|---|---|---|---|---|---| -| 1 | **High** | `gl_install_pkg` | A package could ship top-level `files/.glacier-*` entries, glacier's own store files. As a symlink, `.glacier-fresh` made syspkg `open(O_CREAT\|O_TRUNC)` its target as root: an unsigned extra package truncated `/root/victim` to 0 bytes (reproduced). `.glacier-overwrite` granted the package `-O` without the user asking; `.glacier-manifest` rewrote its saved manifest. | Top-level names starting `.glacier-` are refused (`GL_MARKER_PREFIX`, common.h); the marker writes use `O_NOFOLLOW`. | audit_alpine: reserved names (mutants c3, c4 caught) | -| 2 | Medium | `gl_rmdir_recursive` (common.h) | `lstat` then `opendir` by path: root deleting a tree a user can write to (`gstore -x UID`) could be steered, by swapping a directory for a symlink between the two calls, into emptying the symlink's target. | fd-relative walk: `openat(O_DIRECTORY\|O_NOFOLLOW)`, `fdopendir`, `unlinkat`; the top path must not be a symlink. | audit_alpine: `gstore -x` race, 40 runs (mutant c1 caught 34-38/40) | -| 3 | Medium | `add_to_archive` (istoreutils.c) | Same class: `lstat` then `open`/`opendir` by path, no `O_NOFOLLOW`. Root backing up a user's store (`gstore -b`) could be steered into archiving root-only files. | fd-relative (`fstatat`/`openat(O_NOFOLLOW\|O_NONBLOCK)`/`readlinkat`); the opened descriptor's type is what gets archived. | **No failing-on-old test**: the window is too narrow for a shell race to hit (mutant c2 survived). Verified by review only. | -| 4 | Medium | `gl_gpm2gpkg` (pkg.c) | Manifests come from untrusted archives; libconfig honours `@include "FILE"`, so a manifest could make syspkg read any file as root. | A manifest with a line starting `@include` is refused (read into memory first, 1 MiB cap, no NUL). | audit_alpine (mutant c5 caught) | -| 5 | Low | `gl_gpm2gpkg` | A dependency/conflict entry without `PKG_NAME` ended the list early (later entries silently ignored, and leaked); names were not checked. | Every entry needs a `gl_valid_pkg_ident` name, else the manifest is refused. | audit_alpine (mutants c6, c7 caught) | -| 6 | Low | `gpkg_common.lua` | `read_manifest_fields` pattern-matched the manifest (via `tar` as root) and could disagree with the library: a decoy `// PKG_REPO = "community";` line hid that a package replaced an installed one, skipping the `-O` rule and the KEEP_OLD backup (two versions in the store). The tar extraction itself was not exploitable (GNU and busybox tar strip `..`; checked). | Replaced by `manifest_of`, a wrapper around `gl_read_pkg_manifest`; an unreadable manifest is refused before the prompt. | audit_alpine (old file as mutant l1, caught) | -| 7 | Low | `gstore`, `gpkg` | Text concatenated into `lg_printf` format strings: gstore's `argv[0]` and UID (as root), gpkg `-u`'s operand. | Passed as `%s` arguments; the `-u`/`-f`/`-s` stubs now refuse in one line. | audit_alpine (mutants l2, l3 caught) | -| 8 | Low | `gstore` | A UID above uid_t's range wrapped around in C to another UID. | Refused (`0..4294967294`). | audit_alpine (mutant l4 caught) | -| 9 | Low | `gl_abort_transaction` | Wiped the stage even for a context that never got the lock, i.e. another process's running transaction. | Only the lock holder's abort removes the stage (`GL_TXN_ERR_NO_TXN` otherwise). | test_abort_unlocked.lua (mutant f8 caught) | -| 10 | Low | `gpkg_common.lua` | Lua numbers passed to `lg_printf("%d")` (a double into varargs: undefined behaviour). | `%s` + `tostring`. | none (not observable) | -| 11 | Low | `gl_parse_semver` | `sscanf("%d")` on an untrusted, oversized number is undefined behaviour. | `strtol`, clamped to `0..INT_MAX`. | none (not observable) | -| 12 | Hardening | `is_glacier_symlink` | A plain prefix match: `/glacier/sys/store` also matched `/glacier/sys/store2/...` (only root can create such paths). | The prefix must be followed by `/` or end the target. | none | -| 13 | Bug | `join_with_cwd` (pkg.c) | `strlen(cwd + strlen(path) + 2)`: an out-of-bounds read. Unused. | Removed (see below). | n/a | -| 14 | Hardening | `lg_printf` | No format checking for C callers. | `__attribute__((format(printf, 2, 3)))`; the build is clean under `-Wformat=2 -Werror`. | the build | - -Reviewed and found sound: signature code (`sign.c`: strict signify -parsing, secrets wiped, `O_NOFOLLOW|O_EXCL` writes), the index parser, -extraction's tar-slip defences (`is_safe_rel_path`, deferred symlinks, -`crosses_symlink`, `O_NOFOLLOW`), the sysroot trust check, syspkg's and -gstore's hardened loading, the private-copy verification, shell quoting -in every `os.execute`/`io.popen`, `/etc` config handling, `-O` displace -and restore. - -## Removed as unused or redundant - -- libglacier-ng: the `dag`, `runtime` and `make_conf` modules (nothing - linked them); `gl_pkgver`, `gl_mkdir`, `gl_spawn_pkg`, `gl_cat_dir`, - `gl_cat_dir_and_ver`, `gl_return_dir`, `gl_return_dir_and_ver`, - `gl_free_path`, `gl_free_dir`, `gl_show_pkg_props`, `join_with_cwd`, - `empty`/`null_dep`/`null_conf`, `dir_t`; `gl_parse_index`, - `gl_free_index` (and `struct gindex`), `gl_find_pkg_repo` (duplicate of - `gl_find_pkg_repos`), `gl_sys_istore_exists`, `gl_restore_istore` - (also unsafe: followed symlinks when restoring); `lg_printf_no_newline`, - `lg_syslog`, `lg_log` (its declaration and definition disagreed), - `p2s`; `GL_CONF_PATH`; the broken `install_test_dir` Makefile target. - The marker names, defined twice (deps.c, istoreutils.c), now live once - in common.h; log.c includes log.h instead of redefining its enum. -- glacier-ng: `M.read_manifest_fields`, `M.extract_pkg_info`, - `M.summary`; `install_with_reinstall` is module-local; the matching - `glacier_cdef.lua` declarations. - -## Open - -- Finding 3 has no test that fails on the old code (see the table). -- Extracted entries keep setuid/setgid bits (known gap, unchanged). -- No size limits on extraction (a decompression bomb fills the disk). diff --git a/src/bar.gpm.cfg b/src/bar.gpm.cfg deleted file mode 100644 index fa5950c..0000000 --- a/src/bar.gpm.cfg +++ /dev/null @@ -1,17 +0,0 @@ -# -# bar -# - -PKG_NAME = "bar"; -PKG_VER = 1.0.0; -PKG_DESC = "example pkg"; -PKG_MAINT = "liamwaldron@everestlinux.org"; -PKG_COPYRIGHT = "GPL3"; - -PKG_DEPS = ( - { PKG_NAME = "foo"; PKG_VER = 1.1.1; }; -); - -PKG_CONFS = ( - {}; -); diff --git a/src/common.h b/src/common.h index 5250188..29d7929 100644 --- a/src/common.h +++ b/src/common.h @@ -34,6 +34,8 @@ * Dot-prefixed like the other store markers, so seeding carries it and * linking skips it; the index's 4th field is derived from it. */ #define GL_AUTO_MARKER ".glacier-auto" +/* /.glacier-src: built from this recipe repository (gl_set_pkg_src). */ +#define GL_SRC_MARKER ".glacier-src" /* The other files glacier keeps in a version dir (see gl_install_pkg): * the package's saved manifest, and the one-shot markers for the next * link pass (this transaction installed it; it may displace, -O). A diff --git a/src/deb.c b/src/deb.c deleted file mode 100644 index 7ce3d48..0000000 --- a/src/deb.c +++ /dev/null @@ -1,22 +0,0 @@ -#define _POSIX_C_SOURCE 200809L -#define _DEFAULT_SOURCE -#define _XOPEN_SOURCE 700 - -#include "color.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static int -extract_tar(const char *tarfile, const char *dest) -{ - struct archive *a = archive_read_new(); - struct archive *ext = archive_write_disk_new(); -} diff --git a/src/glacier.cfg b/src/glacier.cfg deleted file mode 100644 index 9572453..0000000 --- a/src/glacier.cfg +++ /dev/null @@ -1,8 +0,0 @@ - -// If GL_ALLOW_NONFREE is false, software tagged as NONFREE cannot be installed, -// even if NONFREE is listed under GL_ALLOWED_LICENSES. -GL_ALLOW_NONFREE = false; - -// GL_ALLOWED_LICENSES allows a user to configure which kinds of software Glacier -// is allowed to install. -GL_ALLOWED_LICENSES = [ "GPL", "GPL2", "GPL3", "BSD", "MIT", "APACHE" ]; diff --git a/src/glacier.log b/src/glacier.log deleted file mode 100644 index 1b147bf..0000000 --- a/src/glacier.log +++ /dev/null @@ -1,45 +0,0 @@ -[2025-09-16 17:54:10] [INFO] Glacier started with PID 12345 -[2025-09-16 20:09:54] [6] Glacier started with PID 12345 -[2025-09-16 20:13:34] [-173481940] Glacier started with PID 12345 -[2025-09-16 20:13:36] [-1935986644] Glacier started with PID 12345 -[2025-09-16 20:15:21] [INFO] Glacier started with PID 12345 -[2025-09-16 20:17:18] [INFO] Glacier started with PID 12345 -[2025-09-16 20:17:18] [ERR] Failed to install package glibc -[2025-09-16 20:19:42] [INFO] Glacier started with PID 12345 -[2025-09-16 20:19:42] [ERR] Failed to install package glibc -[2025-09-17 08:39:22] [INFO] Glacier started with PID 12345 -[2025-09-17 08:39:22] [ERR] Failed to install package glibc -[2025-09-17 11:33:39] [INFO] Glacier started with PID 12345 -[2025-09-17 11:33:39] [ERR] Failed to install package glibc -[2025-09-17 11:33:40] [INFO] Glacier started with PID 12345 -[2025-09-17 11:33:40] [ERR] Failed to install package glibc -[2025-09-18 14:21:45] [INFO] Glacier started with PID 12345 -[2025-09-18 14:21:45] [ERR] Failed to install package glibc -[2025-09-18 20:37:44] [INFO] Glacier started with PID 12345 -[2025-09-18 20:37:44] [ERR] Failed to install package glibc -[2025-09-22 23:24:51] [INFO] Glacier started with PID 12345 -[2025-09-22 23:24:51] [ERR] Failed to install package glibc -[2025-09-22 23:24:51] [INFO] Glacier started with PID 12345 -[2025-09-22 23:24:51] [ERR] Failed to install package glibc -[2025-10-16 14:45:24] [INFO] Glacier started with PID 12345 -[2025-10-16 14:45:24] [ERR] Failed to install package glibc -[2025-10-22 15:59:02] [INFO] Glacier started with PID 12345 -[2025-10-22 15:59:02] [ERR] Failed to install package glibc -[2025-10-22 15:59:07] [INFO] Glacier started with PID 12345 -[2025-10-22 15:59:07] [ERR] Failed to install package glibc -[2025-10-29 09:19:46] [INFO] Glacier started with PID 12345 -[2025-10-29 09:19:46] [ERR] Failed to install package glibc -[2026-02-04 14:49:07] [INFO] Glacier started with PID 12345 -[2026-02-04 14:49:07] [ERR] Failed to install package glibc -[2026-03-16 13:29:49] [INFO] Glacier started with PID 12345 -[2026-03-16 13:29:49] [ERR] Failed to install package glibc -[2026-04-17 14:31:12] [INFO] Glacier started with PID 12345 -[2026-04-17 14:31:12] [ERR] Failed to install package glibc -[2026-04-17 14:32:30] [INFO] Glacier started with PID 12345 -[2026-04-17 14:32:30] [ERR] Failed to install package glibc -[2026-04-17 14:32:39] [INFO] Glacier started with PID 12345 -[2026-04-17 14:32:39] [ERR] Failed to install package glibc -[2026-04-17 14:32:55] [INFO] Glacier started with PID 12345 -[2026-04-17 14:32:55] [ERR] Failed to install package glibc -[2026-04-17 14:33:04] [INFO] Glacier started with PID 12345 -[2026-04-17 14:33:04] [ERR] Failed to install package glibc diff --git a/src/gpkg.lua b/src/gpkg.lua deleted file mode 100644 index be32747..0000000 --- a/src/gpkg.lua +++ /dev/null @@ -1,70 +0,0 @@ -local gpkg = {} - -function gpkg.parse_manifest(buffer) - local pkg = { - PKG_NAME = nil, - PKG_DESC = nil, - PKG_MAJOR = 0, - PKG_MINOR = 0, - PKG_PAATCH = 0, - PKG_MAINT = nil, - PKG_LICENSE = nil, - PKG_ARCH = nil, - PKG_DEPS = {}, - PKG_CONFLICTS = {}, - } - - for line in buffer:gmatch("[^\r\n]+") do - line = line:match("^%s*(.-)%s*$+"); - if line -= "" and not line:match("^#") then - local key, val = line:match("([^=]+)=(.*)"); - if key and val then - key = key:match("^%s*(.-)%s*$"); - val = val:match("^%s*(.-)%s*$"); - - if key == "PKG_NAME" then pkg.PKG_NAME = val - elseif key == "PKG_DESC" then pkg.PKG_DESC = val - elseif key == "PKG_MAJOR" then pkg.PKG_MAJOR = tonumber(val) or 0 - elseif key == "PKG_MINOR" then pkg.PKG_MINOR = tonumber(val) or 0 - elseif key == "PKG_PATCH" then pkg.PKG_PATCH = tonumber(val) or 0 - elseif key == "PKG_MAINT" then pkg.PKG_MAINT = val - elseif key == "PKG_LICENSE" then pkg.PKG_LICENSE = val - elseif key == "PKG_ARCH" then pkg.PKG_ARCH = val - elseif key == "PKG_DEPS" then - pkg.PKG_DEPS = {} - for dep in val:gmatch("[^,%s]+") do - table.insert(pkg.PKG_DEPS, dep) - end - elseif key == "PKG_CONFLICTS" then - pkg.PKG_CONFLICTS = {} - for c in val:gmatch("[^,%s]+") do - table.insert(pkg.PKG_CONFLICTS, c) - end - end - end - end - end - - return pkg -end - -function gpkg.serialize(pkg) - local out = {} - local function line(k, v) table.insert(out, string.format("%s=%s", k, v or "")) end - - line("PKG_NAME", pkg.PKG_NAME or "") - line("PKG_DESC", pkg.PKG_DESC or "") - line("PKG_MAJOR", pkg.PKG_MAJOR or 0) - line("PKG_MINOR", pkg.PKG_MINOR or 0) - line("PKG_PATCH", pkg.PKG_PATCH or 0) - line("PKG_MAINT", pkg.PKG_MAINT or "") - line("PKG_LICENSE", pkg.PKG_LICENSE or "") - line("PKG_ARCH", pkg.PKG_ARCH or "") - - line("PKG_DEPS", table.concat(pkg.PKG_DEPS or {}, ",")) - line("PKG_CONFLICTS", table.concat(pkg.PKG_CONFLICTS or {}, ",")) - - return table.concat(out, "\n") .. "\n" -end - -return gpkg diff --git a/src/grepo.c b/src/grepo.c index 15edf8c..aed10a5 100644 --- a/src/grepo.c +++ b/src/grepo.c @@ -10,6 +10,10 @@ * NAME-VER.gpkg as the manifest names it. The server is then any static * file host serving DIR. * + * A REPO named X-src is a recipe repository (BUILD_DESIGN.txt section + * 3): DIR holds recipe bundles, NAME-VER.grcp, each read with + * gl_recipe_read; the recipe's REPO must be X. + * * SERIAL (decided 2026-10-06) is the date form YYYYMMDDNN: the larger * of the previous DIR/repo.idx's SERIAL + 1 and today (UTC) * 100 + 1. * -n sets it explicitly; it must still be above the previous one, or @@ -38,6 +42,7 @@ #include "istoreutils.h" #include "log.h" #include "pkg.h" +#include "recipe.h" #include "sha256.h" #include "sign.h" @@ -148,6 +153,89 @@ relation(FILE *f, const char *path, const char *what, const char *name, return 1; } +/* Whether REPO is a recipe repository, "X-src" (X not empty). */ +static int +is_src(const char *repo) +{ + size_t l = strlen(repo); + return l > 4 && strcmp(repo + l - 4, "-src") == 0; +} + +/* gl_recipe_t relation lines ("NAME VER[ IF]\n") as an index list. */ +static void +relation_lines(FILE *f, const char *key, const char *lines) +{ + fprintf(f, "\n\t %s = (", key); + const char *sep = ""; + for (const char *p = lines; *p; p = strchr(p, '\n') + 1) { + /* One line: "NAME VER" or "NAME VER IF", never more. */ + char line[512]; + snprintf(line, sizeof line, "%.*s", (int)(strchr(p, '\n') - p), p); + char *ver = strchr(line, ' '); + *ver++ = '\0'; + char *cond = strchr(ver, ' '); + if (cond) + *cond++ = '\0'; + fprintf(f, "%s { NAME = \"%s\"; VER = \"%s\";", sep, line, ver); + if (cond) + fprintf(f, " IF = \"%s\";", cond); + fprintf(f, " }"); + sep = ","; + } + fprintf(f, "%s);", *sep ? " " : ""); +} + +/* One recipe bundle's PKGS entry (REPO is X-src). */ +static int +write_src_entry(FILE *f, const char *path, const char *file, const char *repo) +{ + gl_recipe_t r; + gl_recipe_status_t st = gl_recipe_read(path, &r); + if (st != GL_RECIPE_OK) { + lg_printf(LG_ERR, "%s is %s: %s.", path, + st == GL_RECIPE_ERR_READ ? "not a readable recipe bundle" : + st == GL_RECIPE_ERR_BUNDLE ? "not a valid recipe bundle" : + "a bundle with a malformed recipe", gl_recipe_error()); + return -1; + } + int rc = -1; + char want[PATH_MAX]; + snprintf(want, sizeof want, "%s-%s.grcp", r.name, r.ver); + if (strlen(r.repo) != strlen(repo) - 4 || strncmp(r.repo, repo, strlen(r.repo)) != 0) { + lg_printf(LG_ERR, "%s builds %s packages, not %.*s.", path, r.repo, + (int)(strlen(repo) - 4), repo); + goto out; + } + if (strcmp(file, want) != 0) { + lg_printf(LG_ERR, "%s must be named %s, as its recipe says.", path, want); + goto out; + } + char sha[72]; + int64_t size; + if (hash_file(path, sha, &size) != 0) { + lg_printf(LG_ERR, "Cannot read %s.", path); + goto out; + } + fprintf(f, "\t{ NAME = \"%s\"; VER = \"%s\"; FILE = \"%s\";\n" + "\t SHA256 = \"%s\"; SIZE = %" PRId64 "L;", r.name, r.ver, file, sha, size); + relation_lines(f, "DEPS", r.deps); + relation_lines(f, "CONFS", r.confs); + relation_lines(f, "BUILD_DEPS", r.build_deps); + fprintf(f, "\n\t TRAITS = ("); + const char *sep = ""; + for (const char *p = r.traits; *p; p = strchr(p, '\n') + 1) { + size_t l = (size_t)(strchr(p, ' ') - p); + fprintf(f, "%s { NAME = \"%.*s\"; DEFAULT = %s; }", sep, (int)l, p, + p[l + 1] == '1' ? "true" : "false"); + sep = ","; + } + fprintf(f, "%s); }", *sep ? " " : ""); + rc = 0; +out: + gl_recipe_free(&r); + return rc; +} + /* One package's PKGS entry, appended to f. 0, or -1 having said why. */ static int write_entry(FILE *f, const char *dir, const char *file, const char *repo) @@ -160,6 +248,8 @@ write_entry(FILE *f, const char *dir, const char *file, const char *repo) lg_printf(LG_ERR, "Refusing %s: not a regular file.", path); return -1; } + if (is_src(repo)) + return write_src_entry(f, path, file, repo); gl_pkg_t pkg = {0}; if (gl_read_pkg_manifest(path, &pkg) != 0) { lg_printf(LG_ERR, "Cannot read the manifest of %s.", path); @@ -323,7 +413,8 @@ main(int argc, char *argv[]) struct dirent *de; while ((de = readdir(d))) { size_t l = strlen(de->d_name); - if (de->d_name[0] == '.' || l < 6 || strcmp(de->d_name + l - 5, ".gpkg") != 0) + if (de->d_name[0] == '.' || l < 6 || + strcmp(de->d_name + l - 5, is_src(repo) ? ".grcp" : ".gpkg") != 0) continue; char **grown = realloc(names, (n + 1) * sizeof *names); if (!grown || !(grown[n] = strdup(de->d_name))) { diff --git a/src/gsandbox.c b/src/gsandbox.c new file mode 100644 index 0000000..8f73ece --- /dev/null +++ b/src/gsandbox.c @@ -0,0 +1,435 @@ +/* + * gsandbox: the build sandbox (BUILD_DESIGN.txt section 6). Run by + * gpkg/syspkg, not by hand; installed beside the libraries. + * + * gsandbox -X [-u USER] -p GPKG -d LAYER + * gsandbox -R [-u USER] -L DIR [-l NAME]... -w WORK -i IN -o OUT + * + * Run as root, -u is required: gsandbox drops to USER (supplementary + * groups, gid, uid) before anything else and refuses a USER whose uid + * is 0. Run as anyone else, there is no -u: it acts as its caller. + * + * -X extracts GPKG's files/ tree into LAYER (created; it must not + * exist), with the rules of an install (gl_extract_files). + * + * -R runs a build. In new user, mount, network, pid, ipc and uts + * namespaces, with the caller mapped to uid/gid 0: an overlay whose + * lower layers are DIR/NAME for each -l (the first on top) over a + * skeleton made in WORK, with WORK/upper as its writable layer; /dev's + * null, zero, full, random, urandom and tty bound in; a fresh /proc; + * IN read-only at /.glacier/in and OUT writable at /.glacier/out; then + * pivot_root into it, no new privileges, a clean environment, and + * /bin/sh /.glacier/in/driver as pid 1. The network namespace has only + * a loopback, down. Everything the build writes outside OUT lands in + * WORK/upper, which the caller deletes. + * + * Exit: -X 0 or 1; -R the driver's status (128 + signal if killed), or + * 125 if the sandbox could not be set up (having said why). + */ + +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "istoreutils.h" +#include "log.h" +#include "pkg.h" + +#define SETUP_FAILED 125 +#define MAX_LAYERS 256 + +#define USAGE \ + "usage: gsandbox [-hv]\n" \ + " gsandbox -X [-u USER] -p GPKG -d LAYER\n" \ + " gsandbox -R [-u USER] -L DIR [-l NAME]... -w WORK -i IN -o OUT\n" + +static const struct option longopts[] = { + { "help", no_argument, NULL, 'h' }, + { "version", no_argument, NULL, 'v' }, + { "extract", no_argument, NULL, 'X' }, + { "run", no_argument, NULL, 'R' }, + { "user", required_argument, NULL, 'u' }, + { "package", required_argument, NULL, 'p' }, + { "dest", required_argument, NULL, 'd' }, + { "layers", required_argument, NULL, 'L' }, + { "layer", required_argument, NULL, 'l' }, + { "work", required_argument, NULL, 'w' }, + { "in", required_argument, NULL, 'i' }, + { "out", required_argument, NULL, 'o' }, + { NULL, 0, NULL, 0 } +}; + +static void +usage(void) +{ + fprintf(stderr, USAGE); +} + +static void +help(void) +{ + printf("gsandbox: Run Glacier package builds in a sandbox\n"); + printf(USAGE); + printf("\n"); + printf("%-25s %s\n", "{-h --help}", "Show this message"); + printf("%-25s %s\n", "{-v --version}", "Show the current version"); + printf("%-25s %s\n", "{-X --extract}", "Extract a package into a build layer"); + printf("%-25s %s\n", "{-R --run}", "Run a build"); + printf("%-25s %s\n", "{-u --user} USER", "Build as USER (required as root)"); + printf("%-25s %s\n", "{-p --package} GPKG", "Package to extract"); + printf("%-25s %s\n", "{-d --dest} LAYER", "Layer directory to create"); + printf("%-25s %s\n", "{-L --layers} DIR", "Directory holding the layers"); + printf("%-25s %s\n", "{-l --layer} NAME", "Add a layer, first on top"); + printf("%-25s %s\n", "{-w --work} WORK", "Work directory"); + printf("%-25s %s\n", "{-i --in} IN", "Build input, read-only"); + printf("%-25s %s\n", "{-o --out} OUT", "Build output"); + printf("\n"); + printf("This program is free software.\n"); + printf("See the GNU GPL version 3 for details.\n"); +} + +/* As root: become USER for good. Elsewhere: USER must not be given. */ +static int +drop_privileges(const char *user) +{ + if (geteuid() != 0) { + if (user) { + lg_printf(LG_ERR, "-u needs root."); + return -1; + } + return 0; + } + if (!user) { + lg_printf(LG_ERR, "Refusing to build as root: -u is required."); + return -1; + } + struct passwd *pw = getpwnam(user); + if (!pw) { + lg_printf(LG_ERR, "No user named %s.", user); + return -1; + } + if (pw->pw_uid == 0 || pw->pw_gid == 0) { + lg_printf(LG_ERR, "Refusing to build as %s: its uid or gid is 0.", user); + return -1; + } + if (setgroups(0, NULL) != 0 || setgid(pw->pw_gid) != 0 || + setuid(pw->pw_uid) != 0) { + lg_printf(LG_ERR, "Cannot become %s: %s", user, strerror(errno)); + return -1; + } + if (setuid(0) == 0 || geteuid() == 0 || getegid() == 0) { + lg_printf(LG_ERR, "Cannot drop root."); + return -1; + } + /* Changing uid made the process non-dumpable, which leaves + * /proc/self owned by root: it could not write its own uid_map. + * Nothing of root's is left in it to protect. */ + if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) != 0) { + lg_printf(LG_ERR, "Cannot drop root."); + return -1; + } + return 0; +} + +static int +write_file(const char *path, const char *text) +{ + int fd = open(path, O_WRONLY | O_CLOEXEC); + if (fd < 0) + return -1; + ssize_t n = write(fd, text, strlen(text)); + int rc = (n == (ssize_t)strlen(text)) ? 0 : -1; + close(fd); + return rc; +} + +static int +make_file(const char *path, const char *text, mode_t mode) +{ + int fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode); + if (fd < 0) + return -1; + ssize_t n = write(fd, text, strlen(text)); + int rc = (n == (ssize_t)strlen(text) && fchmod(fd, mode) == 0) ? 0 : -1; + close(fd); + return rc; +} + +/* The lowest layer: the merged-/usr links gl_create_fs_tree makes, the + * mount points, a root user and the build directory. */ +static int +make_skeleton(const char *skel) +{ + static const char *const dirs[] = { "", "usr", "usr/bin", "usr/lib", + "etc", "dev", "proc", "tmp", "build", ".glacier", ".glacier/in", + ".glacier/out", NULL }; + static const char *const links[][2] = { { "bin", "usr/bin" }, + { "sbin", "usr/bin" }, { "lib", "usr/lib" }, { "usr/sbin", "bin" } }; + char p[PATH_MAX]; + for (size_t i = 0; dirs[i]; i++) { + snprintf(p, sizeof p, "%s/%s", skel, dirs[i]); + if (mkdir(p, 0755) != 0 || chmod(p, 0755) != 0) + return -1; + } + snprintf(p, sizeof p, "%s/tmp", skel); + if (chmod(p, 01777) != 0) + return -1; + for (size_t i = 0; i < sizeof links / sizeof *links; i++) { + snprintf(p, sizeof p, "%s/%s", skel, links[i][0]); + if (symlink(links[i][1], p) != 0) + return -1; + } + snprintf(p, sizeof p, "%s/etc/passwd", skel); + if (make_file(p, "root:x:0:0:root:/tmp:/bin/sh\n", 0644) != 0) + return -1; + snprintf(p, sizeof p, "%s/etc/group", skel); + return make_file(p, "root:x:0:\n", 0644); +} + +/* A path that can go into overlayfs's option string as is. */ +static bool +plain_path(const char *s) +{ + return *s == '/' && !strpbrk(s, ",:\\") && strlen(s) < 1024; +} + +static int +bind_dir(const char *src, const char *dst, bool ro) +{ + if (mount(src, dst, NULL, MS_BIND | MS_REC, NULL) != 0) + return -1; + unsigned long fl = MS_BIND | MS_REMOUNT | MS_NOSUID | MS_NODEV | (ro ? MS_RDONLY : 0); + return mount(NULL, dst, NULL, fl, NULL); +} + +#define FAIL(...) do { lg_printf(LG_ERR, __VA_ARGS__); _exit(SETUP_FAILED); } while (0) + +/* Pid 1 of the new namespaces: mount the root, enter it, run the driver. */ +static void +child(const char *ldir, char **layers, size_t nlayers, const char *work, + const char *in, const char *out) +{ + char skel[PATH_MAX], upper[PATH_MAX], ovl[PATH_MAX], root[PATH_MAX]; + snprintf(skel, sizeof skel, "%s/skel", work); + snprintf(upper, sizeof upper, "%s/upper", work); + snprintf(ovl, sizeof ovl, "%s/ovl", work); + snprintf(root, sizeof root, "%s/root", work); + + if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) != 0) + FAIL("Cannot make the mounts private: %s", strerror(errno)); + + /* Layer names relative to DIR keep the option string short. */ + if (chdir(ldir) != 0) + FAIL("Cannot enter %s: %s", ldir, strerror(errno)); + size_t cap = 3 * PATH_MAX + 64, used = 0; + for (size_t i = 0; i < nlayers; i++) + cap += strlen(layers[i]) + 1; + char *opts = malloc(cap); + if (!opts) + FAIL("Out of memory."); + used += (size_t)snprintf(opts, cap, "lowerdir="); + for (size_t i = 0; i < nlayers; i++) + used += (size_t)snprintf(opts + used, cap - used, "%s:", layers[i]); + /* userxattr: inside a user namespace overlayfs can't set its + * trusted.* xattrs, so without it a directory removed and made + * again in the build root would show the layer's old contents + * (no opaque marker). Kernels before 5.11 don't know the option. */ + used += (size_t)snprintf(opts + used, cap - used, + "%s,upperdir=%s,workdir=%s", skel, upper, ovl); + snprintf(opts + used, cap - used, ",userxattr"); + if (mount("overlay", root, "overlay", MS_NOSUID | MS_NODEV, opts) != 0) { + opts[used] = '\0'; + if (errno != EINVAL || + mount("overlay", root, "overlay", MS_NOSUID | MS_NODEV, opts) != 0) + FAIL("Cannot mount the build root: %s", strerror(errno)); + } + free(opts); + + static const char *const devs[] = { "null", "zero", "full", "random", + "urandom", "tty", NULL }; + char p[PATH_MAX], h[PATH_MAX]; + for (size_t i = 0; devs[i]; i++) { + snprintf(h, sizeof h, "/dev/%s", devs[i]); + if (access(h, F_OK) != 0) + continue; + snprintf(p, sizeof p, "%s/dev/%s", root, devs[i]); + int fd = open(p, O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0666); + if (fd < 0) + FAIL("Cannot create %s: %s", p, strerror(errno)); + close(fd); + if (mount(h, p, NULL, MS_BIND, NULL) != 0) + FAIL("Cannot bind %s: %s", h, strerror(errno)); + } + snprintf(p, sizeof p, "%s/proc", root); + if (mount("proc", p, "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC, NULL) != 0) + FAIL("Cannot mount /proc: %s", strerror(errno)); + snprintf(p, sizeof p, "%s/.glacier/in", root); + if (bind_dir(in, p, true) != 0) + FAIL("Cannot bind %s: %s", in, strerror(errno)); + snprintf(p, sizeof p, "%s/.glacier/out", root); + if (bind_dir(out, p, false) != 0) + FAIL("Cannot bind %s: %s", out, strerror(errno)); + + if (chdir(root) != 0 || syscall(SYS_pivot_root, ".", ".") != 0 || + umount2(".", MNT_DETACH) != 0 || chdir("/") != 0) + FAIL("Cannot enter the build root: %s", strerror(errno)); + if (sethostname("glacier-build", 13) != 0 || + prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) + FAIL("Cannot set up the build: %s", strerror(errno)); + + for (int fd = 3; fd < 1024; fd++) + close(fd); + char *const argv[] = { "/bin/sh", "/.glacier/in/driver", NULL }; + char *const envp[] = { "PATH=/usr/bin:/bin", "HOME=/tmp", "LC_ALL=C", + "TZ=UTC", "TERM=dumb", "FORCE_UNSAFE_CONFIGURE=1", NULL }; + execve(argv[0], argv, envp); + FAIL("Cannot run the build driver: %s", strerror(errno)); +} + +static int +run(const char *ldir, char **layers, size_t nlayers, const char *work, + const char *in, const char *out) +{ + if (!plain_path(work) || !plain_path(ldir) || !plain_path(in) || !plain_path(out)) { + lg_printf(LG_ERR, "Refusing a path that is not absolute or holds ',', ':' or '\\'."); + return SETUP_FAILED; + } + for (size_t i = 0; i < nlayers; i++) { + if (!gl_valid_pkg_ident(layers[i])) { + lg_printf(LG_ERR, "Refusing layer name %s.", layers[i]); + return SETUP_FAILED; + } + } + char p[PATH_MAX]; + const char *subdirs[] = { "upper", "ovl", "root" }; + for (size_t i = 0; i < 3; i++) { + snprintf(p, sizeof p, "%s/%s", work, subdirs[i]); + if (mkdir(p, 0700) != 0) { + lg_printf(LG_ERR, "Cannot create %s: %s", p, strerror(errno)); + return SETUP_FAILED; + } + } + snprintf(p, sizeof p, "%s/skel", work); + if (make_skeleton(p) != 0) { + lg_printf(LG_ERR, "Cannot create %s: %s", p, strerror(errno)); + return SETUP_FAILED; + } + + uid_t uid = getuid(); + gid_t gid = getgid(); + if (unshare(CLONE_NEWUSER | CLONE_NEWNS | CLONE_NEWNET | CLONE_NEWPID | + CLONE_NEWIPC | CLONE_NEWUTS) != 0) { + lg_printf(LG_ERR, "Builds need unprivileged user namespaces."); + return SETUP_FAILED; + } + char map[64]; + snprintf(map, sizeof map, "0 %u 1\n", (unsigned)uid); + if (write_file("/proc/self/setgroups", "deny") != 0 || + write_file("/proc/self/uid_map", map) != 0) { + lg_printf(LG_ERR, "Cannot map the build user: %s", strerror(errno)); + return SETUP_FAILED; + } + snprintf(map, sizeof map, "0 %u 1\n", (unsigned)gid); + if (write_file("/proc/self/gid_map", map) != 0) { + lg_printf(LG_ERR, "Cannot map the build group: %s", strerror(errno)); + return SETUP_FAILED; + } + + pid_t pid = fork(); + if (pid < 0) { + lg_printf(LG_ERR, "Cannot start the build: %s", strerror(errno)); + return SETUP_FAILED; + } + if (pid == 0) + child(ldir, layers, nlayers, work, in, out); + + int status; + while (waitpid(pid, &status, 0) < 0) { + if (errno != EINTR) + return SETUP_FAILED; + } + if (WIFSIGNALED(status)) + return 128 + WTERMSIG(status); + return WEXITSTATUS(status); +} + +int +main(int argc, char *argv[]) +{ + const char *user = NULL, *pkg = NULL, *dest = NULL, *ldir = NULL; + const char *work = NULL, *in = NULL, *out = NULL; + char *layers[MAX_LAYERS]; + size_t nlayers = 0; + int mode = 0, c; + + while ((c = getopt_long(argc, argv, "hvXRu:p:d:L:l:w:i:o:", longopts, NULL)) != -1) { + switch (c) { + case 'h': + help(); + return 0; + case 'v': + printf("v4.0.0\n"); + return 0; + case 'X': + case 'R': + if (mode && mode != c) { + usage(); + return 1; + } + mode = c; + break; + case 'u': user = optarg; break; + case 'p': pkg = optarg; break; + case 'd': dest = optarg; break; + case 'L': ldir = optarg; break; + case 'l': + if (nlayers == MAX_LAYERS) { + lg_printf(LG_ERR, "At most %d layers.", MAX_LAYERS); + return 1; + } + layers[nlayers++] = optarg; + break; + case 'w': work = optarg; break; + case 'i': in = optarg; break; + case 'o': out = optarg; break; + default: + usage(); + return 1; + } + } + if (optind != argc || (mode == 'X' && (!pkg || !dest || ldir || nlayers || work || in || out)) || + (mode == 'R' && (!ldir || !work || !in || !out || pkg || dest)) || !mode) { + usage(); + return 1; + } + + if (drop_privileges(user) != 0) + return mode == 'R' ? SETUP_FAILED : 1; + + if (mode == 'X') { + gl_install_status_t st = gl_extract_files(pkg, dest); + if (st != GL_INSTALL_OK) { + lg_printf(LG_ERR, "Cannot extract %s into %s.", pkg, dest); + return 1; + } + return 0; + } + return run(ldir, layers, nlayers, work, in, out); +} diff --git a/src/istoreutils.c b/src/istoreutils.c index 6ea20bc..c0bd874 100644 --- a/src/istoreutils.c +++ b/src/istoreutils.c @@ -214,13 +214,14 @@ gl_init_user(uid_t uid, bool isVerbose) * the next `gstore -n` would refuse as "already exists". mkdir() is * subject to umask, so chmod explicitly: gl_usr_base_check insists * on no group/other bits. */ - const char *subdirs[] = { "index", "store", "links" }; + /* config: the user's build settings (BUILD_DESIGN.txt section 5). */ + const char *subdirs[] = { "index", "store", "links", "config" }; char sub[PATH_MAX]; char ind_path[PATH_MAX]; snprintf(ind_path, sizeof(ind_path), "%s/index", base); if (chmod(base, 0700) != 0) { goto fail; } - for (int i = 0; i < 3; i++) { + for (int i = 0; i < 4; i++) { snprintf(sub, sizeof(sub), "%s/%s", base, subdirs[i]); if (isVerbose) { lg_printf(0, "Creating %s", sub); } if (mkdir(sub, 0700) != 0 || chown(sub, uid, (gid_t)-1) != 0) { @@ -767,6 +768,71 @@ gl_set_pkg_auto(gl_context_t *ctx, const char *repo, const char *name, bool auto return gl_rebuild_index(ctx) == 0 ? 0 : -1; } +/* + * gl_set_pkg_src + * DESCRIPTION: records that the installed repo/name was built from the + * recipe repository src_repo (BUILD_DESIGN.txt section 8): the + * marker GL_SRC_MARKER in its version dir holds "SRC_REPO\n". + * -u then rebuilds it from there. Reinstalling the package + * from a binary drops it (a fresh version dir). + * RETURNS: 0, or -1 if the package isn't installed, src_repo isn't a + * valid name, or the marker can't be written + */ +int +gl_set_pkg_src(gl_context_t *ctx, const char *repo, const char *name, const char *src_repo) +{ + if (!ctx || !gl_valid_pkg_ident(repo) || !gl_valid_pkg_ident(name) || + !gl_valid_pkg_ident(src_repo)) { + return -1; + } + char vdir[PATH_MAX], dirname[NAME_MAX + 1], marker[PATH_MAX]; + if (find_version_dir(ctx->store_path, repo, name, vdir, sizeof(vdir), + dirname, sizeof(dirname)) != 0) { + return -1; + } + snprintf(marker, sizeof(marker), "%s/" GL_SRC_MARKER, vdir); + int fd = open(marker, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, + gl_scope_file_mode(ctx->scope)); + if (fd < 0) { return -1; } + size_t len = strlen(src_repo); + bool ok = fchmod(fd, gl_scope_file_mode(ctx->scope)) == 0 && + write(fd, src_repo, len) == (ssize_t)len && write(fd, "\n", 1) == 1; + close(fd); + return ok ? 0 : -1; +} + +/* + * gl_pkg_src + * DESCRIPTION: the recipe repository the installed repo/name was built + * from (gl_set_pkg_src), into out (len bytes). + * RETURNS: 1 with out set; 0 if it was not built from source (no + * marker); -1 if it isn't installed or the marker is unreadable or + * malformed + */ +int +gl_pkg_src(gl_context_t *ctx, const char *repo, const char *name, char *out, size_t len) +{ + if (!ctx || !out || len == 0 || !gl_valid_pkg_ident(repo) || !gl_valid_pkg_ident(name)) { + return -1; + } + char vdir[PATH_MAX], dirname[NAME_MAX + 1], marker[PATH_MAX]; + if (find_version_dir(ctx->store_path, repo, name, vdir, sizeof(vdir), + dirname, sizeof(dirname)) != 0) { + return -1; + } + snprintf(marker, sizeof(marker), "%s/" GL_SRC_MARKER, vdir); + int fd = open(marker, O_RDONLY | O_NOFOLLOW); + if (fd < 0) { return errno == ENOENT ? 0 : -1; } + char buf[NAME_MAX + 2]; + ssize_t n = read(fd, buf, sizeof(buf) - 1); + close(fd); + if (n < 2 || buf[n - 1] != '\n') { return -1; } + buf[n - 1] = '\0'; + if (!gl_valid_pkg_ident(buf) || strlen(buf) >= len) { return -1; } + snprintf(out, len, "%s", buf); + return 1; +} + /* * Archive the installed version of repo/name back into a .gpkg at * out_path (same layout gl_install_pkg reads: NAME-VER/manifest.gpm.cfg @@ -1848,6 +1914,259 @@ gl_read_pkg_manifest(const char *gpkg_path, gl_pkg_t *pkg) return GL_INSTALL_OK; } +/* + * Extract an open package archive's strip_prefix entries + * ("NAME-VER/files/") into the existing directory dest, with every rule + * package extraction has (see the comments inside): no "..", no + * absolute paths, no reserved .glacier-* names, never writing through a + * symlink, symlinks last, hardlinks refused, devices/fifos skipped, modes + * GL_ENTRY_MODE. manifest_entry, if not NULL, is copied to + * dest/GL_MANIFEST_COPY. What it made in dest is left for the caller to + * remove on failure. + */ +static gl_install_status_t +extract_tree(struct archive *a, const char *dest, const char *strip_prefix, + const char *manifest_entry, mode_t dir_mode) +{ + struct archive_entry *entry; + + /* Symlink entries are collected here and only created once every + * directory and regular file is in place. While regular content is + * being written the package dir therefore contains no symlinks at + * all, so no entry can be written *through* one — the classic + * symlink tar-slip, where `x -> /etc` followed by `x/passwd` writes + * the real /etc/passwd, as root under syspkg. crosses_symlink() and + * O_NOFOLLOW below are the second line of defense, and also cover + * a deferred symlink whose parent is another deferred symlink. */ + struct deferred_link { char *dest; char *target; } *links = NULL; + size_t nlinks = 0; + gl_install_status_t ret = GL_INSTALL_ERR_EXTRACT; + + while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { + const char *entry_path = archive_entry_pathname(entry); + + /* Keep the manifest beside the files (GL_MANIFEST_COPY). */ + if (manifest_entry && strcmp(entry_path, manifest_entry) == 0 && + archive_entry_filetype(entry) == AE_IFREG) { + char mpath[PATH_MAX]; + snprintf(mpath, sizeof(mpath), "%s/" GL_MANIFEST_COPY, dest); + int mfd = open(mpath, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644); + if (mfd < 0) { goto extract_fail; } + char buffer[8192]; + ssize_t n; + while ((n = archive_read_data(a, buffer, sizeof(buffer))) > 0) { + if (write(mfd, buffer, (size_t)n) != n) { + close(mfd); + goto extract_fail; + } + } + close(mfd); + continue; + } + + if (strncmp(entry_path, strip_prefix, strlen(strip_prefix)) != 0) { + archive_read_data_skip(a); + continue; + } + + const char *rel_path = entry_path + strlen(strip_prefix); + if (rel_path[0] == '\0') { + archive_read_data_skip(a); + continue; + } + + /* Refuse the whole package rather than skip the entry: an + * archive carrying a traversal path is hostile or broken, and + * installing the rest of it would be a partial install of + * something we've already stopped trusting. */ + if (!is_safe_rel_path(rel_path)) { + lg_printf(2, "Refusing unsafe archive entry path '%s'.", + entry_path); + goto extract_fail; + } + + /* A hardlink entry has no content of its own: skipping it + * silently dropped files packages ship (binutils' ld is a + * hardlink to ld.bfd). Packers store hardlinks as plain files + * (gbuild, build-driver.sh); a package that has one anyway is + * refused, never installed with files missing. */ + if (archive_entry_hardlink(entry)) { + lg_printf(2, "Refusing archive entry '%s': it is a hardlink.", + entry_path); + goto extract_fail; + } + + /* Top-level .glacier-* names are glacier's own files in the + * version dir (GL_MARKER_PREFIX). A package shipping one could + * grant itself -O, rewrite its saved manifest, or, as a + * symlink, redirect glacier's marker write (as root, under + * syspkg) to any file on the system. */ + if (strncmp(rel_path, GL_MARKER_PREFIX, strlen(GL_MARKER_PREFIX)) == 0) { + lg_printf(2, "Refusing archive entry '%s': %s* names are reserved.", + entry_path, GL_MARKER_PREFIX); + goto extract_fail; + } + + char dest_path[PATH_MAX]; + snprintf(dest_path, sizeof(dest_path), "%s/%s", + dest, rel_path); + + if (crosses_symlink(dest, dest_path)) { + lg_printf(2, "Refusing archive entry '%s': a parent directory is a symlink.", + entry_path); + goto extract_fail; + } + + switch (archive_entry_filetype(entry)) { + case AE_IFDIR: + if (gl_mkdir_exact(dest_path, GL_ENTRY_MODE(entry)) != 0) { + goto extract_fail; + } + break; + + case AE_IFREG: { + char parent[PATH_MAX]; + snprintf(parent, sizeof(parent), "%s", dest_path); + char *slash = strrchr(parent, '/'); + if (slash) { + *slash = '\0'; + gl_mkdirp(parent, dir_mode); + } + + int fd = open(dest_path, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, + GL_ENTRY_MODE(entry)); + if (fd < 0) { goto extract_fail; } + if (fchmod(fd, GL_ENTRY_MODE(entry)) != 0) { + close(fd); + goto extract_fail; + } + + char buffer[8192]; + ssize_t n; + while ((n = archive_read_data(a, buffer, sizeof(buffer))) > 0) { + ssize_t written = write(fd, buffer, (size_t)n); + if (written < 0 || written != n) { + close(fd); + goto extract_fail; + } + } + + close(fd); + break; + } + + case AE_IFLNK: { + /* The target is stored verbatim and means what it says + * at RUNTIME: musl's lib/ld-musl-x86_64.so.1 -> + * /usr/lib/libc.so resolves against the running system, + * not the store. Nothing glacier does afterwards writes + * through a store symlink (removal and seeding lstat()). */ + const char *target = archive_entry_symlink(entry); + if (!target || target[0] == '\0') { + lg_printf(2, "Refusing archive entry '%s': symlink with no target.", + entry_path); + goto extract_fail; + } + + struct deferred_link *grown = realloc(links, + (nlinks + 1) * sizeof(*links)); + if (!grown) { goto extract_fail; } + links = grown; + links[nlinks].dest = strdup(dest_path); + links[nlinks].target = strdup(target); + nlinks++; + if (!links[nlinks - 1].dest || !links[nlinks - 1].target) { + goto extract_fail; + } + break; + } + + default: + /* Devices, fifos: nothing a package needs, and nothing + * worth trusting an archive to create. Skipped. (Hardlinks + * are refused above.) */ + archive_read_data_skip(a); + break; + } + } + + for (size_t i = 0; i < nlinks; i++) { + if (crosses_symlink(dest, links[i].dest)) { + lg_printf(2, "Refusing symlink '%s': a parent directory is a symlink.", + links[i].dest); + goto extract_fail; + } + + char parent[PATH_MAX]; + snprintf(parent, sizeof(parent), "%s", links[i].dest); + char *slash = strrchr(parent, '/'); + if (slash) { + *slash = '\0'; + gl_mkdirp(parent, dir_mode); + } + + /* symlink() fails EEXIST rather than replacing: an archive that + * ships both a file/dir and a symlink at one path is refused. */ + if (symlink(links[i].target, links[i].dest) != 0) { + lg_printf(2, "Cannot create symlink %s: %s", links[i].dest, strerror(errno)); + goto extract_fail; + } + } + + ret = GL_INSTALL_OK; + +extract_fail: + for (size_t i = 0; i < nlinks; i++) { + free(links[i].dest); + free(links[i].target); + } + free(links); + + return ret; +} + +/* + * gl_extract_files + * DESCRIPTION: extracts a package's files/ tree into dest, a directory + * this call creates (0755; it must not exist yet), with every + * rule an install has (extract_tree). For build layers + * (BUILD_DESIGN.txt section 6): nothing is installed, linked or + * indexed. On failure, dest is removed. + * RETURNS: GL_INSTALL_OK, GL_INSTALL_ERR_OPEN, GL_INSTALL_ERR_MANIFEST + * or GL_INSTALL_ERR_EXTRACT (including dest existing) + */ +gl_install_status_t +gl_extract_files(const char *gpkg_path, const char *dest) +{ + gl_pkg_t pkg = {0}; + int mrc = gl_read_pkg_manifest(gpkg_path, &pkg); + if (mrc != GL_INSTALL_OK) { + return (gl_install_status_t)mrc; + } + + char strip_prefix[PATH_MAX]; + snprintf(strip_prefix, sizeof(strip_prefix), "%s-%d.%d.%d/files/", pkg.pkg_name, + pkg.pkg_ver.maj, pkg.pkg_ver.min, pkg.pkg_ver.pat); + gl_free_pkg(&pkg); + + if (mkdir(dest, 0755) != 0) { + return GL_INSTALL_ERR_EXTRACT; + } + gl_install_status_t ret = GL_INSTALL_ERR_EXTRACT; + struct archive *a = archive_read_new(); + archive_read_support_filter_gzip(a); + archive_read_support_format_tar(a); + if (chmod(dest, 0755) == 0 && + archive_read_open_filename(a, gpkg_path, 10240) == ARCHIVE_OK) { + ret = extract_tree(a, dest, strip_prefix, NULL, 0755); + } + archive_read_free(a); + if (ret != GL_INSTALL_OK) { + gl_rmdir_recursive(dest); + } + return ret; +} + gl_install_status_t gl_install_pkg(gl_context_t *ctx, const char *gpkg_path) { @@ -1931,7 +2250,6 @@ gl_install_pkg(gl_context_t *ctx, const char *gpkg_path) } /* now the archive must be reopened in order to extract package files */ - struct archive_entry *entry; struct archive *a2 = archive_read_new(); archive_read_support_filter_gzip(a2); archive_read_support_format_tar(a2); @@ -1947,193 +2265,14 @@ gl_install_pkg(gl_context_t *ctx, const char *gpkg_path) "%s-%d.%d.%d/files/", pkg.pkg_name, pkg.pkg_ver.maj, pkg.pkg_ver.min, pkg.pkg_ver.pat); - /* Symlink entries are collected here and only created once every - * directory and regular file is in place. While regular content is - * being written the package dir therefore contains no symlinks at - * all, so no entry can be written *through* one — the classic - * symlink tar-slip, where `x -> /etc` followed by `x/passwd` writes - * the real /etc/passwd, as root under syspkg. crosses_symlink() and - * O_NOFOLLOW below are the second line of defense, and also cover - * a deferred symlink whose parent is another deferred symlink. */ - struct deferred_link { char *dest; char *target; } *links = NULL; - size_t nlinks = 0; - gl_install_status_t ret = GL_INSTALL_ERR_EXTRACT; - char manifest_entry[PATH_MAX]; snprintf(manifest_entry, sizeof(manifest_entry), "%s-%d.%d.%d/manifest.gpm.cfg", pkg.pkg_name, pkg.pkg_ver.maj, pkg.pkg_ver.min, pkg.pkg_ver.pat); - while (archive_read_next_header(a2, &entry) == ARCHIVE_OK) { - const char *entry_path = archive_entry_pathname(entry); - - /* Keep the manifest beside the files (GL_MANIFEST_COPY). */ - if (strcmp(entry_path, manifest_entry) == 0 && - archive_entry_filetype(entry) == AE_IFREG) { - char mpath[PATH_MAX]; - snprintf(mpath, sizeof(mpath), "%s/" GL_MANIFEST_COPY, pkg_store_final); - int mfd = open(mpath, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644); - if (mfd < 0) { goto extract_fail; } - char buffer[8192]; - ssize_t n; - while ((n = archive_read_data(a2, buffer, sizeof(buffer))) > 0) { - if (write(mfd, buffer, (size_t)n) != n) { - close(mfd); - goto extract_fail; - } - } - close(mfd); - continue; - } - - if (strncmp(entry_path, strip_prefix, strlen(strip_prefix)) != 0) { - archive_read_data_skip(a2); - continue; - } - - const char *rel_path = entry_path + strlen(strip_prefix); - if (rel_path[0] == '\0') { - archive_read_data_skip(a2); - continue; - } - - /* Refuse the whole package rather than skip the entry: an - * archive carrying a traversal path is hostile or broken, and - * installing the rest of it would be a partial install of - * something we've already stopped trusting. */ - if (!is_safe_rel_path(rel_path)) { - lg_printf(2, "Refusing unsafe archive entry path '%s'.", - entry_path); - goto extract_fail; - } - - /* Top-level .glacier-* names are glacier's own files in the - * version dir (GL_MARKER_PREFIX). A package shipping one could - * grant itself -O, rewrite its saved manifest, or, as a - * symlink, redirect glacier's marker write (as root, under - * syspkg) to any file on the system. */ - if (strncmp(rel_path, GL_MARKER_PREFIX, strlen(GL_MARKER_PREFIX)) == 0) { - lg_printf(2, "Refusing archive entry '%s': %s* names are reserved.", - entry_path, GL_MARKER_PREFIX); - goto extract_fail; - } - - char dest_path[PATH_MAX]; - snprintf(dest_path, sizeof(dest_path), "%s/%s", - pkg_store_final, rel_path); - - if (crosses_symlink(pkg_store_final, dest_path)) { - lg_printf(2, "Refusing archive entry '%s': a parent directory is a symlink.", - entry_path); - goto extract_fail; - } - - switch (archive_entry_filetype(entry)) { - case AE_IFDIR: - if (gl_mkdir_exact(dest_path, GL_ENTRY_MODE(entry)) != 0) { - goto extract_fail; - } - break; - - case AE_IFREG: { - char parent[PATH_MAX]; - snprintf(parent, sizeof(parent), "%s", dest_path); - char *slash = strrchr(parent, '/'); - if (slash) { - *slash = '\0'; - gl_mkdirp(parent, dir_mode); - } - - int fd = open(dest_path, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, - GL_ENTRY_MODE(entry)); - if (fd < 0) { goto extract_fail; } - if (fchmod(fd, GL_ENTRY_MODE(entry)) != 0) { - close(fd); - goto extract_fail; - } - - char buffer[8192]; - ssize_t n; - while ((n = archive_read_data(a2, buffer, sizeof(buffer))) > 0) { - ssize_t written = write(fd, buffer, (size_t)n); - if (written < 0 || written != n) { - close(fd); - goto extract_fail; - } - } - - close(fd); - break; - } - - case AE_IFLNK: { - /* The target is stored verbatim and means what it says - * at RUNTIME: musl's lib/ld-musl-x86_64.so.1 -> - * /usr/lib/libc.so resolves against the running system, - * not the store. Nothing glacier does afterwards writes - * through a store symlink (removal and seeding lstat()). */ - const char *target = archive_entry_symlink(entry); - if (!target || target[0] == '\0') { - lg_printf(2, "Refusing archive entry '%s': symlink with no target.", - entry_path); - goto extract_fail; - } - - struct deferred_link *grown = realloc(links, - (nlinks + 1) * sizeof(*links)); - if (!grown) { goto extract_fail; } - links = grown; - links[nlinks].dest = strdup(dest_path); - links[nlinks].target = strdup(target); - nlinks++; - if (!links[nlinks - 1].dest || !links[nlinks - 1].target) { - goto extract_fail; - } - break; - } - - default: - /* Hardlinks, devices, fifos: nothing a package needs, and - * nothing worth trusting an archive to create. Skipped, - * same as before symlinks were supported. */ - archive_read_data_skip(a2); - break; - } - } - - for (size_t i = 0; i < nlinks; i++) { - if (crosses_symlink(pkg_store_final, links[i].dest)) { - lg_printf(2, "Refusing symlink '%s': a parent directory is a symlink.", - links[i].dest); - goto extract_fail; - } - - char parent[PATH_MAX]; - snprintf(parent, sizeof(parent), "%s", links[i].dest); - char *slash = strrchr(parent, '/'); - if (slash) { - *slash = '\0'; - gl_mkdirp(parent, dir_mode); - } - - /* symlink() fails EEXIST rather than replacing: an archive that - * ships both a file/dir and a symlink at one path is refused. */ - if (symlink(links[i].target, links[i].dest) != 0) { - lg_printf(2, "Cannot create symlink %s: %s", links[i].dest, strerror(errno)); - goto extract_fail; - } - } - - ret = GL_INSTALL_OK; - -extract_fail: - for (size_t i = 0; i < nlinks; i++) { - free(links[i].dest); - free(links[i].target); - } - free(links); - + gl_install_status_t ret = extract_tree(a2, pkg_store_final, strip_prefix, + manifest_entry, dir_mode); + archive_read_free(a2); if (ret != GL_INSTALL_OK) { - archive_read_free(a2); /* Remove the half-extracted version dir (created by this call, * just above). Left behind, it made the next attempt report * GL_INSTALL_ERR_ALREADY_INSTALLED — harmless in a stage that's @@ -2142,7 +2281,6 @@ extract_fail: gl_free_pkg(&pkg); return ret; } - archive_read_free(a2); /* now the index will be updated */ /* Resolve "current" symlink to confirm an index exists to rebuild diff --git a/src/istoreutils.h b/src/istoreutils.h index dc878dc..123a5b3 100644 --- a/src/istoreutils.h +++ b/src/istoreutils.h @@ -70,6 +70,7 @@ int gl_create_fs_tree(const char *root, bool isVerbose); int gl_delete_user(uid_t uid, bool isVerbose); int gl_rebuild_index(gl_context_t *ctx); +gl_install_status_t gl_extract_files(const char *gpkg_path, const char *dest); typedef struct { char **repos; @@ -86,6 +87,8 @@ gl_backup_status_t gl_backup_istore(const char *tar_path, const char *glacier_ro int gl_read_pkg_manifest(const char *gpkg_path, gl_pkg_t *pkg); gl_install_status_t gl_install_pkg(gl_context_t *ctx, const char *gpkg_path); int gl_set_pkg_auto(gl_context_t *ctx, const char *repo, const char *name, bool automatic); +int gl_set_pkg_src(gl_context_t *ctx, const char *repo, const char *name, const char *src_repo); +int gl_pkg_src(gl_context_t *ctx, const char *repo, const char *name, char *out, size_t len); gl_remove_status_t gl_remove_pkg(gl_context_t *ctx, const char *pkg_name, const char *pkg_repo); int gl_relink_store(gl_context_t *ctx); diff --git a/src/log.c b/src/log.c index 9498327..61d0609 100644 --- a/src/log.c +++ b/src/log.c @@ -67,7 +67,7 @@ lg_gpkg_help(int argc, char *argv[]) (void)argc; printf("%s: Install, update, and remove packages\n", argv[0]); - printf("usage: %s [-hv] [-y] [-flux PKG] [-OSV]\n", argv[0]); + printf("usage: %s [-hv] [-y] [-flux PKG] [-OSVq]\n", argv[0]); printf("\n"); printf("%-25s %s\n", "{-h --help}", "Show this message"); printf("%-25s %s\n", "{-v --version}", "Show the current version"); @@ -79,6 +79,7 @@ lg_gpkg_help(int argc, char *argv[]) printf("%-25s %s\n", "{-O --overwrite}", "Allow Glacier to overwrite existing files"); printf("%-25s %s\n", "{-S --skip-installed}", "Skip packages that are already up to date"); printf("%-25s %s\n", "{-V --verbose}", "Log events more verbosely"); + printf("%-25s %s\n", "{-q --quiet}", "Hide build output"); printf("\n"); printf("This program is free software.\n"); printf("See the GNU GPL version 3 for details.\n"); @@ -90,7 +91,7 @@ lg_syspkg_help(int argc, char *argv[]) (void)argc; printf("%s: Manage the system package index\n", argv[0]); - printf("usage: %s [-hv] [-n] [-y] [-flux PKG] [-OSV] [-R DIR] [--strict]\n", argv[0]); + printf("usage: %s [-hv] [-n] [-y] [-flux PKG] [-OSVq] [-R DIR] [--strict]\n", argv[0]); printf("\n"); printf("%-25s %s\n", "{-h --help}", "Show this message"); printf("%-25s %s\n", "{-v --version}", "Show the current version"); @@ -103,6 +104,7 @@ lg_syspkg_help(int argc, char *argv[]) printf("%-25s %s\n", "{-O --overwrite}", "Allow Glacier to overwrite existing files"); printf("%-25s %s\n", "{-S --skip-installed}", "Skip packages that are already up to date"); printf("%-25s %s\n", "{-V --verbose}", "Log events more verbosely"); + printf("%-25s %s\n", "{-q --quiet}", "Hide build output"); printf("%-25s %s\n", "{-R --root} DIR", "Operate on the system installed under DIR (implies --strict)"); printf("%-25s %s\n", "{--strict}", "Refuse the whole transaction if any path can't be linked"); printf("\n"); diff --git a/src/pkg.c b/src/pkg.c index f5c487c..3461265 100644 --- a/src/pkg.c +++ b/src/pkg.c @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -14,6 +15,7 @@ #include "common.h" #include "pkg.h" +#include "recipe.h" /* "MAJ.MIN.PAT[-TAG]". Each number is read with strtol and clamped to * 0..INT_MAX (a manifest is untrusted: sscanf's %d overflowing is @@ -85,6 +87,17 @@ gl_valid_pkg_ident(const char *s) /* A manifest comes out of an untrusted archive. libconfig honours * `@include "FILE"` at the start of a line, which would have it read any * file (as root, under syspkg): such a manifest is refused. */ +static bool +has_include(const char *buf) +{ + for (const char *line = buf; line; line = strchr(line, '\n')) { + if (*line == '\n') { line++; } + while (*line == ' ' || *line == '\t') { line++; } + if (strncmp(line, "@include", 8) == 0) { return true; } + } + return false; +} + static char * read_manifest_text(const char *filename) { @@ -100,13 +113,9 @@ read_manifest_text(const char *filename) return NULL; } buf[n] = '\0'; - for (const char *line = buf; line; line = strchr(line, '\n')) { - if (*line == '\n') { line++; } - while (*line == ' ' || *line == '\t') { line++; } - if (strncmp(line, "@include", 8) == 0) { - free(buf); - return NULL; - } + if (has_include(buf)) { + free(buf); + return NULL; } return buf; } @@ -140,6 +149,112 @@ manifest_relations(config_t *cfg, const char *key, char ***names, semver_t **ver return true; } +/* A growing string of lines. A failed append leaves ok false and the + * caller frees s. */ +struct sbuf { + char *s; + size_t len, cap; + bool ok; +}; + +static void +sb_add(struct sbuf *b, const char *a, const char *sep1, const char *c, + const char *sep2, const char *d) +{ + const char *parts[] = { a, sep1, c, sep2, d, "\n" }; + size_t need = 0; + if (!b->ok) { return; } + for (size_t i = 0; i < 6; i++) { need += parts[i] ? strlen(parts[i]) : 0; } + if (b->len + need + 1 > b->cap) { + size_t cap = (b->len + need + 1) * 2; + char *grown = realloc(b->s, cap); + if (!grown) { + b->ok = false; + return; + } + b->s = grown; + b->cap = cap; + } + for (size_t i = 0; i < 6; i++) { + if (!parts[i]) { continue; } + size_t l = strlen(parts[i]); + memcpy(b->s + b->len, parts[i], l); + b->len += l; + } + b->s[b->len] = '\0'; +} + +/* The finished string ("" if nothing was added), or NULL on failure. */ +static char * +sb_take(struct sbuf *b) +{ + if (b->ok && !b->s) { b->s = strdup(""); } + if (!b->ok || !b->s) { + free(b->s); + b->s = NULL; + } + return b->s; +} + +/* + * gl_valid_trait + * DESCRIPTION: a trait name (BUILD_DESIGN.txt section 4): 1 to 32 of + * [a-z0-9_]. Trait names end up in configuration lines and + * manifests; nothing else is ever a trait. + */ +bool +gl_valid_trait(const char *s) +{ + if (!s || !*s || strlen(s) > 32) { return false; } + for (; *s; s++) { + if (!((*s >= 'a' && *s <= 'z') || (*s >= '0' && *s <= '9') || *s == '_')) { + return false; + } + } + return true; +} + +/* Whether `line` ("NAME" or "-NAME") appears in `lines` with either + * sign: one trait listed twice is malformed. */ +static bool +trait_listed(const char *lines, const char *name) +{ + size_t l = strlen(name); + for (const char *p = lines; p && *p; p = strchr(p, '\n') + 1) { + const char *q = *p == '-' ? p + 1 : p; + if (strncmp(q, name, l) == 0 && q[l] == '\n') { return true; } + } + return false; +} + +/* PKG_TRAITS: an optional array of "NAME" / "-NAME" strings, each trait + * once, into "NAME\n" lines (*out stays NULL if absent). */ +static bool +manifest_traits(config_t *cfg, char **out) +{ + *out = NULL; + config_setting_t *l = config_lookup(cfg, "PKG_TRAITS"); + if (!l) { return true; } + if (config_setting_type(l) != CONFIG_TYPE_ARRAY && + config_setting_type(l) != CONFIG_TYPE_LIST) { + return false; + } + int n = config_setting_length(l); + if (n > GL_MAX_TRAITS) { return false; } + struct sbuf b = { NULL, 0, 0, true }; + for (int i = 0; i < n; i++) { + const char *t = config_setting_get_string(config_setting_get_elem(l, (unsigned)i)); + const char *name = t && *t == '-' ? t + 1 : t; + if (!gl_valid_trait(name) || trait_listed(b.s, name)) { + free(b.s); + return false; + } + sb_add(&b, t, NULL, NULL, NULL, NULL); + } + *out = sb_take(&b); + return *out != NULL; +} + static void free_relations(char **names, semver_t *vers) { @@ -176,12 +291,16 @@ gl_gpm2gpkg(const char *filename, gl_pkg_t *pkg) bool ok = gl_valid_pkg_ident(name) && gl_valid_pkg_ident(repo); bool rels = manifest_relations(&cfg, "PKG_DEPS", &dnames, &dvers); rels = manifest_relations(&cfg, "PKG_CONFS", &cnames, &cvers) && rels; - if (!ok || !rels) { + char *traits = NULL; + bool tr = manifest_traits(&cfg, &traits); + if (!ok || !rels || !tr) { free_relations(dnames, dvers); free_relations(cnames, cvers); + free(traits); config_destroy(&cfg); return EINVAL; } + pkg->pkg_traits = traits; pkg->pkg_name = strdup(name); pkg->pkg_repo = strdup(repo); @@ -233,6 +352,7 @@ gl_free_pkg(gl_pkg_t *pkg) free(pkg->pkg_maint); free(pkg->pkg_copyright); free(pkg->pkg_repo); + free(pkg->pkg_traits); gl_free_semver(&pkg->pkg_ver); @@ -515,6 +635,41 @@ valid_sha256_field(const char *s) return true; } +/* Why the last gl_recipe_parse / gl_recipe_read in this thread failed + * (gl_recipe_error). The helpers below are shared with the index and + * build-settings readers, which set it too and never read it. */ +static _Thread_local char recipe_why[256]; + +/* Set recipe_why from a format, every byte outside printable ASCII + * replaced by '?': it quotes untrusted recipe text and ends up on a + * terminal. Returns false, so a check can `return why(...)`. */ +bool +gl_recipe_set_error(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vsnprintf(recipe_why, sizeof recipe_why, fmt, ap); + va_end(ap); + for (char *c = recipe_why; *c; c++) + if (*c < 0x20 || *c > 0x7e) + *c = '?'; + return false; +} +#define why gl_recipe_set_error + +/* + * gl_recipe_error + * DESCRIPTION: why the last gl_recipe_parse or gl_recipe_read in the + * calling thread failed, as a short phrase without a final + * period ("SOURCES entry 1: SHA256 must be ..."), printable + * ASCII only. "" after a success. + */ +const char * +gl_recipe_error(void) +{ + return recipe_why; +} + /* A group with exactly the members named in `names` (NULL-terminated). */ static bool has_exactly(config_setting_t *g, const char *const *names) @@ -548,37 +703,177 @@ int_member(config_setting_t *g, const char *name, int64_t *out) return true; } -/* DEPS or CONFS: a list of { NAME; VER; } groups, as "NAME VER\n" lines - * into a new string (*out; "" for an empty list). */ +/* Whether every member of group g is named in `names` (NULL-terminated). */ static bool -read_relations(config_setting_t *pkg, const char *name, char **out) +members_within(config_setting_t *g, const char *const *names) { - static const char *const members[] = { "NAME", "VER", NULL }; - config_setting_t *l = config_setting_get_member(pkg, name); - if (!l || config_setting_type(l) != CONFIG_TYPE_LIST) + if (!g || config_setting_type(g) != CONFIG_TYPE_GROUP) return false; - int n = config_setting_length(l); - size_t cap = 1, used = 0; + int n = config_setting_length(g); for (int i = 0; i < n; i++) { - config_setting_t *r = config_setting_get_elem(l, (unsigned)i); - const char *nm, *ver; - if (!has_exactly(r, members) || !(nm = str_member(r, "NAME")) || - !(ver = str_member(r, "VER")) || !gl_valid_pkg_ident(nm) || - !valid_index_ver(ver)) + const char *m = config_setting_name(config_setting_get_elem(g, (unsigned)i)); + bool known = false; + for (size_t k = 0; names[k] && !known; k++) + known = strcmp(m, names[k]) == 0; + if (!known) return false; - cap += strlen(nm) + strlen(ver) + 2; - } - if (!(*out = malloc(cap))) - return false; - (*out)[0] = '\0'; - for (int i = 0; i < n; i++) { - config_setting_t *r = config_setting_get_elem(l, (unsigned)i); - used += (size_t)snprintf(*out + used, cap - used, "%s %s\n", - str_member(r, "NAME"), str_member(r, "VER")); } return true; } +/* An IF condition, "T" or "-T", naming one of `traits` ("NAME D\n" + * lines: a -src index's or a recipe's). */ +static bool +valid_if(const char *cond, const char *traits) +{ + const char *t = *cond == '-' ? cond + 1 : cond; + size_t l = strlen(t); + if (!gl_valid_trait(t)) + return false; + for (const char *p = traits; *p; p = strchr(p, '\n') + 1) + if (strncmp(p, t, l) == 0 && p[l] == ' ') + return true; + return false; +} + +/* DEPS, CONFS or BUILD_DEPS: a list of { NAME; VER; } groups, as + * "NAME VER\n" lines into a new string (*out; "" for an empty list). + * With `traits` (a -src index or a recipe), a group may also have + * IF = "T" / "-T" naming one of them: "NAME VER IF\n". A missing list + * is malformed unless `optional`. */ +static bool +read_relations(config_setting_t *pkg, const char *name, const char *traits, + bool optional, char **out) +{ + static const char *const members[] = { "NAME", "VER", "IF", NULL }; + *out = NULL; + config_setting_t *l = config_setting_get_member(pkg, name); + if (!l && optional) + return (*out = strdup("")) != NULL; + if (!l) + return why("%s is missing", name); + if (config_setting_type(l) != CONFIG_TYPE_LIST) + return why("%s must be a list of { NAME; VER; } groups", name); + int n = config_setting_length(l); + struct sbuf b = { NULL, 0, 0, true }; + for (int i = 0; i < n; i++) { + config_setting_t *r = config_setting_get_elem(l, (unsigned)i); + const char *nm = str_member(r, "NAME"), *ver = str_member(r, "VER"); + config_setting_t *cond = config_setting_get_member(r, "IF"); + const char *c = cond ? str_member(r, "IF") : NULL; + if (!members_within(r, members)) + why("%s entry %d may only have NAME, VER and IF", name, i + 1); + else if (!nm) + why("%s entry %d: NAME is missing or not a string", name, i + 1); + else if (!gl_valid_pkg_ident(nm)) + why("%s entry %d: \"%s\" is not a valid package name", name, i + 1, nm); + else if (!ver) + why("%s entry %d: VER is missing or not a string", name, i + 1); + else if (!valid_index_ver(ver)) + why("%s entry %d: VER \"%s\" must be X.Y.Z", name, i + 1, ver); + else if (cond && !traits) + why("%s entry %d: IF is only allowed in recipes", name, i + 1); + else if (cond && !c) + why("%s entry %d: IF must be a string", name, i + 1); + else if (cond && !valid_if(c, traits)) + why("%s entry %d: IF \"%s\" names no trait in TRAITS", name, i + 1, c); + else { + sb_add(&b, nm, " ", ver, c ? " " : NULL, c); + continue; + } + free(b.s); + return false; + } + *out = sb_take(&b); + return *out != NULL || why("out of memory"); +} + +/* TRAITS: a list of { NAME; DEFAULT; } groups (a recipe's may also have + * ON and OFF arrays of arguments), each NAME a gl_valid_trait, once, at + * most GL_MAX_TRAITS. "NAME 1\n" / "NAME 0\n" into *traits, and for a + * recipe (args != NULL) "NAME\t+\tARG\n" / "NAME\t-\tARG\n" into *args. + * A missing list is malformed unless `optional`. */ +static bool valid_arg(const char *s); + +static bool +read_traits(config_setting_t *g, bool optional, char **traits, char **args) +{ + static const char *const index_members[] = { "NAME", "DEFAULT", NULL }; + static const char *const recipe_members[] = { "NAME", "DEFAULT", "ON", "OFF", NULL }; + *traits = NULL; + if (args) + *args = NULL; + config_setting_t *l = config_setting_get_member(g, "TRAITS"); + struct sbuf t = { NULL, 0, 0, true }, a = { NULL, 0, 0, true }; + if (!l && !optional) + return why("TRAITS is missing"); + int n = l ? config_setting_length(l) : 0; + if (l && config_setting_type(l) != CONFIG_TYPE_LIST) + return why("TRAITS must be a list of { NAME; DEFAULT; } groups"); + if (n > GL_MAX_TRAITS) + return why("TRAITS has more than %d traits", GL_MAX_TRAITS); + for (int i = 0; i < n; i++) { + config_setting_t *e = config_setting_get_elem(l, (unsigned)i); + config_setting_t *def = config_setting_get_member(e, "DEFAULT"); + const char *nm = str_member(e, "NAME"); + if (!members_within(e, args ? recipe_members : index_members)) { + why(args ? "TRAITS entry %d may only have NAME, DEFAULT, ON and OFF" : + "TRAITS entry %d may only have NAME and DEFAULT", i + 1); + goto fail; + } + if (!nm || !gl_valid_trait(nm)) { + why("TRAITS entry %d: NAME must be 1-32 of a-z, 0-9 and _", i + 1); + goto fail; + } + if (!def || config_setting_type(def) != CONFIG_TYPE_BOOL) { + why("TRAITS entry %d: DEFAULT must be true or false", i + 1); + goto fail; + } + for (const char *p = t.s; p && *p; p = strchr(p, '\n') + 1) + if (strncmp(p, nm, strlen(nm)) == 0 && p[strlen(nm)] == ' ') { + why("TRAITS declares %s twice", nm); + goto fail; + } + sb_add(&t, nm, " ", config_setting_get_bool(def) ? "1" : "0", NULL, NULL); + for (int side = 0; args && side < 2; side++) { + const char *sname = side ? "OFF" : "ON"; + config_setting_t *v = config_setting_get_member(e, sname); + if (!v) + continue; + if (config_setting_type(v) != CONFIG_TYPE_ARRAY && + config_setting_type(v) != CONFIG_TYPE_LIST) { + why("TRAITS entry %d: %s must be a list of strings", i + 1, sname); + goto fail; + } + int na = config_setting_length(v); + for (int k = 0; k < na; k++) { + const char *arg = config_setting_get_string( + config_setting_get_elem(v, (unsigned)k)); + if (!arg || !valid_arg(arg)) { + why("TRAITS entry %d: %s entry %d must be a non-empty " + "string of printable ASCII (no tab or newline)", + i + 1, sname, k + 1); + goto fail; + } + sb_add(&a, nm, "\t", side ? "-" : "+", "\t", arg); + } + } + } + if (!(*traits = sb_take(&t)) || (args && !(*args = sb_take(&a)))) { + free(*traits); + *traits = NULL; + free(a.s); + return why("out of memory"); + } + if (!args) + free(a.s); + return true; +fail: + free(t.s); + free(a.s); + return false; +} + void gl_index_free(gl_index_t *idx) { @@ -592,12 +887,23 @@ gl_index_free(gl_index_t *idx) free(p->sha256); free(p->deps); free(p->confs); + free(p->build_deps); + free(p->traits); } free(idx->pkgs); free(idx->repo); memset(idx, 0, sizeof(*idx)); } +/* Whether repository name r is a recipe repository, "X-src" (X itself a + * gl_valid_pkg_ident, so "-src" alone is not one). */ +static bool +is_src_repo(const char *r) +{ + size_t l = strlen(r); + return l > 4 && strcmp(r + l - 4, "-src") == 0; +} + /* * Parse an index's bytes (text[0..len)) into *out, which is zeroed * first; free it with gl_index_free on GL_INDEX_OK. The caller checks @@ -612,6 +918,12 @@ gl_index_free(gl_index_t *idx) * "sha256:" + 64 lowercase hex; DEPS/CONFS lists of { NAME; VER; }; no * NAME + VER twice. A NUL or '@' anywhere is refused before parsing: * an index never has one, and '@' is how libconfig spells @include. + * + * A REPO ending in "-src" is a recipe index (BUILD_DESIGN.txt section + * 3): each package also has exactly BUILD_DEPS and TRAITS ({ NAME; + * DEFAULT; } groups), FILE is "NAME-VER.grcp", and DEPS, CONFS and + * BUILD_DEPS entries may have IF naming one of its TRAITS. In a binary + * index those are all malformed. * GL_INDEX_OK, GL_INDEX_ERR_FORMAT, GL_INDEX_ERR_REPO (well formed, * but REPO is not `repo`), GL_INDEX_ERR_NOMEM */ @@ -621,6 +933,8 @@ gl_index_parse(const char *text, size_t len, const char *repo, gl_index_t *out) static const char *const top[] = { "REPO", "SERIAL", "VALID_UNTIL", "PKGS", NULL }; static const char *const fields[] = { "NAME", "VER", "FILE", "SHA256", "SIZE", "DEPS", "CONFS", NULL }; + static const char *const src_fields[] = { "NAME", "VER", "FILE", "SHA256", + "SIZE", "DEPS", "CONFS", "BUILD_DEPS", "TRAITS", NULL }; if (!out) return GL_INDEX_ERR_FORMAT; @@ -654,6 +968,7 @@ gl_index_parse(const char *text, size_t len, const char *repo, gl_index_t *out) out->valid_until <= 0 || config_setting_type(pkgs) != CONFIG_TYPE_LIST) goto fail; + bool src = is_src_repo(r); size_t n = (size_t)config_setting_length(pkgs); if (n && !(out->pkgs = calloc(n, sizeof(*out->pkgs)))) { @@ -665,7 +980,7 @@ gl_index_parse(const char *text, size_t len, const char *repo, gl_index_t *out) gl_index_pkg_t *p = &out->pkgs[i]; out->npkgs = i + 1; const char *nm, *ver, *file, *sha; - if (!has_exactly(e, fields) || + if (!has_exactly(e, src ? src_fields : fields) || !(nm = str_member(e, "NAME")) || !gl_valid_pkg_ident(nm) || !(ver = str_member(e, "VER")) || !valid_index_ver(ver) || !(file = str_member(e, "FILE")) || @@ -673,7 +988,7 @@ gl_index_parse(const char *text, size_t len, const char *repo, gl_index_t *out) !int_member(e, "SIZE", &p->size) || p->size < 0) goto fail; char want[PATH_MAX]; - snprintf(want, sizeof want, "%s-%s.gpkg", nm, ver); + snprintf(want, sizeof want, "%s-%s.%s", nm, ver, src ? "grcp" : "gpkg"); if (strcmp(file, want) != 0) goto fail; for (size_t j = 0; j < i; j++) @@ -685,8 +1000,16 @@ gl_index_parse(const char *text, size_t len, const char *repo, gl_index_t *out) st = GL_INDEX_ERR_NOMEM; goto fail; } - if (!read_relations(e, "DEPS", &p->deps) || - !read_relations(e, "CONFS", &p->confs)) + if (src) { + if (!read_traits(e, false, &p->traits, NULL) || + !read_relations(e, "BUILD_DEPS", p->traits, false, &p->build_deps)) + goto fail; + } else if (!(p->traits = strdup("")) || !(p->build_deps = strdup(""))) { + st = GL_INDEX_ERR_NOMEM; + goto fail; + } + if (!read_relations(e, "DEPS", src ? p->traits : NULL, false, &p->deps) || + !read_relations(e, "CONFS", src ? p->traits : NULL, false, &p->confs)) goto fail; } if (strcmp(r, repo) != 0) { @@ -704,3 +1027,427 @@ fail: gl_index_free(out); return st; } + +/* ------------------------------------------------------------------ */ +/* Recipes (BUILD_DESIGN.txt section 4) */ +/* ------------------------------------------------------------------ */ + +/* What valid_arg and valid_text accept, for gl_recipe_error. */ +#define ARG_RULE "a non-empty string of printable ASCII (no tab or newline)" +#define TEXT_RULE "non-empty text without control characters" + +/* A configure argument: non-empty printable ASCII, spaces allowed, no + * tab or newline (those separate the lines it is stored in). */ +static bool +valid_arg(const char *s) +{ + if (!*s) + return false; + for (; *s; s++) + if (*s < 0x20 || *s > 0x7e) + return false; + return true; +} + +/* A free-text field (DESC, MAINT, COPYRIGHT): non-empty, no control + * characters. UTF-8 is fine. */ +static bool +valid_text(const char *s) +{ + if (!*s) + return false; + for (; *s; s++) + if ((unsigned char)*s < 0x20 || *s == 0x7f) + return false; + return true; +} + +/* A string member that is a valid_text, or NULL. */ +static const char * +text_member(config_setting_t *g, const char *name) +{ + const char *v = str_member(g, name); + return v && valid_text(v) ? v : NULL; +} + +/* An array (or list) of strings each passing `ok` (`what` says what + * one must be, for gl_recipe_error), as "S\n" lines; a missing member + * is "". With `unique`, no string twice. */ +static bool +read_strings(config_setting_t *g, const char *name, bool (*ok)(const char *), + const char *what, bool unique, char **out) +{ + *out = NULL; + config_setting_t *l = config_setting_get_member(g, name); + if (!l) + return (*out = strdup("")) != NULL || why("out of memory"); + if (config_setting_type(l) != CONFIG_TYPE_ARRAY && + config_setting_type(l) != CONFIG_TYPE_LIST) + return why("%s must be a list of strings", name); + struct sbuf b = { NULL, 0, 0, true }; + int n = config_setting_length(l); + for (int i = 0; i < n; i++) { + const char *v = config_setting_get_string(config_setting_get_elem(l, (unsigned)i)); + bool dup = false; + for (int j = 0; unique && v && j < i; j++) + dup = dup || strcmp(v, config_setting_get_string( + config_setting_get_elem(l, (unsigned)j))) == 0; + if (!v || !ok(v) || dup) { + if (!v) + why("%s entry %d is not a string", name, i + 1); + else if (!ok(v)) + why("%s entry %d must be %s", name, i + 1, what); + else + why("%s lists \"%s\" twice", name, v); + free(b.s); + return false; + } + sb_add(&b, v, NULL, NULL, NULL, NULL); + } + *out = sb_take(&b); + return *out != NULL || why("out of memory"); +} + +/* SOURCES: a non-empty list of { URL; SHA256; }. URL is https:// or + * file:// (valid_repo_url) and its last component, the file the + * builder saves it as, a gl_valid_pkg_ident, each once. */ +static bool +read_sources(config_setting_t *g, char **out) +{ + static const char *const members[] = { "URL", "SHA256", NULL }; + *out = NULL; + config_setting_t *l = config_setting_get_member(g, "SOURCES"); + if (!l) + return why("SOURCES is missing"); + if (config_setting_type(l) != CONFIG_TYPE_LIST || config_setting_length(l) < 1) + return why("SOURCES must be a non-empty list of { URL; SHA256; } groups"); + struct sbuf b = { NULL, 0, 0, true }; + int n = config_setting_length(l); + for (int i = 0; i < n; i++) { + config_setting_t *e = config_setting_get_elem(l, (unsigned)i); + const char *url = str_member(e, "URL"), *sha = str_member(e, "SHA256"); + const char *file = url ? strrchr(url, '/') : NULL; + if (!has_exactly(e, members)) { + why("SOURCES entry %d must have exactly URL and SHA256", i + 1); + goto fail; + } + if (!url || !valid_repo_url(url)) { + why("SOURCES entry %d: URL must be https:// or file://, " + "printable ASCII without spaces", i + 1); + goto fail; + } + if (!sha || !valid_sha256_field(sha)) { + why("SOURCES entry %d: SHA256 must be \"sha256:\" followed by " + "64 lowercase hex digits", i + 1); + goto fail; + } + if (!file || !gl_valid_pkg_ident(file + 1)) { + why("SOURCES entry %d: the URL must end in a file name " + "(letters, digits, '.', '_' and '-')", i + 1); + goto fail; + } + for (int j = 0; j < i; j++) { + const char *prev = strrchr(str_member(config_setting_get_elem(l, + (unsigned)j), "URL"), '/'); + if (strcmp(prev, file) == 0) { + why("SOURCES entries %d and %d are both named %s", j + 1, + i + 1, file + 1); + goto fail; + } + } + sb_add(&b, url, " ", sha, NULL, NULL); + } + *out = sb_take(&b); + return *out != NULL || why("out of memory"); +fail: + free(b.s); + return false; +} + +static bool +valid_patch(const char *s) +{ + return gl_valid_pkg_ident(s); +} + +void +gl_recipe_free(gl_recipe_t *r) +{ + if (!r) + return; + char **fields[] = { &r->name, &r->ver, &r->repo, &r->desc, &r->maint, + &r->copyright, &r->sources, &r->patches, &r->build, &r->configure, + &r->traits, &r->trait_args, &r->deps, &r->build_deps, &r->confs }; + for (size_t i = 0; i < sizeof fields / sizeof *fields; i++) + free(*fields[i]); + memset(r, 0, sizeof(*r)); +} + +/* + * gl_recipe_parse + * DESCRIPTION: parse a recipe's bytes (text[0..len), at most + * GL_RECIPE_MAX) into *out, which is zeroed first; free it + * with gl_recipe_free on GL_RECIPE_OK. Recipes come from a + * signed -src index's bundles, but are still parsed as + * untrusted: strict, and nothing unknown is ignored (CLAUDE.md + * bug 10's class). + * + * Required: NAME (gl_valid_pkg_ident), VER (as the store names + * versions), REPO (gl_valid_pkg_ident, not itself a -src + * name), DESC, MAINT, COPYRIGHT (text), SOURCES (read_sources). + * Optional: PATCHES (unique file names), BUILD (autotools, + * cmake, meson, make or hooks), CONFIGURE (valid_arg strings), + * TRAITS (read_traits, with ON/OFF), DEPS, BUILD_DEPS, CONFS + * (read_relations, IF naming one of TRAITS). An `@include` + * line or a NUL is refused before parsing. + * RETURNS: GL_RECIPE_OK, GL_RECIPE_ERR_FORMAT, GL_RECIPE_ERR_NOMEM + */ +gl_recipe_status_t +gl_recipe_parse(const char *text, size_t len, gl_recipe_t *out) +{ + static const char *const known[] = { "NAME", "VER", "REPO", "DESC", "MAINT", + "COPYRIGHT", "SOURCES", "PATCHES", "BUILD", "CONFIGURE", "TRAITS", + "DEPS", "BUILD_DEPS", "CONFS", NULL }; + static const char *const builds[] = { "autotools", "cmake", "meson", + "make", "hooks", NULL }; + + recipe_why[0] = '\0'; + if (!out) + return GL_RECIPE_ERR_FORMAT; + memset(out, 0, sizeof(*out)); + if (!text) { + why("no recipe"); + return GL_RECIPE_ERR_FORMAT; + } + if (len > GL_RECIPE_MAX) { + why("the recipe is larger than %d bytes", GL_RECIPE_MAX); + return GL_RECIPE_ERR_FORMAT; + } + if (memchr(text, '\0', len)) { + why("the recipe contains a NUL byte"); + return GL_RECIPE_ERR_FORMAT; + } + + char *buf = malloc(len + 1); + if (!buf) { + why("out of memory"); + return GL_RECIPE_ERR_NOMEM; + } + memcpy(buf, text, len); + buf[len] = '\0'; + if (has_include(buf)) { + free(buf); + why("@include is not allowed"); + return GL_RECIPE_ERR_FORMAT; + } + + config_t cfg; + config_init(&cfg); + int ok = config_read_string(&cfg, buf); + free(buf); + if (!ok) { + why("line %d: %s", config_error_line(&cfg), + config_error_text(&cfg) ? config_error_text(&cfg) : "not libconfig syntax"); + config_destroy(&cfg); + return GL_RECIPE_ERR_FORMAT; + } + + config_setting_t *root = config_root_setting(&cfg); + const char *nm = str_member(root, "NAME"), *ver = str_member(root, "VER"); + const char *repo = str_member(root, "REPO"); + const char *desc = text_member(root, "DESC"), *maint = text_member(root, "MAINT"); + const char *copy = text_member(root, "COPYRIGHT"); + config_setting_t *build = config_setting_get_member(root, "BUILD"); + const char *b = build ? str_member(root, "BUILD") : ""; + bool known_build = b && !*b; + for (size_t i = 0; b && builds[i]; i++) + known_build = known_build || strcmp(b, builds[i]) == 0; + + /* The first problem, in the order a recipe is usually written. */ + const char *field = NULL, *must = NULL; + for (int i = 0; i < config_setting_length(root) && !field; i++) { + const char *m = config_setting_name(config_setting_get_elem(root, (unsigned)i)); + bool k = false; + for (size_t j = 0; known[j] && !k; j++) + k = strcmp(m, known[j]) == 0; + if (!k) { + why("unknown setting %s", m); + goto fail; + } + } + if (!nm || !gl_valid_pkg_ident(nm)) + field = "NAME", must = "a package name (letters, digits, '.', '_' and '-')"; + else if (!ver || !valid_index_ver(ver)) + field = "VER", must = "a version X.Y.Z (decimal, no leading zeros)"; + else if (!repo || !gl_valid_pkg_ident(repo)) + field = "REPO", must = "a repository name"; + else if (is_src_repo(repo)) + field = "REPO", must = "the binary repository built for (\"extra\", not \"extra-src\")"; + else if (!desc) + field = "DESC", must = TEXT_RULE; + else if (!maint) + field = "MAINT", must = TEXT_RULE; + else if (!copy) + field = "COPYRIGHT", must = TEXT_RULE; + else if (!b || !known_build || (build && !*b)) + field = "BUILD", must = "autotools, cmake, meson, make or hooks"; + if (field) { + if (config_setting_get_member(root, field)) + why("%s must be %s", field, must); + else + why("%s is missing", field); + goto fail; + } + if (!(out->name = strdup(nm)) || !(out->ver = strdup(ver)) || + !(out->repo = strdup(repo)) || !(out->desc = strdup(desc)) || + !(out->maint = strdup(maint)) || !(out->copyright = strdup(copy)) || + !(out->build = strdup(b))) { + gl_recipe_free(out); + config_destroy(&cfg); + why("out of memory"); + return GL_RECIPE_ERR_NOMEM; + } + if (!read_sources(root, &out->sources) || + !read_strings(root, "PATCHES", valid_patch, + "a file name (letters, digits, '.', '_' and '-')", true, &out->patches) || + !read_strings(root, "CONFIGURE", valid_arg, ARG_RULE, false, &out->configure) || + !read_traits(root, true, &out->traits, &out->trait_args) || + !read_relations(root, "DEPS", out->traits, true, &out->deps) || + !read_relations(root, "BUILD_DEPS", out->traits, true, &out->build_deps) || + !read_relations(root, "CONFS", out->traits, true, &out->confs)) + goto fail; + config_destroy(&cfg); + return GL_RECIPE_OK; +fail: + gl_recipe_free(out); + config_destroy(&cfg); + return GL_RECIPE_ERR_FORMAT; +} + +/* ------------------------------------------------------------------ */ +/* Build settings (BUILD_DESIGN.txt section 5) */ +/* ------------------------------------------------------------------ */ + +void +gl_build_conf_free(gl_build_conf_t *c) +{ + if (!c) + return; + free(c->traits); + free(c->cflags); + free(c->cxxflags); + free(c->ldflags); + free(c->configure); + free(c->build_user); + free(c->build_root); + memset(c, 0, sizeof(*c)); +} + +static bool +valid_trait_setting(const char *s) +{ + return gl_valid_trait(*s == '-' ? s + 1 : s); +} + +/* + * gl_conf_build + * DESCRIPTION: read the build settings of one configuration file into + * *out (zeroed first; gl_build_conf_free it on GL_CONF_OK). + * Which settings a file may have depends on `kind`, and any + * other is INVALID (nothing unknown is ignored, CLAUDE.md bug + * 10's class): + * SYSTEM KEEP_OLD (read by gl_conf_get_int), TRAITS, CFLAGS, + * CXXFLAGS, LDFLAGS, JOBS, BUILD_USER, BUILD_ROOT + * USER TRAITS, CFLAGS, CXXFLAGS, LDFLAGS, JOBS + * PACKAGE TRAITS, CFLAGS, CXXFLAGS, LDFLAGS, CONFIGURE + * TRAITS: strings "T" / "-T", each trait once; CFLAGS, + * CXXFLAGS, LDFLAGS: a string of printable ASCII (no tab or + * newline); CONFIGURE: strings likewise; JOBS: 1 to 1024; + * BUILD_USER: a gl_valid_pkg_ident; BUILD_ROOT: package names. + * RETURNS: GL_CONF_OK, GL_CONF_ERR_READ (missing, unreadable or not + * libconfig), GL_CONF_ERR_INVALID, GL_CONF_ERR_SPACE (out of memory) + */ +gl_conf_status_t +gl_conf_build(const char *path, gl_conf_kind_t kind, gl_build_conf_t *out) +{ + static const char *const system_keys[] = { "KEEP_OLD", "TRAITS", "CFLAGS", + "CXXFLAGS", "LDFLAGS", "JOBS", "BUILD_USER", "BUILD_ROOT", NULL }; + static const char *const user_keys[] = { "TRAITS", "CFLAGS", "CXXFLAGS", + "LDFLAGS", "JOBS", NULL }; + static const char *const package_keys[] = { "TRAITS", "CFLAGS", "CXXFLAGS", + "LDFLAGS", "CONFIGURE", NULL }; + const char *const *keys = kind == GL_CONF_SYSTEM ? system_keys : + kind == GL_CONF_USER ? user_keys : package_keys; + + if (!out) + return GL_CONF_ERR_INVALID; + memset(out, 0, sizeof(*out)); + + config_t cfg; + config_init(&cfg); + if (!config_read_file(&cfg, path)) { + config_destroy(&cfg); + return GL_CONF_ERR_READ; + } + config_setting_t *root = config_root_setting(&cfg); + if (!members_within(root, keys)) + goto invalid; + + config_setting_t *t = config_setting_get_member(root, "TRAITS"); + if (t) { + int n = config_setting_length(t); + if (!read_strings(root, "TRAITS", valid_trait_setting, + "a trait, \"name\" or \"-name\"", false, &out->traits) || + n > GL_MAX_TRAITS) + goto invalid; + for (int i = 0; i < n; i++) { + const char *a = config_setting_get_string(config_setting_get_elem(t, (unsigned)i)); + for (int j = 0; j < i; j++) { + const char *b = config_setting_get_string( + config_setting_get_elem(t, (unsigned)j)); + if (strcmp(*a == '-' ? a + 1 : a, *b == '-' ? b + 1 : b) == 0) + goto invalid; + } + } + } + const char *flags[] = { "CFLAGS", "CXXFLAGS", "LDFLAGS" }; + char **dest[] = { &out->cflags, &out->cxxflags, &out->ldflags }; + for (size_t i = 0; i < 3; i++) { + config_setting_t *m = config_setting_get_member(root, flags[i]); + const char *v = m ? str_member(root, flags[i]) : NULL; + if (m && (!v || (*v && !valid_arg(v)))) + goto invalid; + if (v && !(*dest[i] = strdup(v))) + goto nomem; + } + if (config_setting_get_member(root, "CONFIGURE") && + !read_strings(root, "CONFIGURE", valid_arg, ARG_RULE, false, &out->configure)) + goto invalid; + if (config_setting_get_member(root, "JOBS")) { + int64_t j; + if (!int_member(root, "JOBS", &j) || j < 1 || j > 1024) + goto invalid; + out->jobs = (int)j; + } + if (config_setting_get_member(root, "BUILD_USER")) { + const char *u = str_member(root, "BUILD_USER"); + if (!u || !gl_valid_pkg_ident(u)) + goto invalid; + if (!(out->build_user = strdup(u))) + goto nomem; + } + if (config_setting_get_member(root, "BUILD_ROOT") && + !read_strings(root, "BUILD_ROOT", gl_valid_pkg_ident, + "a package name", true, &out->build_root)) + goto invalid; + config_destroy(&cfg); + return GL_CONF_OK; +invalid: + gl_build_conf_free(out); + config_destroy(&cfg); + return GL_CONF_ERR_INVALID; +nomem: + gl_build_conf_free(out); + config_destroy(&cfg); + return GL_CONF_ERR_SPACE; +} diff --git a/src/pkg.h b/src/pkg.h index f41bca5..05f60ad 100644 --- a/src/pkg.h +++ b/src/pkg.h @@ -41,6 +41,10 @@ typedef struct { char *pkg_repo; dep_t *pkg_dependencies; conf_t *pkg_conflicts; + /* PKG_TRAITS (BUILD_DESIGN.txt section 8): "ssl\n-ldap\n", one + * "NAME" (on) or "-NAME" (off) line per trait; NULL if the manifest + * has none. */ + char *pkg_traits; } gl_pkg_t; @@ -63,8 +67,37 @@ gl_conf_status_t gl_conf_repo_keys(const char *path, const char *repo, char *out, size_t outlen); gl_conf_status_t gl_conf_repos(const char *path, char *out, size_t outlen); +/* Build settings (BUILD_DESIGN.txt section 5), as gl_conf_build reads + * them from one file; every string is NULL where the file doesn't set + * it, jobs is 0. traits is "NAME\n" / "-NAME\n" lines, configure and + * build_root "S\n" lines. */ +typedef struct { + char *traits; + char *cflags; + char *cxxflags; + char *ldflags; + char *configure; + int jobs; + char *build_user; + char *build_root; +} gl_build_conf_t; + +typedef enum { + GL_CONF_SYSTEM = 0, /* /etc/glacier/glacier.conf */ + GL_CONF_USER = 1, /* /config/glacier.conf */ + GL_CONF_PACKAGE = 2 /* .../config/NAME.conf */ +} gl_conf_kind_t; + +gl_conf_status_t gl_conf_build(const char *path, gl_conf_kind_t kind, + gl_build_conf_t *out); +void gl_build_conf_free(gl_build_conf_t *c); + /* A repository index (REPO_DESIGN.txt section 4), as gl_index_parse - * reads it. deps/confs are "NAME VER\n" lines ("" for none). */ + * reads it. deps/confs are "NAME VER\n" lines ("" for none). In a -src + * index (BUILD_DESIGN.txt section 3), deps/confs/build_deps lines may + * end in " IF" ("NAME VER ssl\n", "NAME VER -ssl\n") and traits are + * "NAME 1\n" / "NAME 0\n" (the default); both are "" in a binary + * index. */ typedef struct { char *name; char *ver; @@ -73,6 +106,8 @@ typedef struct { int64_t size; char *deps; char *confs; + char *build_deps; + char *traits; } gl_index_pkg_t; typedef struct { @@ -94,6 +129,52 @@ gl_index_status_t gl_index_parse(const char *text, size_t len, const char *repo, gl_index_t *out); void gl_index_free(gl_index_t *idx); +/* A recipe (BUILD_DESIGN.txt section 4), as gl_recipe_parse reads it. + * Every list is newline-terminated lines, "" for none: + * sources "URL sha256:HEX\n" + * patches "FILE\n" + * configure "ARG\n" + * traits "NAME 1\n" / "NAME 0\n" (the default), as an index + * trait_args "NAME\t+\tARG\n" (ON) / "NAME\t-\tARG\n" (OFF) + * deps, build_deps, confs "NAME VER[ IF]\n", as a -src index + * build is "" (autodetect) or autotools, cmake, meson, make, hooks. */ +typedef struct { + char *name; + char *ver; + char *repo; + char *desc; + char *maint; + char *copyright; + char *sources; + char *patches; + char *build; + char *configure; + char *traits; + char *trait_args; + char *deps; + char *build_deps; + char *confs; +} gl_recipe_t; + +typedef enum { + GL_RECIPE_OK = 0, + GL_RECIPE_ERR_READ = 1, + GL_RECIPE_ERR_BUNDLE = 2, + GL_RECIPE_ERR_FORMAT = 3, + GL_RECIPE_ERR_NOMEM = 4 +} gl_recipe_status_t; + +/* The largest recipe file, and the most traits a recipe declares. */ +#define GL_RECIPE_MAX (1024 * 1024) +#define GL_MAX_TRAITS 32 + +gl_recipe_status_t gl_recipe_parse(const char *text, size_t len, gl_recipe_t *out); +/* Why the last gl_recipe_parse / gl_recipe_read in this thread failed: + * a short phrase, no final period, printable ASCII; "" after a success. */ +const char *gl_recipe_error(void); +void gl_recipe_free(gl_recipe_t *r); +bool gl_valid_trait(const char *s); + bool gl_valid_pkg_ident(const char *s); int gl_gpm2gpkg(const char *filename, gl_pkg_t *pkg); diff --git a/src/recipe.c b/src/recipe.c new file mode 100644 index 0000000..4427835 --- /dev/null +++ b/src/recipe.c @@ -0,0 +1,256 @@ +/* + * Recipe bundles (BUILD_DESIGN.txt section 4): NAME-VER.grcp, a gzip + * tar holding NAME-VER/recipe, optionally NAME-VER/build and + * NAME-VER/patches/FILE, and nothing else. + */ + +#define _POSIX_C_SOURCE 200809L +#define _XOPEN_SOURCE 700 + +#include +#include +#include +#include +#include +#include +#include + +#include "pkg.h" +#include "recipe.h" + +/* What an entry below the top directory is: 0 the top itself, 1 + * recipe, 2 build, 3 patches/, 4 patches/FILE; -1 anything else. */ +static int +entry_kind(const char *rel, bool dir) +{ + if (*rel == '\0') + return dir ? 0 : -1; + if (strcmp(rel, "recipe") == 0) + return dir ? -1 : 1; + if (strcmp(rel, "build") == 0) + return dir ? -1 : 2; + if (strcmp(rel, "patches") == 0) + return dir ? 3 : -1; + if (strncmp(rel, "patches/", 8) == 0 && !dir && gl_valid_pkg_ident(rel + 8)) + return 4; + return -1; +} + +/* Whether "FILE\n" is one of `lines`. */ +static bool +listed(const char *lines, const char *file) +{ + size_t l = strlen(file); + for (const char *p = lines; *p; p = strchr(p, '\n') + 1) + if (strncmp(p, file, l) == 0 && p[l] == '\n') + return true; + return false; +} + +/* + * gl_recipe_read + * DESCRIPTION: read and check a recipe bundle, and parse its recipe + * into *out (zeroed first; gl_recipe_free it on GL_RECIPE_OK). + * Nothing is extracted. Every entry is checked, not only the + * recipe: the builder unpacks the bundle (inside the sandbox), + * so what it holds must be exactly what this function allowed. + * + * The bundle is refused (GL_RECIPE_ERR_BUNDLE) unless: every + * entry is a regular file or directory (no symlinks, hardlinks, + * devices), under one top directory TOP named NAME-VER as the + * recipe says; the only entries are TOP/, TOP/recipe (required), + * TOP/build, TOP/patches/ and TOP/patches/FILE (a + * gl_valid_pkg_ident), none twice; the patches are exactly the + * recipe's PATCHES; BUILD = "hooks" has a TOP/build; the + * entries' sizes add up to at most GL_BUNDLE_MAX. + * RETURNS: GL_RECIPE_OK, GL_RECIPE_ERR_READ (not a readable gzip tar), + * GL_RECIPE_ERR_BUNDLE, GL_RECIPE_ERR_FORMAT (the recipe itself), + * GL_RECIPE_ERR_NOMEM + */ +gl_recipe_status_t +gl_recipe_read(const char *bundle, gl_recipe_t *out) +{ + gl_recipe_set_error("%s", ""); + if (!out) + return GL_RECIPE_ERR_FORMAT; + memset(out, 0, sizeof(*out)); + + struct archive *a = archive_read_new(); + if (!a) { + gl_recipe_set_error("out of memory"); + return GL_RECIPE_ERR_NOMEM; + } + archive_read_support_filter_gzip(a); + archive_read_support_format_tar(a); + if (archive_read_open_filename(a, bundle, 10240) != ARCHIVE_OK) { + gl_recipe_set_error("not a gzip tar (%s)", archive_error_string(a) ? + archive_error_string(a) : "unreadable"); + archive_read_free(a); + return GL_RECIPE_ERR_READ; + } + + gl_recipe_status_t st = GL_RECIPE_ERR_BUNDLE; + char top[PATH_MAX] = ""; + char *recipe = NULL, *patches = NULL; + size_t rlen = 0, plen = 0; + int64_t total = 0; + bool seen[4] = { false, false, false, false }; + struct archive_entry *e; + int r; + + while ((r = archive_read_next_header(a, &e)) == ARCHIVE_OK) { + const char *path = archive_entry_pathname(e); + mode_t type = archive_entry_filetype(e); + bool dir = type == AE_IFDIR; + if (!path) { + gl_recipe_set_error("an entry has no path"); + goto out; + } + if ((!dir && type != AE_IFREG) || archive_entry_hardlink(e) || + archive_entry_symlink(e) || archive_entry_size(e) < 0) { + gl_recipe_set_error("%s is not a regular file or directory", path); + goto out; + } + total += archive_entry_size(e); + if (total > GL_BUNDLE_MAX) { + gl_recipe_set_error("its files add up to more than %d bytes", + GL_BUNDLE_MAX); + goto out; + } + + /* "TOP/rel", a directory possibly with a trailing '/'. */ + char p[PATH_MAX]; + size_t l = strlen(path); + if (l == 0 || l >= sizeof p) { + gl_recipe_set_error("an entry's path is empty or too long"); + goto out; + } + memcpy(p, path, l + 1); + if (dir && p[l - 1] == '/') + p[--l] = '\0'; + char *slash = strchr(p, '/'); + const char *rel = slash ? slash + 1 : ""; + if (slash) + *slash = '\0'; + if (!gl_valid_pkg_ident(p)) { + gl_recipe_set_error("%s is not under a NAME-VER directory", path); + goto out; + } + if (*top && strcmp(top, p) != 0) { + gl_recipe_set_error("it has two top directories, %s and %s", top, p); + goto out; + } + snprintf(top, sizeof top, "%s", p); + + int kind = entry_kind(rel, dir); + if (kind < 0) { + gl_recipe_set_error("%s is not allowed (only recipe, build and " + "patches/FILE)", path); + goto out; + } + if (kind < 4) { + if (seen[kind]) { + gl_recipe_set_error("%s appears twice", path); + goto out; + } + seen[kind] = true; + } else { + /* One patch twice would be listed twice. */ + size_t fl = strlen(rel + 8); + if (patches && listed(patches, rel + 8)) { + gl_recipe_set_error("%s appears twice", path); + goto out; + } + char *grown = realloc(patches, plen + fl + 2); + if (!grown) { + gl_recipe_set_error("out of memory"); + st = GL_RECIPE_ERR_NOMEM; + goto out; + } + patches = grown; + memcpy(patches + plen, rel + 8, fl); + patches[plen + fl] = '\n'; + plen += fl + 1; + patches[plen] = '\0'; + } + + if (kind == 1) { + if (archive_entry_size(e) > GL_RECIPE_MAX) { + gl_recipe_set_error("the recipe is larger than %d bytes", + GL_RECIPE_MAX); + goto out; + } + rlen = (size_t)archive_entry_size(e); + if (!(recipe = malloc(rlen + 1))) { + gl_recipe_set_error("out of memory"); + st = GL_RECIPE_ERR_NOMEM; + goto out; + } + la_ssize_t got = rlen ? archive_read_data(a, recipe, rlen) : 0; + if (got < 0 || (size_t)got != rlen) { + gl_recipe_set_error("cannot read %s", path); + st = GL_RECIPE_ERR_READ; + goto out; + } + recipe[rlen] = '\0'; + } else if (archive_read_data_skip(a) != ARCHIVE_OK) { + gl_recipe_set_error("cannot read %s", path); + st = GL_RECIPE_ERR_READ; + goto out; + } + } + if (r != ARCHIVE_EOF) { + gl_recipe_set_error("not a readable gzip tar (%s)", archive_error_string(a) ? + archive_error_string(a) : "truncated"); + st = GL_RECIPE_ERR_READ; + goto out; + } + if (!recipe) { + gl_recipe_set_error("it has no recipe"); + goto out; + } + + st = gl_recipe_parse(recipe, rlen, out); + if (st != GL_RECIPE_OK) + goto out; + + char want[PATH_MAX]; + snprintf(want, sizeof want, "%s-%s", out->name, out->ver); + bool ok = strcmp(top, want) == 0; + if (!ok) + gl_recipe_set_error("its top directory is %s, but the recipe says %s", + top, want); + else if (!(ok = strcmp(out->build, "hooks") != 0 || seen[2])) + gl_recipe_set_error("BUILD = \"hooks\" needs a build file"); + /* The patches present are exactly the ones PATCHES lists. */ + size_t listed_n = 0, present_n = 0; + for (const char *q = out->patches; ok && *q; q = strchr(q, '\n') + 1) { + char f[PATH_MAX]; + size_t fl = (size_t)(strchr(q, '\n') - q); + snprintf(f, sizeof f, "%.*s", (int)fl, q); + if (!(ok = patches && listed(patches, f))) + gl_recipe_set_error("PATCHES lists %s, but there is no patches/%s", + f, f); + listed_n++; + } + for (const char *q = patches; ok && q && *q; q = strchr(q, '\n') + 1) + present_n++; + for (const char *q = patches; ok && listed_n != present_n && q && *q; + q = strchr(q, '\n') + 1) { + char f[PATH_MAX]; + snprintf(f, sizeof f, "%.*s", (int)(strchr(q, '\n') - q), q); + if (!listed(out->patches, f)) { + gl_recipe_set_error("patches/%s is not in PATCHES", f); + break; + } + } + if (!ok || listed_n != present_n) { + gl_recipe_free(out); + st = GL_RECIPE_ERR_BUNDLE; + } +out: + free(recipe); + free(patches); + archive_read_free(a); + return st; +} diff --git a/src/recipe.h b/src/recipe.h new file mode 100644 index 0000000..558dc04 --- /dev/null +++ b/src/recipe.h @@ -0,0 +1,15 @@ +#ifndef RECIPE_H_ +#define RECIPE_H_ + +#include "pkg.h" + +/* The largest recipe bundle, by the sum of its entries' sizes. */ +#define GL_BUNDLE_MAX (16 * 1024 * 1024) + +gl_recipe_status_t gl_recipe_read(const char *bundle, gl_recipe_t *out); + +/* Set what gl_recipe_error returns (internal: pkg.c and recipe.c). + * Always returns false. */ +bool gl_recipe_set_error(const char *fmt, ...) __attribute__((format(printf, 1, 2))); + +#endif diff --git a/src/report.c b/src/report.c deleted file mode 100644 index 47a70bf..0000000 --- a/src/report.c +++ /dev/null @@ -1,4 +0,0 @@ -#define _POSIX_C_SOURCE 200809L -#define _DEFAULT_SOURCE -#define _XOPEN_SOURCE 700 - diff --git a/src/test_backup.c b/src/test_backup.c deleted file mode 100644 index 11429d6..0000000 --- a/src/test_backup.c +++ /dev/null @@ -1,17 +0,0 @@ -#include - -#include "istoreutils.h" - -int -main(int argc, char *argv[]) -{ - gl_backup_status_t status = gl_backup_istore("/tmp/backup.tar", - "/home/lw/Projects/glacier-ng/tree/glacier", - "1000" - ); - - if (status != GL_BACKUP_OK) { - printf("backup failed: %d\n", status); - } - return 0; -} diff --git a/src/test_deps.c b/src/test_deps.c deleted file mode 100644 index c1b8de0..0000000 --- a/src/test_deps.c +++ /dev/null @@ -1,2 +0,0 @@ -#include "dag.h" -#include diff --git a/src/transaction.c b/src/transaction.c index 668f5e5..19038fc 100644 --- a/src/transaction.c +++ b/src/transaction.c @@ -411,6 +411,50 @@ gl_scope_state_dir(const gl_context_t *ctx, const char *name, char *out) return checked_subdir(base, name, owner, mode, out); } +/* + * /build/NAME: where source builds keep their state + * (BUILD_DESIGN.txt section 6). /build is made and checked as + * gl_scope_state_dir makes and checks NAME. With owner -1, NAME is the + * scope's like it; with another uid (system scope only: BUILD_USER), + * NAME is created owned by that uid with mode 0700, and refused unless + * it is a real directory owned by it with exactly that mode. 0, or -1 + * having printed why. + */ +int +gl_scope_build_dir(const gl_context_t *ctx, const char *name, int owner, char *out) +{ + char build[PATH_MAX]; + if (!ctx || !out || !gl_valid_pkg_ident(name) || + gl_scope_state_dir(ctx, "build", build) != 0) { + return -1; + } + uid_t scope_owner = ctx->scope == GL_SCOPE_SYS ? 0 : ctx->uid; + if (owner < 0 || (uid_t)owner == scope_owner) { + return checked_subdir(build, name, scope_owner, gl_scope_dir_mode(ctx->scope), out); + } + if (ctx->scope != GL_SCOPE_SYS || owner == 0) { + return -1; + } + snprintf(out, PATH_MAX, "%s/%s", build, name); + if (mkdir(out, 0700) == 0) { + if (chmod(out, 0700) != 0 || chown(out, (uid_t)owner, (gid_t)-1) != 0) { + lg_printf(2, "Cannot create %s: %s", out, strerror(errno)); + return -1; + } + } else if (errno != EEXIST) { + lg_printf(2, "Cannot create %s: %s", out, strerror(errno)); + return -1; + } + struct stat st; + if (lstat(out, &st) != 0 || !S_ISDIR(st.st_mode) || st.st_uid != (uid_t)owner || + (st.st_mode & 07777) != 0700) { + lg_printf(2, "Refusing %s: not a directory owned by UID %u with mode 700.", + out, (unsigned)owner); + return -1; + } + return 0; +} + /* * /cache/REPO: where packages fetched from REPO are downloaded * (REPO_DESIGN.txt section 5). Both levels are made and checked as diff --git a/src/transaction.h b/src/transaction.h index 63eb3f9..76150a6 100644 --- a/src/transaction.h +++ b/src/transaction.h @@ -130,6 +130,7 @@ gl_txn_status_t gl_init_stage_context_at(gl_context_t *ctx, gl_ctx_scope_t scope gl_txn_status_t gl_begin_transaction(gl_context_t *ctx); int gl_scope_state_dir(const gl_context_t *ctx, const char *name, char *out); int gl_scope_cache_dir(const gl_context_t *ctx, const char *repo, char *out); +int gl_scope_build_dir(const gl_context_t *ctx, const char *name, int owner, char *out); gl_txn_status_t gl_commit_transaction(gl_context_t *ctx); gl_txn_status_t gl_abort_transaction(gl_context_t *ctx);