eBPF-based security platform
bpm: confine package installation to the boot state directory
KP Singh91d0d3dea36f
diff --git a/Documentation/contribute/testing/proof-coverage.rst b/Documentation/contribute/testing/proof-coverage.rstindex a9a7cb83..0a84c1df 100644--- a/Documentation/contribute/testing/proof-coverage.rst+++ b/Documentation/contribute/testing/proof-coverage.rst@@ -1617,7 +1617,8 @@ a proof covers.* - Files- Why no proof reads them- * - :src:`util/bpm_cleanup.c`, :src:`util/harden.c`, :src:`util/identity.c`,+ * - :src:`util/bpm_cleanup.c`, :src:`util/bpm_install.c`,+ :src:`util/harden.c`, :src:`util/identity.c`,:src:`util/image_cache.c`, :src:`util/image_config.c`,:src:`util/image_guards.c`, :src:`util/image_keys.c`,:src:`util/image_runtime.c`, :src:`util/initrd.c`,diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex 76f1d951..955c621e 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -873,6 +873,14 @@ signed config image.of root's, uninstall refuses and the pins, the archive and thestate stay. Without a bind it detaches the link and retires thepackage tree, archive and state.+ * - ``t7116-bpm-package-install``+ - BPM installs a signed upatch from the fixture registry and keeps+ the archive beside the version. With a sealed directory bound+ over the staging directory or the package store, or the private+ bpffs bound over the store, in a mount namespace of root's,+ install refuses: neither the archive nor the version lands in+ what the bind shows, nothing is loaded and no state is written.+ Without a bind it installs again.``otel`` (8)~~~~~~~~~~~~@@ -1041,8 +1049,9 @@ OCI registry. The macOS workflow checks the Lima template withUnit suites and fuzz targets~~~~~~~~~~~~~~~~~~~~~~~~~~~~-The unit suites in :src:`testing/unit/` cover 44 of the modules in-:src:`util/`: ``attest``, ``bpm_cleanup``, ``bpm_oci``, ``bpm_package``, ``bpm_state``,+The unit suites in :src:`testing/unit/` cover 45 of the modules in+:src:`util/`: ``attest``, ``bpm_cleanup``, ``bpm_install``, ``bpm_oci``,+``bpm_package``, ``bpm_state``,``bpm_tree``, ``bpm_tree_overlap``, ``bpm_tree_state``, ``chain``,``chain_history``, ``conditions``, ``config_update``, ``crypto_openssl``,``curl``, ``eventlog``, ``format``, ``hex``, ``identity``, ``io``,diff --git a/Documentation/reference/cli/bpm.rst b/Documentation/reference/cli/bpm.rstindex 55dd6f92..2f3ea4e9 100644--- a/Documentation/reference/cli/bpm.rst+++ b/Documentation/reference/cli/bpm.rst@@ -551,6 +551,17 @@ For each package ``install`` and ``upgrade``:--no-precheck`` does, each load measured.#. Record the package in ``/var/lib/shirudo/bpm/state.json``.+Both open the package's directory and ``/var/lib/shirudo/bpm/staging``+once, below the state directory whose device and inode init recorded,+and reach the downloaded archive, the extracted version, its+``cert.der`` and its members from those directories. The package digest+is computed from the descriptor the download was written through, and+the extraction reads that same descriptor. A mount below the state root+stops the install with ``Invalid cross-device link``, a bind on the same+file system and one file bound over another included. A symbolic link or+an entry without the seal label stops it too. The version a failed+install extracted is removed again.+``upgrade`` takes no argument. For every package not installed ``direct``it installs the greatest version in the cached index when that version isgreater than the installed one: it unloads the old version with its@@ -566,8 +577,8 @@ and reads each from the descriptor it checked. A load member without itsdirective stops uninstall. Cleanup removes load members before theirdirectives, so an interrupted uninstall can finish on a retry. Successfuluninstall removes the whole package directory, including archives and-older versions left by upgrades. Uninstall and failed-install cleanup-refuse to cross mounts below the state root.+older versions left by upgrades. Uninstall refuses to cross mounts below+the state root, as install and upgrade do.``list`` prints the installed packages under the heading ``Installedpackages:`` as a table with the columns ``NAME``, ``VERSION`` anddiff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rstindex 08659da1..d40d1896 100644--- a/Documentation/security/threat-model.rst+++ b/Documentation/security/threat-model.rst@@ -2009,11 +2009,18 @@ R22 Labeled inodes are interchangeableroot directory itself. Init records its device and inode in the frozenidentity map before enforcement starts. BPM verifies both on the opendirectory, which also has to carry the seal and reside outside bpffs.- Package uninstall opens its directives and removes the package tree- relative to held directory descriptors. Those lookups and failed-install- cleanup reject mount crossings below the state root, including binds on- the same file system. BPM reads and replaces its package state file- relative to the verified BPM directory as well.+ Package install and upgrade stage the archive, extract the version,+ read its certificate, load its members and unload the version they+ replace relative to directories they open once below that root. The+ digest they check is of the bytes the extraction reads, taken from+ the descriptor that wrote them. Package uninstall opens its+ directives and removes the package tree relative to held directory+ descriptors. Those lookups reject mount crossings below the state+ root, including binds on the same file system and one file bound over+ another (``t7115``, ``t7116``). BPM reads and replaces its package+ state file relative to the verified BPM directory as well. ``bpm tree+ sync`` still names the artifact it checks and then loads by its path+ in the cache.R23 Policy labels follow the inodeA policy label is an xattr of the executable's inode, applied atdiff --git a/Makefile.shirudo b/Makefile.shirudoindex cfb068e7..31d65ff5 100644--- a/Makefile.shirudo+++ b/Makefile.shirudo@@ -270,6 +270,7 @@ UTIL_SRCS := \util/bpm_oci.c \util/curl.c \util/bpm_cleanup.c \+ util/bpm_install.c \util/bpm_package.c \util/bpm_state.c \util/kconfig.c \diff --git a/builtin-bpm.c b/builtin-bpm.cindex f21e6e5b..d0f209db 100644--- a/builtin-bpm.c+++ b/builtin-bpm.c@@ -34,6 +34,7 @@#include "builtin.h"#include "util/bpm_cleanup.h"+#include "util/bpm_install.h"#include "util/bpm_oci.h"#include "util/bpm_package.h"#include "util/bpm_state.h"@@ -69,7 +70,6 @@ struct bpm_source {char key_file[BPM_MAX_KEY];};-static int sha256_file_hex(const char *path, char *hex, size_t hex_sz);static int sha256_fd_hex(int fd, char *hex, size_t hex_sz);/** -ENODEV, not -ENOENT, without the identity init pins: callers take@@ -91,22 +91,6 @@ static int package_store_open(void)return packages;}-static int remove_partial_version(const char *name, const char *version)-{- int store, package, ret;-- store = package_store_open();- if (store < 0)- return store;- package = seal_open_child(store, name, O_RDONLY | O_DIRECTORY);- close(store);- if (package < 0)- return package;- ret = bpm_pkg_remove_at(package, version);- close(package);- return ret;-}-static int prepare_direct_install(const char *raw, struct bpm_source *source,struct bpm_index_entry *entry){@@ -553,18 +537,6 @@ done:return ret;}-static int sha256_file_hex(const char *path, char *hex, size_t hex_sz)-{- int fd, ret;-- fd = open(path, O_RDONLY | O_CLOEXEC);- if (fd < 0)- return -errno;- ret = sha256_fd_hex(fd, hex, hex_sz);- close(fd);- return ret;-}-/** A package the operator names, open for reading: the local file, or* the download in memory. Never a file of /tmp, which root can bind to a@@ -779,20 +751,6 @@ static int cert_matches_active(const __u8 *der, size_t len)return ret;}-static int cert_file_matches_active(const char *path)-{- size_t len = 0;- __u8 *der;- int ret;-- ret = keys_read_der(path, &der, &len);- if (ret)- return ret;- ret = cert_matches_active(der, len);- xfree(der, len);- return ret;-}-static int key_fingerprint(const __u8 *der, size_t len, char hex[65]){__u8 digest[CRYPTO_SHA256_LEN];@@ -1156,55 +1114,69 @@ static int find_entry(const struct bpm_index_entry *e, int n, const char *name,return 0;}-static int path_compare(const void *left, const void *right)+/* 0 when the certificate the extracted version ships is the active one. */+static int install_cert_matches_active(const struct bpm_install *in){- return strcmp(left, right);+ size_t len = 0;+ __u8 *der;+ int fd, ret;++ fd = bpm_install_member(in, "cert.der");+ if (fd < 0)+ return fd;+ ret = keys_read_der_fd(fd, &der, &len);+ close(fd);+ if (ret)+ return ret;+ ret = cert_matches_active(der, len);+ xfree(der, len + 1);+ return ret;}/*- * The old version's unload directives in reverse name order, as- * uninstall runs them, each kept beside the load it undoes.+ * One package layer: staged, checked against its digest, extracted,+ * loaded and kept, through directories opened once below the state root+ * init recorded. The digest is of the bytes the extraction then reads,+ * taken from the descriptor that wrote them.*/-static void sort_old_pairs(char (*unloads)[PATH_MAX], char (*loads)[PATH_MAX],- int n)-{- char tmp[PATH_MAX];-- for (int i = 1; i < n; i++) {- for (int j = i; j > 0 && strcmp(unloads[j - 1], unloads[j]) < 0;- j--) {- memcpy(tmp, unloads[j], PATH_MAX);- memcpy(unloads[j], unloads[j - 1], PATH_MAX);- memcpy(unloads[j - 1], tmp, PATH_MAX);- memcpy(tmp, loads[j], PATH_MAX);- memcpy(loads[j], loads[j - 1], PATH_MAX);- memcpy(loads[j - 1], tmp, PATH_MAX);- }- }+static int install_layer(struct bpm_oci_client *c, const char *url,+ const struct bpm_descriptor *layer,+ const struct bpm_index_entry *entry,+ const char *old_version)+{+ struct bpm_install in;+ char digest[65];+ int root, ret;++ root = state_root_open();+ if (root < 0)+ return root == -ENOENT ? -ENODEV : root;+ ret = bpm_install_open(&in, root, entry->name, entry->version);+ close(root);+ if (!ret)+ ret = bpm_oci_get_file(c, url, BPM_PACKAGE_MEDIA, in.archive,+ layer->size);+ if (!ret && (sha256_fd_hex(in.archive, digest, sizeof(digest)) ||+ !bpm_digest_matches(layer->digest, digest)))+ ret = -EKEYREJECTED;+ if (!ret)+ ret = bpm_install_extract(&in);+ if (!ret && install_cert_matches_active(&in))+ ret = -EKEYREJECTED;+ if (!ret)+ ret = bpm_install_load(&in, old_version);+ return bpm_install_close(&in, ret);}static int package_install(const struct bpm_source *s, const struct bpm_index_entry *entry,- const char *old_path, const char *old_version)+ const char *old_version){struct bpm_oci_client c __cleanup(bpm_oci_client_clear) = {};struct bpm_descriptor layers[8];- int nl = 0;struct bpm_buffer manifest = {};- char url[PATH_MAX], archive[PATH_MAX] = {}, dir[PATH_MAX], package_dir[PATH_MAX];- char digest[65];- int fd, ret;- DIR *d;- struct dirent *de;- bool found_package = false, extracted = false;- char (*loaded)[PATH_MAX], (*old_loads)[PATH_MAX], (*old_unloads)[PATH_MAX];- int nloaded = 0, nactive = 0, nold = 0, nold_removed = 0;-- /* 1.5 MiB of paths, which a stack frame should not carry. */- loaded = xcalloc(3 * BPM_MAX_UPATCHES, PATH_MAX);- if (!loaded)- return -ENOMEM;- old_loads = loaded + BPM_MAX_UPATCHES;- old_unloads = old_loads + BPM_MAX_UPATCHES;+ char url[PATH_MAX];+ int nl = 0, ret;+ret = bpm_oci_parse_endpoint(s->endpoint, &c);if (ret)goto out;@@ -1236,7 +1208,6 @@ static int package_install(const struct bpm_source *s, const struct bpm_index_enfor (int i = 0; i < nl; i++) {if (strcmp(layers[i].media, BPM_PACKAGE_MEDIA))continue;- found_package = true;if (entry->package_digest[0] && strcmp(entry->package_digest, layers[i].digest)) {ret = -EKEYREJECTED;goto out;@@ -1247,214 +1218,14 @@ static int package_install(const struct bpm_source *s, const struct bpm_index_en}ret = bpm_oci_url(&c, entry->repository[0] ? entry->repository : entry->name,"blobs", layers[i].digest, url, sizeof(url));- if (ret)- goto out;- if (strsprintf(dir, sizeof(dir), "%s/%s", BPM_PACKAGES_DIR,- entry->name) < 0) {- ret = -ENAMETOOLONG;- goto out;- }- ret = seal_mkdir_p(dir, 0700);- if (ret)- goto out;- if (strsprintf(package_dir, sizeof(package_dir), "%s/%s", dir,- entry->version) < 0) {- ret = -ENAMETOOLONG;- goto out;- }- ret = seal_mkdir_p(BPM_STAGING_DIR, 0700);- if (ret)- goto out;- if (strsprintf(archive, sizeof(archive), "%s/%s-%s.bee",- BPM_STAGING_DIR, entry->name,- entry->version) < 0) {- ret = -ENAMETOOLONG;- goto out;- }- fd = seal_open(archive, O_WRONLY | O_CREAT | O_TRUNC |- O_NOFOLLOW, 0600);- if (fd < 0) {- ret = fd;- goto out;- }- ret = bpm_oci_get_file(&c, url, BPM_PACKAGE_MEDIA, fd,- layers[i].size);- close(fd);- if (ret) {- unlink(archive);- goto out;- }- if (sha256_file_hex(archive, digest, sizeof(digest)) ||- !bpm_digest_matches(layers[i].digest, digest)) {- ret = -EKEYREJECTED;- goto out;- }- if (access(package_dir, F_OK) == 0) {- ret = -EEXIST;- goto out;- }- extracted = true;- ret = bpm_pkg_extract(archive, package_dir);- if (ret)- goto out;- {- char cert[PATH_MAX];-- if (strsprintf(cert, sizeof(cert), "%s/cert.der",- package_dir) < 0) {- ret = -ENAMETOOLONG;- goto out;- }- if (cert_file_matches_active(cert)) {- ret = -EKEYREJECTED;- goto out;- }- }- {- char updir[PATH_MAX];-- if (strsprintf(updir, sizeof(updir), "%s/upatches",- package_dir) < 0) {- ret = -ENAMETOOLONG;- goto out;- }- d = opendir(updir);- if (!d) {- ret = -errno;- goto out;- }- }- while ((de = readdir(d))) {- char up[PATH_MAX];- struct stat st;-- if (bpm_upatch_member(de->d_name, strlen(de->d_name)) !=- BPM_UPATCH_LOAD)- continue;- if (strsprintf(up, sizeof(up), "%s/upatches/%s", package_dir,- de->d_name) < 0) {- ret = -ENAMETOOLONG;- break;- }- if (stat(up, &st) || !S_ISREG(st.st_mode))- continue;- if (nloaded >= BPM_MAX_UPATCHES) {- ret = -E2BIG;- break;- }- if (strscpy(loaded[nloaded], up,- sizeof(loaded[nloaded])) < 0) {- ret = -ENAMETOOLONG;- break;- }- nloaded++;- }- closedir(d);- if (ret || !nloaded) {- if (!ret)- ret = -EINVAL;- goto out;- }- /* Measured in name order, not in the file system's. */- qsort(loaded, (size_t)nloaded, sizeof(loaded[0]), path_compare);- if (old_path && old_path[0]) {- char olddir[PATH_MAX];-- if (strsprintf(olddir, sizeof(olddir), "%s/upatches",- old_path) < 0) {- ret = -ENAMETOOLONG;- goto out;- }- d = opendir(olddir);- if (d) {- while ((de = readdir(d))) {- size_t len = strlen(de->d_name);- char load[NAME_MAX + 1];-- if (bpm_upatch_member(de->d_name, len) !=- BPM_UPATCH_UNLOAD || nold >= BPM_MAX_UPATCHES)- continue;- if (bpm_upatch_pair(de->d_name, len, load,- sizeof(load)) ||- strsprintf(old_unloads[nold],- sizeof(old_unloads[nold]), "%s/%s",- olddir, de->d_name) < 0 ||- strsprintf(old_loads[nold],- sizeof(old_loads[nold]), "%s/%s",- olddir, load) < 0) {- ret = -ENAMETOOLONG;- break;- }- nold++;- }- closedir(d);- }- if (ret)- goto out;- sort_old_pairs(old_unloads, old_loads, nold);- for (int old_i = 0; old_i < nold; old_i++) {- if (upatch_remove(old_unloads[old_i])) {- ret = -EIO;- for (int restore_i = nold_removed - 1;- restore_i >= 0; restore_i--)- upatch_install(old_loads[restore_i]);- goto out;- }- nold_removed++;- }- }- for (int loaded_i = 0; loaded_i < nloaded; loaded_i++) {- if (upatch_install(loaded[loaded_i])) {- ret = -EIO;- goto rollback;- }- nactive++;- }- {- char saved[PATH_MAX];-- if (strsprintf(saved, sizeof(saved), "%s/%s-%s.bee", dir,- entry->name, entry->version) < 0 ||- rename(archive, saved)) {- pr_warn("bpm: cannot keep %s; dropping it",- archive);- unlink(archive);- }- }- break;- }- if (!ret && !found_package)- ret = -EINVAL;- goto out;-rollback:- for (int active_i = nactive - 1; active_i >= 0; active_i--) {- const char *base = strrchr(loaded[active_i], '/');- char unload[PATH_MAX], name[NAME_MAX + 1];-- if (!base ||- bpm_upatch_pair(base + 1, strlen(base + 1), name,- sizeof(name)) ||- strsprintf(unload, sizeof(unload), "%.*s/%s",- (int)(base - loaded[active_i]), loaded[active_i],- name) < 0)- continue;- upatch_remove(unload);+ if (!ret)+ ret = install_layer(&c, url, &layers[i], entry,+ old_version);+ goto out;}- for (int restore_i = nold - 1; restore_i >= 0; restore_i--)- upatch_install(old_loads[restore_i]);+ ret = -EINVAL;out:bpm_buffer_free(&manifest);- if (ret && archive[0])- unlink(archive);- /* What failed to install must not block the next attempt. */- if (ret && extracted) {- int err = remove_partial_version(entry->name, entry->version);-- if (err && err != -ENOENT)- pr_warn("bpm install: could not clean up %s: %s",- package_dir, strerror(-err));- }- xfree(loaded, 3 * BPM_MAX_UPATCHES * PATH_MAX);return ret;}@@ -3038,7 +2809,7 @@ static int bpm_install(const char *ref, struct bpm_tables *t)return bpm_finish(lock, ret, "install");if (n_state >= BPM_MAX_STATE)return bpm_finish(lock, -E2BIG, "install");- ret = package_install(&source_cfg, &selected, NULL, NULL);+ ret = package_install(&source_cfg, &selected, NULL);if (ret)return bpm_finish(lock, ret, "install");bpm_copy_string(state[n_state].name, sizeof(state[n_state].name),@@ -3104,7 +2875,7 @@ static int bpm_upgrade(const char *unused, struct bpm_tables *t)break;if (bpm_semver_compare(selected.version, state[i].version) <= 0)continue;- ret = package_install(&source_cfg, &selected, state[i].path,+ ret = package_install(&source_cfg, &selected,state[i].version);if (ret)break;diff --git a/builtin-upatch.c b/builtin-upatch.cindex e9003743..98d1bab7 100644--- a/builtin-upatch.c+++ b/builtin-upatch.c@@ -3574,7 +3574,8 @@ struct load_args {bool loaded_is_done;};-static int upatch_load(const struct load_args *args)+/* fd, when it is one, is the file to read; args->file then only names it. */+static int upatch_load(const struct load_args *args, int fd){const char *file = args->file, *report = args->report;char name[UPATCH_NAME_MAX + 1] = {};@@ -3592,7 +3593,7 @@ static int upatch_load(const struct load_args *args)"load") != 0)goto done;- err = read_upatch(file, -1, &buf, &len, &u);+ err = read_upatch(file, fd, &buf, &len, &u);if (err) {pr_err("upatch load: read %s: %s", file, strerror(-err));rep_fail(&rep, "parse", "parser_rejected", -err,@@ -3731,7 +3732,7 @@ static int cmd_upatch_load(int argc, const char **argv)&args.no_version_check, &args.report);if (err)return err == OPT_DONE ? 0 : err;- return upatch_load(&args);+ return upatch_load(&args, -1);}/*@@ -4223,7 +4224,7 @@ int upatch_purge(const char *name, const struct cert *signer,* Package installs take the same path as the upatch commands, and take* the payload already loaded under the name for one done.*/-int upatch_install(const char *path)+int upatch_install_fd(const char *path, int fd){const struct load_args args = {.file = path,@@ -4231,7 +4232,12 @@ int upatch_install(const char *path).loaded_is_done = true,};- return upatch_load(&args);+ return upatch_load(&args, fd);+}++int upatch_install(const char *path)+{+ return upatch_install_fd(path, -1);}int upatch_remove_fd(const char *path, int fd)diff --git a/testing/functional/bpm/t7116-bpm-package-install.sh b/testing/functional/bpm/t7116-bpm-package-install.shnew file mode 100755index 00000000..0aa65827--- /dev/null+++ b/testing/functional/bpm/t7116-bpm-package-install.sh@@ -0,0 +1,104 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t7116 -- bpm install works below the state root init recorded, through+# directories it opens once. A directory root binds over one of them is+# not followed: the install stops, and neither the archive nor the+# version lands in what the bind shows, nor is anything loaded from it.++cd "$(dirname "$0")/../.."+. ./integration-lib.sh+target_guard++WORK=$(mktemp -d)+PKG=install-fixture+NAME=shirudo-test-lifecycle+VERSION=1.0.0+ARCHIVE=$PKG-$VERSION+TREE=$WORK/$ARCHIVE+REPO=$WORK/registry/test/$PKG+REF=oci://127.0.0.1:5443/test/$PKG:$VERSION+BPM=/var/lib/shirudo/bpm+STORE=$BPM/packages/$PKG+SEALED=/var/lib/shirudo/upatches+PIN=/run/shirudo/bpffs/upatches/$NAME/link+TREE_SERVER_PID=++cleanup() {+ tree_registry_stop+ rm -rf "$WORK"+}+trap cleanup EXIT++mkdir -p "$TREE/upatches" "$REPO/manifests" "$REPO/blobs"+cp /var/lib/shirudo/keys/cert.der "$TREE/"+cp "$SHIRUDO_TEST_FIXTURES_DIR/$NAME.upatch" \+ "$SHIRUDO_TEST_FIXTURES_DIR/$NAME.unload.upatch" "$TREE/upatches/"+printf '[package]\nname = "%s"\n' "$PKG" >"$TREE/Beefile"+tar --format=ustar -czf "$WORK/package.bee" -C "$WORK" "$ARCHIVE"+digest=sha256:$(sha256sum "$WORK/package.bee" | cut -d' ' -f1)+size=$(wc -c <"$WORK/package.bee")+mv "$WORK/package.bee" "$REPO/blobs/$digest"+cat >"$REPO/manifests/$VERSION" <<EOF+{"schemaVersion":2,"layers":[{"mediaType":"application/vnd.shirudo.bpm.package.v1+gzip",+"digest":"$digest","size":$size}]}+EOF++tree_registry_start "$WORK/registry" "$WORK"+export BPM_OCI_SCHEME=http NO_PROXY=127.0.0.1 no_proxy=127.0.0.1++test_expect_success 'install extracts the version, loads it and keeps the archive' '+ "$SHIRUDO_BIN" bpm install "$REF" &&+ test -e "$PIN" &&+ test -s "$STORE/$VERSION/upatches/$NAME.unload.upatch" &&+ test -f "$STORE/$ARCHIVE.bee" &&+ test ! -e "$BPM/staging/$ARCHIVE.bee" &&+ "$SHIRUDO_BIN" bpm uninstall "$PKG" &&+ test ! -e "$PIN" &&+ test ! -e "$STORE"+'++# The bind is made in a mount namespace of root's own, over a directory+# the first install left behind.+RUNTIME=$(runtime_binary)+bound_install() {+ unshare -m sh -c "mount --bind \"$1\" \"$2\" &&+ ! \"$RUNTIME\" bpm install \"$REF\"" >"$WORK/out" 2>&1+}+not_installed() {+ test ! -e "$PIN" &&+ test ! -e "$STORE/$VERSION" &&+ test ! -e "$SEALED/$ARCHIVE.bee" &&+ test ! -e "$SEALED/$PKG" &&+ test -e /run/shirudo/bpffs/lsm_link &&+ "$SHIRUDO_BIN" bpm list >"$WORK/list" &&+ ! grep -q "$PKG" "$WORK/list"+}++test_expect_success 'install refuses a sealed directory bound over the staging directory' '+ bound_install "$SEALED" "$BPM/staging" &&+ grep -q "cross-device" "$WORK/out" &&+ not_installed+'++test_expect_success 'and bound over the package store' '+ bound_install "$SEALED" "$BPM/packages" &&+ grep -q "cross-device" "$WORK/out" &&+ not_installed+'++test_expect_success 'and the private bpffs bound over the package store' '+ bound_install /run/shirudo/bpffs "$BPM/packages" &&+ not_installed+'++test_expect_success 'with no bind the install goes through again' '+ "$SHIRUDO_BIN" bpm install "$REF" &&+ test -e "$PIN" &&+ test -f "$STORE/$ARCHIVE.bee" &&+ "$SHIRUDO_BIN" bpm uninstall "$PKG" &&+ test ! -e "$PIN"+'++test_donediff --git a/testing/fuzz/fuzz-bpm-package.c b/testing/fuzz/fuzz-bpm-package.cindex 3fd86e79..8dada95e 100644--- a/testing/fuzz/fuzz-bpm-package.c+++ b/testing/fuzz/fuzz-bpm-package.c@@ -8,9 +8,11 @@#include <dirent.h>#include <errno.h>+#include <fcntl.h>#include <limits.h>#include <stdlib.h>#include <string.h>+#include <sys/stat.h>#include "bpm_package.h"#include "fuzz.h"@@ -70,14 +72,19 @@ int LLVMFuzzerTestOneInput(const __u8 *data, size_t size){struct bpm_package_info info = {};char path[64];- int fd;+ int fd, dir;fd = fuzz_gzip_file(data, size, path, sizeof(path));if (fd < 0)return 0;if (!bpm_pkg_load_info(path, &info))xfree(info.cert, info.cert_len + 1);- bpm_pkg_extract(path, dest);+ dir = mkdir(dest, 0700) ? -1 :+ open(dest, O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ if (dir >= 0) {+ bpm_pkg_extract(fd, dir);+ close(dir);+ }empty_base();close(fd);return 0;diff --git a/testing/unit/archive_test.h b/testing/unit/archive_test.hnew file mode 100644index 00000000..56bca7c3--- /dev/null+++ b/testing/unit/archive_test.h@@ -0,0 +1,61 @@+/* SPDX-License-Identifier: BSD-2-Clause */+/* Copyright (c) 2026 Authors of shirudo */++#ifndef SHIRUDO_TEST_ARCHIVE_H+#define SHIRUDO_TEST_ARCHIVE_H++#include <string.h>+#include <unistd.h>+#include <zlib.h>++#include <linux/types.h>++#include <shirudo/string.h>++#include "unit.h"++/* One member of a test .bee: of type '0' a file with body, of '5' a directory. */+struct archive_member {+ const char *name;+ char type;+ const char *body;+};++/* The members as a gzip'd ustar, which replaces what fd holds. */+static inline void archive_write(int fd, const struct archive_member *m, int n)+{+ static const __u8 zero[1024];+ gzFile gz;+ int copy;++ ASSERT_EQ(ftruncate(fd, 0), 0);+ ASSERT_EQ(lseek(fd, 0, SEEK_SET), 0);+ copy = dup(fd);+ ASSERT_TRUE(copy >= 0);+ gz = gzdopen(copy, "wb");+ ASSERT_TRUE(gz);+ for (int i = 0; i < n; i++) {+ __u32 len = m[i].body ? (__u32)strlen(m[i].body) : 0;+ __u32 pad = (512 - len % 512) % 512, sum = 0;+ __u8 h[512] = {};++ ASSERT_TRUE(strsprintf((char *)h, 100, "%s", m[i].name) > 0);+ ASSERT_TRUE(strsprintf((char *)h + 100, 8, "%07o", 0644) > 0);+ ASSERT_TRUE(strsprintf((char *)h + 124, 12, "%011o", len) > 0);+ memset(h + 148, ' ', 8);+ h[156] = (__u8)m[i].type;+ memcpy(h + 257, "ustar", 6);+ for (size_t j = 0; j < sizeof(h); j++)+ sum += h[j];+ ASSERT_TRUE(strsprintf((char *)h + 148, 7, "%06o", sum) > 0);+ ASSERT_EQ(gzwrite(gz, h, sizeof(h)), (int)sizeof(h));+ if (len)+ ASSERT_EQ(gzwrite(gz, m[i].body, len), (int)len);+ if (pad)+ ASSERT_EQ(gzwrite(gz, zero, pad), (int)pad);+ }+ ASSERT_EQ(gzwrite(gz, zero, sizeof(zero)), (int)sizeof(zero));+ ASSERT_EQ(gzclose(gz), Z_OK);+}++#endif /* SHIRUDO_TEST_ARCHIVE_H */diff --git a/testing/unit/bpm_install.c b/testing/unit/bpm_install.cnew file mode 100644index 00000000..6e820200--- /dev/null+++ b/testing/unit/bpm_install.c@@ -0,0 +1,331 @@+// SPDX-License-Identifier: BSD-2-Clause+/* Copyright (c) 2026 Authors of shirudo */++#include <errno.h>+#include <fcntl.h>+#include <ftw.h>+#include <limits.h>+#include <sched.h>+#include <stdlib.h>+#include <string.h>+#include <sys/mount.h>+#include <sys/stat.h>+#include <unistd.h>++#include <shirudo/misc.h>+#include <shirudo/string.h>++#include "archive_test.h"+#include "bpm_install.h"+#include "upatch.h"+#include "unit.h"++/*+ * What the loader was asked for: +x a load of the member whose file+ * starts with x, -x an unload. A member that starts with refuse fails.+ */+static char order[32];+static char refuse;++static int record(char op, int fd)+{+ size_t n = strlen(order);+ char byte;++ if (n + 3 > sizeof(order) || pread(fd, &byte, 1, 0) != 1)+ return 1;+ order[n] = op;+ order[n + 1] = byte;+ return byte == refuse;+}++int upatch_install_fd(const char *path, int fd)+{+ return record('+', fd);+}++int upatch_remove_fd(const char *path, int fd)+{+ return record('-', fd);+}++/* A directory that stands for the state root. */+static char root_dir[PATH_MAX];+static int root = -1;++static void new_root(void)+{+ strscpy_literal(root_dir, "/tmp/shirudo-bpm-install-XXXXXX");+ ASSERT_TRUE(mkdtemp(root_dir));+ root = open(root_dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ ASSERT_TRUE(root >= 0);+ memset(order, 0, sizeof(order));+ refuse = 0;+}++static int remove_entry(const char *path, const struct stat *st, int type,+ struct FTW *ftw)+{+ return remove(path);+}++static void remove_root(void)+{+ close(root);+ ASSERT_EQ(nftw(root_dir, remove_entry, 16, FTW_DEPTH | FTW_PHYS), 0);+}++static void make_dir(const char *path)+{+ char buf[PATH_MAX], *slash;++ ASSERT_TRUE(strscpy(buf, path, sizeof(buf)) > 0);+ for (slash = strchr(buf, '/'); slash; slash = strchr(slash + 1, '/')) {+ *slash = '\0';+ ASSERT_TRUE(!mkdirat(root, buf, 0700) || errno == EEXIST);+ *slash = '/';+ }+ ASSERT_TRUE(!mkdirat(root, buf, 0700) || errno == EEXIST);+}++static void put_file(const char *path, char byte)+{+ int fd = openat(root, path, O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0600);++ ASSERT_TRUE(fd >= 0);+ ASSERT_EQ(write(fd, &byte, 1), 1);+ ASSERT_EQ(close(fd), 0);+}++static bool there(const char *path)+{+ return !faccessat(root, path, F_OK, AT_SYMLINK_NOFOLLOW);+}++static const struct archive_member version_2[] = {+ { "sample-2/", '5', NULL },+ { "sample-2/cert.der", '0', "C" },+ { "sample-2/upatches/b.upatch", '0', "b" },+ { "sample-2/upatches/b.unload.upatch", '0', "B" },+ { "sample-2/upatches/a.upatch", '0', "a" },+ { "sample-2/upatches/a.unload.upatch", '0', "A" },+ { "sample-2/doc/notes/readme", '0', "n" },+};++static void open_and_extract(struct bpm_install *in)+{+ ASSERT_EQ(bpm_install_open(in, root, "sample", "2"), 0);+ archive_write(in->archive, version_2, ARRAY_SIZE(version_2));+ ASSERT_EQ(bpm_install_extract(in), 0);+}++/* Version 1, which loaded p and q and ships the directives P and Q. */+static void old_version(void)+{+ make_dir("bpm/packages/sample/1/upatches");+ put_file("bpm/packages/sample/1/upatches/a.upatch", 'p');+ put_file("bpm/packages/sample/1/upatches/a.unload.upatch", 'P');+ put_file("bpm/packages/sample/1/upatches/c.upatch", 'q');+ put_file("bpm/packages/sample/1/upatches/c.unload.upatch", 'Q');+}++static void install_loads_in_name_order_and_keeps_the_archive(void)+{+ struct bpm_install in;+ struct stat st;+ char byte = 0;+ int fd;++ new_root();+ ASSERT_EQ(bpm_install_open(&in, root, "sample", "2"), 0);+ EXPECT_TRUE(there("bpm/staging/sample-2.bee"));+ archive_write(in.archive, version_2, ARRAY_SIZE(version_2));+ ASSERT_EQ(bpm_install_extract(&in), 0);+ ASSERT_EQ(fstatat(root, "bpm/packages/sample/2/doc/notes/readme", &st, 0), 0);+ EXPECT_EQ(st.st_mode & 07777, 0644);+ fd = bpm_install_member(&in, "cert.der");+ ASSERT_TRUE(fd >= 0);+ EXPECT_EQ(read(fd, &byte, 1), 1);+ EXPECT_EQ(byte, 'C');+ close(fd);+ EXPECT_EQ(bpm_install_member(&in, "upatches/a.upatch"), -EINVAL);+ ASSERT_EQ(bpm_install_load(&in, NULL), 0);+ EXPECT_STREQ(order, "+a+b");+ ASSERT_EQ(bpm_install_close(&in, 0), 0);+ EXPECT_TRUE(there("bpm/packages/sample/sample-2.bee"));+ EXPECT_FALSE(there("bpm/staging/sample-2.bee"));+ remove_root();+}++static void a_version_already_there_is_left_as_it_is(void)+{+ struct bpm_install in;++ new_root();+ make_dir("bpm/packages/sample/2");+ put_file("bpm/packages/sample/2/keep", 'k');+ ASSERT_EQ(bpm_install_open(&in, root, "sample", "2"), 0);+ archive_write(in.archive, version_2, ARRAY_SIZE(version_2));+ EXPECT_EQ(bpm_install_extract(&in), -EEXIST);+ EXPECT_EQ(bpm_install_close(&in, -EEXIST), -EEXIST);+ EXPECT_TRUE(there("bpm/packages/sample/2/keep"));+ EXPECT_FALSE(there("bpm/staging/sample-2.bee"));+ remove_root();+}++static void a_name_that_is_no_single_entry_is_refused(void)+{+ struct bpm_install in;++ new_root();+ EXPECT_EQ(bpm_install_open(&in, root, "..", "2"), -EINVAL);+ EXPECT_EQ(bpm_install_close(&in, -EINVAL), -EINVAL);+ EXPECT_EQ(bpm_install_open(&in, root, "sample", "../2"), -EINVAL);+ EXPECT_EQ(bpm_install_close(&in, -EINVAL), -EINVAL);+ EXPECT_FALSE(there("bpm"));+ remove_root();+}++static void a_refused_load_is_undone_and_the_version_removed(void)+{+ struct bpm_install in;++ new_root();+ open_and_extract(&in);+ refuse = 'b';+ EXPECT_EQ(bpm_install_load(&in, NULL), -EIO);+ EXPECT_STREQ(order, "+a+b-A");+ EXPECT_EQ(bpm_install_close(&in, -EIO), -EIO);+ EXPECT_FALSE(there("bpm/packages/sample/2"));+ EXPECT_FALSE(there("bpm/staging/sample-2.bee"));+ EXPECT_TRUE(there("bpm/packages/sample"));+ remove_root();+}++static void an_upgrade_unloads_the_old_version_first(void)+{+ struct bpm_install in;++ new_root();+ old_version();+ open_and_extract(&in);+ ASSERT_EQ(bpm_install_load(&in, "1"), 0);+ EXPECT_STREQ(order, "-Q-P+a+b");+ memset(order, 0, sizeof(order));+ /* A version that is not there has nothing to unload. */+ ASSERT_EQ(bpm_install_load(&in, "0"), 0);+ EXPECT_STREQ(order, "+a+b");+ ASSERT_EQ(bpm_install_close(&in, 0), 0);+ EXPECT_TRUE(there("bpm/packages/sample/1/upatches/a.upatch"));+ remove_root();+}++static void a_failed_upgrade_loads_the_old_version_again(void)+{+ struct bpm_install in;++ new_root();+ old_version();+ open_and_extract(&in);+ refuse = 'b';+ EXPECT_EQ(bpm_install_load(&in, "1"), -EIO);+ EXPECT_STREQ(order, "-Q-P+a+b-A+p+q");+ /* A directive that fails leaves the ones after it alone. */+ memset(order, 0, sizeof(order));+ refuse = 'P';+ EXPECT_EQ(bpm_install_load(&in, "1"), -EIO);+ EXPECT_STREQ(order, "-Q-P+q");+ EXPECT_EQ(bpm_install_close(&in, -EIO), -EIO);+ EXPECT_TRUE(there("bpm/packages/sample/1/upatches/c.unload.upatch"));+ EXPECT_FALSE(there("bpm/packages/sample/2"));+ remove_root();+}++static void nothing_is_reached_through_a_symbolic_link(void)+{+ struct bpm_install in;+ struct stat st;++ new_root();+ make_dir("elsewhere");+ make_dir("bpm");+ ASSERT_EQ(symlinkat("../elsewhere", root, "bpm/staging"), 0);+ EXPECT_EQ(bpm_install_open(&in, root, "sample", "2"), -ELOOP);+ EXPECT_EQ(bpm_install_close(&in, -ELOOP), -ELOOP);+ ASSERT_EQ(unlinkat(root, "bpm/staging", 0), 0);++ make_dir("bpm/staging");+ put_file("elsewhere/archive", 'x');+ ASSERT_EQ(symlinkat("../../elsewhere/archive", root,+ "bpm/staging/sample-2.bee"), 0);+ EXPECT_EQ(bpm_install_open(&in, root, "sample", "2"), -ELOOP);+ EXPECT_EQ(bpm_install_close(&in, -ELOOP), -ELOOP);+ ASSERT_EQ(fstatat(root, "elsewhere/archive", &st, 0), 0);+ EXPECT_EQ(st.st_size, 1);+ EXPECT_TRUE(there("bpm/staging/sample-2.bee"));+ remove_root();+}++static void bind_over(const char *from, const char *onto, char *target,+ size_t size)+{+ char source[PATH_MAX];++ ASSERT_TRUE(strsprintf(source, sizeof(source), "%s/%s", root_dir, from) > 0);+ ASSERT_TRUE(strsprintf(target, size, "%s/%s", root_dir, onto) > 0);+ ASSERT_EQ(mount(source, target, NULL, MS_BIND, NULL), 0);+}++static void a_mount_below_the_state_root_is_refused(void)+{+ struct bpm_install in;+ char target[PATH_MAX];++ if (geteuid())+ unit_skip("needs root for a private bind mount");+ if (unshare(CLONE_NEWNS))+ unit_skip("cannot make a mount namespace");+ ASSERT_EQ(mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);+ new_root();+ make_dir("elsewhere/upatches");+ put_file("elsewhere/upatches/z.upatch", 'z');+ make_dir("bpm/staging");+ bind_over("elsewhere", "bpm/staging", target, sizeof(target));+ EXPECT_EQ(bpm_install_open(&in, root, "sample", "2"), -EXDEV);+ EXPECT_EQ(bpm_install_close(&in, -EXDEV), -EXDEV);+ ASSERT_EQ(umount(target), 0);+ EXPECT_FALSE(there("elsewhere/sample-2.bee"));++ /* Placed once the version is extracted, it is not read either. */+ open_and_extract(&in);+ bind_over("elsewhere/upatches", "bpm/packages/sample/2/upatches", target,+ sizeof(target));+ EXPECT_EQ(bpm_install_load(&in, NULL), -EXDEV);+ EXPECT_STREQ(order, "");+ ASSERT_EQ(umount(target), 0);++ /* Nor is one over a single member. */+ bind_over("elsewhere/upatches/z.upatch",+ "bpm/packages/sample/2/upatches/b.upatch", target,+ sizeof(target));+ EXPECT_EQ(bpm_install_load(&in, NULL), -EXDEV);+ EXPECT_STREQ(order, "+a-A");+ ASSERT_EQ(umount(target), 0);+ EXPECT_EQ(bpm_install_close(&in, -EXDEV), -EXDEV);+ EXPECT_FALSE(there("bpm/packages/sample/2"));+ remove_root();+}++static const struct unit_case cases[] = {+ UNIT_CASE(install_loads_in_name_order_and_keeps_the_archive),+ UNIT_CASE(a_version_already_there_is_left_as_it_is),+ UNIT_CASE(a_name_that_is_no_single_entry_is_refused),+ UNIT_CASE(a_refused_load_is_undone_and_the_version_removed),+ UNIT_CASE(an_upgrade_unloads_the_old_version_first),+ UNIT_CASE(a_failed_upgrade_loads_the_old_version_again),+ UNIT_CASE(nothing_is_reached_through_a_symbolic_link),+ UNIT_CASE(a_mount_below_the_state_root_is_refused),+ {}+};++UNIT_SUITE(bpm_install, cases);diff --git a/testing/unit/bpm_package.c b/testing/unit/bpm_package.cindex 8e83395e..48dbb3d3 100644--- a/testing/unit/bpm_package.c+++ b/testing/unit/bpm_package.c@@ -2,10 +2,19 @@/* Copyright (c) 2026 Authors of shirudo */#include <errno.h>+#include <fcntl.h>+#include <ftw.h>+#include <limits.h>+#include <stdlib.h>#include <string.h>+#include <sys/mman.h>+#include <sys/stat.h>+#include <unistd.h>+#include <shirudo/misc.h>#include <shirudo/string.h>+#include "archive_test.h"#include "bpm_oci.h"#include "bpm_package.h"#include "malloc.h"@@ -223,7 +232,112 @@ static void tree_manifest_is_the_publisher_form(void)EXPECT_EQ(len, 0);}+/* An archive in memory and an empty directory to extract it into. */+static char dest_dir[PATH_MAX];+static int archive = -1, dest = -1;++static void new_extract(const struct archive_member *m, int n)+{+ archive = memfd_create("shirudo-unit-bee", MFD_CLOEXEC);+ ASSERT_TRUE(archive >= 0);+ archive_write(archive, m, n);+ strscpy_literal(dest_dir, "/tmp/shirudo-bpm-package-XXXXXX");+ ASSERT_TRUE(mkdtemp(dest_dir));+ dest = open(dest_dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ ASSERT_TRUE(dest >= 0);+}++static int remove_entry(const char *path, const struct stat *st, int type,+ struct FTW *ftw)+{+ return remove(path);+}++static void end_extract(void)+{+ close(archive);+ close(dest);+ ASSERT_EQ(nftw(dest_dir, remove_entry, 16, FTW_DEPTH | FTW_PHYS), 0);+}++static void extract_makes_the_members_below_the_open_directory(void)+{+ static const struct archive_member m[] = {+ { "pkg/", '5', NULL },+ { "pkg/Beefile", '0', "name" },+ { "pkg/upatches/", '5', NULL },+ { "pkg/upatches/a.upatch", '0', "a" },+ { "pkg/doc/deep/er/notes", '0', "n" },+ { "pkg/empty", '5', NULL },+ };+ struct stat st;++ new_extract(m, ARRAY_SIZE(m));+ ASSERT_EQ(bpm_pkg_extract(archive, dest), 0);+ ASSERT_EQ(fstatat(dest, "Beefile", &st, 0), 0);+ EXPECT_EQ(st.st_size, 4);+ EXPECT_EQ(st.st_mode & 07777, 0644);+ ASSERT_EQ(fstatat(dest, "upatches/a.upatch", &st, 0), 0);+ EXPECT_TRUE(S_ISREG(st.st_mode));+ ASSERT_EQ(fstatat(dest, "doc/deep/er/notes", &st, 0), 0);+ EXPECT_TRUE(S_ISREG(st.st_mode));+ ASSERT_EQ(fstatat(dest, "empty", &st, 0), 0);+ EXPECT_TRUE(S_ISDIR(st.st_mode));+ /* The archive's top-level directory is dest itself. */+ EXPECT_EQ(faccessat(dest, "pkg", F_OK, 0), -1);+ /* A second run finds the files of the first in its way. */+ EXPECT_EQ(bpm_pkg_extract(archive, dest), -EEXIST);+ end_extract();+}++static void extract_takes_files_and_directories_of_one_tree_alone(void)+{+ static const struct archive_member link[] = {+ { "pkg/", '5', NULL },+ { "pkg/link", '2', NULL },+ };+ static const struct archive_member two_trees[] = {+ { "pkg/a", '0', "a" },+ { "other/b", '0', "b" },+ };+ static const struct archive_member above[] = {+ { "pkg/../b", '0', "b" },+ };++ new_extract(link, ARRAY_SIZE(link));+ EXPECT_EQ(bpm_pkg_extract(archive, dest), -EPERM);+ EXPECT_EQ(faccessat(dest, "link", F_OK, AT_SYMLINK_NOFOLLOW), -1);+ end_extract();+ new_extract(two_trees, ARRAY_SIZE(two_trees));+ EXPECT_EQ(bpm_pkg_extract(archive, dest), -EINVAL);+ EXPECT_EQ(faccessat(dest, "b", F_OK, 0), -1);+ end_extract();+ new_extract(above, ARRAY_SIZE(above));+ EXPECT_EQ(bpm_pkg_extract(archive, dest), -EINVAL);+ end_extract();+}++static void extract_reaches_nothing_through_a_symbolic_link(void)+{+ static const struct archive_member m[] = {+ { "pkg/upatches/a.upatch", '0', "a" },+ };+ char outside[PATH_MAX];++ new_extract(m, ARRAY_SIZE(m));+ strscpy_literal(outside, "/tmp/shirudo-bpm-outside-XXXXXX");+ ASSERT_TRUE(mkdtemp(outside));+ ASSERT_EQ(symlinkat(outside, dest, "upatches"), 0);+ EXPECT_EQ(bpm_pkg_extract(archive, dest), -ELOOP);+ /* Still empty. */+ ASSERT_EQ(rmdir(outside), 0);+ end_extract();+}+static const struct unit_case cases[] = {+ UNIT_CASE(extract_makes_the_members_below_the_open_directory),+ UNIT_CASE(extract_takes_files_and_directories_of_one_tree_alone),+ UNIT_CASE(extract_reaches_nothing_through_a_symbolic_link),UNIT_CASE(tree_manifest_is_the_publisher_form),UNIT_CASE(index_entry_needs_its_package_size),UNIT_CASE(semver_valid_is_semver_alone),diff --git a/util/bpm_install.c b/util/bpm_install.cnew file mode 100644index 00000000..f3a124af--- /dev/null+++ b/util/bpm_install.c@@ -0,0 +1,294 @@+// SPDX-License-Identifier: BSD-2-Clause+/* Copyright (c) 2026 Authors of shirudo */++#include <dirent.h>+#include <errno.h>+#include <fcntl.h>+#include <limits.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <unistd.h>++#include <shirudo/misc.h>+#include <shirudo/string.h>++#include "bpm_cleanup.h"+#include "bpm_install.h"+#include "bpm_package.h"+#include "log.h"+#include "malloc.h"+#include "paths.h"+#include "seal.h"+#include "upatch.h"++/* One load member or one directive of a version. */+struct member {+ char name[NAME_MAX + 1];+};++/* The upatches directory of one version of a package, -1 when it has none. */+struct upatches {+ int dir;+ const char *package;+ const char *version;+};++static void close_fd(int *fd)+{+ if (*fd >= 0)+ close(*fd);+ *fd = -1;+}++/* bpm/<name> below the state root, each made when it is not there. */+static int bpm_dir(int root, const char *name)+{+ int bpm, fd;++ bpm = seal_mkdir_child(root, "bpm", 0700, false);+ if (bpm < 0)+ return bpm;+ fd = seal_mkdir_child(bpm, name, 0700, false);+ close(bpm);+ return fd;+}++int bpm_install_open(struct bpm_install *in, int root, const char *name,+ const char *version)+{+ int store;++ *in = (struct bpm_install){+ .name = name, .version = version,+ .staging = -1, .package = -1, .dir = -1, .archive = -1,+ };+ if (!bpm_name_ok(name) || !bpm_version_ok(version))+ return -EINVAL;+ if (strsprintf(in->archive_name, sizeof(in->archive_name), "%s-%s.bee",+ name, version) < 0)+ return -ENAMETOOLONG;+ store = bpm_dir(root, "packages");+ if (store < 0)+ return store;+ in->package = seal_mkdir_child(store, name, 0700, false);+ close(store);+ if (in->package < 0)+ return in->package;+ in->staging = bpm_dir(root, "staging");+ if (in->staging < 0)+ return in->staging;+ in->archive = seal_create_child(in->staging, in->archive_name,+ O_RDWR | O_CREAT | O_TRUNC, 0600);+ return min(in->archive, 0);+}++int bpm_install_extract(struct bpm_install *in)+{+ in->dir = seal_mkdir_child(in->package, in->version, 0700, true);+ if (in->dir < 0)+ return in->dir;+ in->extracted = true;+ return bpm_pkg_extract(in->archive, in->dir);+}++int bpm_install_member(const struct bpm_install *in, const char *name)+{+ return seal_open_child(in->dir, name, O_RDONLY | O_NONBLOCK);+}++static int member_compare(const void *left, const void *right)+{+ const struct member *a = left, *b = right;++ return strcmp(a->name, b->name);+}++/* The members of kind in the directory open as updir, in name order. */+static int list_members(int updir, enum bpm_upatch_member kind,+ struct member *names, int *count)+{+ struct dirent *entry;+ int fd, n = 0, ret;+ struct stat st;+ DIR *dir;++ fd = fcntl(updir, F_DUPFD_CLOEXEC, 0);+ if (fd < 0)+ return -errno;+ dir = fdopendir(fd);+ if (!dir) {+ ret = -errno;+ close(fd);+ return ret;+ }+ rewinddir(dir);+ for (;;) {+ errno = 0;+ entry = readdir(dir);+ if (!entry) {+ ret = -errno;+ break;+ }+ if (bpm_upatch_member(entry->d_name, strlen(entry->d_name)) != kind)+ continue;+ /* A load is a regular file; a directive is opened to see. */+ if (kind == BPM_UPATCH_LOAD &&+ (fstatat(updir, entry->d_name, &st, AT_SYMLINK_NOFOLLOW) ||+ !S_ISREG(st.st_mode)))+ continue;+ if (n == BPM_MAX_UPATCHES) {+ ret = -E2BIG;+ break;+ }+ if (strscpy(names[n].name, entry->d_name,+ sizeof(names[n].name)) < 0) {+ ret = -ENAMETOOLONG;+ break;+ }+ n++;+ }+ closedir(dir);+ if (ret)+ return ret;+ qsort(names, (size_t)n, sizeof(names[0]), member_compare);+ *count = n;+ return 0;+}++/*+ * Load or unload one member, read through the directory held open. 0,+ * -errno for a member that is not shirudo's own to read, or -EIO for+ * one the load or the unload refused.+ */+static int member_apply(const struct upatches *u, const char *name, bool load)+{+ char path[PATH_MAX];+ struct stat st;+ int fd, ret;++ if (strsprintf(path, sizeof(path), "%s/%s/%s/upatches/%s",+ BPM_PACKAGES_DIR, u->package, u->version, name) < 0)+ return -ENAMETOOLONG;+ fd = seal_open_child(u->dir, name, O_RDONLY | O_NONBLOCK);+ if (fd < 0)+ return fd;+ if (fstat(fd, &st))+ ret = -errno;+ else if (!S_ISREG(st.st_mode))+ ret = -EINVAL;+ else if (load ? upatch_install_fd(path, fd) : upatch_remove_fd(path, fd))+ ret = -EIO;+ else+ ret = 0;+ close(fd);+ return ret;+}++/* The same for the member name is paired with: its directive, or its load. */+static int pair_apply(const struct upatches *u, const char *name, bool load)+{+ char pair[NAME_MAX + 1];++ if (bpm_upatch_pair(name, strlen(name), pair, sizeof(pair)))+ return -EINVAL;+ return member_apply(u, pair, load);+}++/* The upatches directory of an older version, left at -1 when it has none. */+static int open_old(const struct bpm_install *in, struct upatches *old)+{+ int version, fd;++ version = seal_open_child(in->package, old->version,+ O_RDONLY | O_DIRECTORY);+ if (version == -ENOENT)+ return 0;+ if (version < 0)+ return version;+ fd = seal_open_child(version, "upatches", O_RDONLY | O_DIRECTORY);+ close(version);+ if (fd == -ENOENT)+ return 0;+ if (fd < 0)+ return fd;+ old->dir = fd;+ return 0;+}++int bpm_install_load(const struct bpm_install *in, const char *old_version)+{+ struct upatches new = { -1, in->name, in->version };+ struct upatches old = { -1, in->name, old_version };+ int nloads = 0, nunloads = 0, nactive, i, ret;+ struct member *loads, *unloads;++ loads = xcalloc(2 * BPM_MAX_UPATCHES, sizeof(*loads));+ if (!loads)+ return -ENOMEM;+ unloads = loads + BPM_MAX_UPATCHES;+ new.dir = seal_open_child(in->dir, "upatches", O_RDONLY | O_DIRECTORY);+ ret = new.dir < 0 ? new.dir :+ list_members(new.dir, BPM_UPATCH_LOAD, loads, &nloads);+ if (!ret && !nloads)+ ret = -EINVAL;+ if (!ret && old_version && *old_version)+ ret = open_old(in, &old);+ if (!ret && old.dir >= 0)+ ret = list_members(old.dir, BPM_UPATCH_UNLOAD, unloads,+ &nunloads);+ if (ret)+ goto out;+ /* Reverse name order, as uninstall runs the directives. */+ for (i = nunloads; i > 0; i--) {+ ret = member_apply(&old, unloads[i - 1].name, false);+ if (ret)+ goto restore;+ }+ for (nactive = 0; nactive < nloads; nactive++) {+ ret = member_apply(&new, loads[nactive].name, true);+ if (ret)+ break;+ }+ if (!ret)+ goto out;+ while (nactive--)+ pair_apply(&new, loads[nactive].name, false);+restore:+ /* From the first directive that ran, or with i at 0 all of them. */+ for (; i < nunloads; i++)+ pair_apply(&old, unloads[i].name, true);+out:+ close_fd(&new.dir);+ close_fd(&old.dir);+ xfree(loads, 2 * BPM_MAX_UPATCHES * sizeof(*loads));+ return ret;+}++int bpm_install_close(struct bpm_install *in, int err)+{+ int ret;++ if (!err && renameat(in->staging, in->archive_name, in->package,+ in->archive_name)) {+ pr_warn("bpm: cannot keep %s/%s; dropping it", BPM_STAGING_DIR,+ in->archive_name);+ unlinkat(in->staging, in->archive_name, 0);+ }+ if (err && in->archive >= 0)+ unlinkat(in->staging, in->archive_name, 0);+ /* What failed to install must not block the next attempt. */+ if (err && in->extracted) {+ ret = bpm_pkg_remove_at(in->package, in->version);+ if (ret && ret != -ENOENT)+ pr_warn("bpm install: could not clean up %s/%s/%s: %s",+ BPM_PACKAGES_DIR, in->name, in->version,+ strerror(-ret));+ }+ close_fd(&in->archive);+ close_fd(&in->dir);+ close_fd(&in->package);+ close_fd(&in->staging);+ return err;+}diff --git a/util/bpm_install.h b/util/bpm_install.hnew file mode 100644index 00000000..3e5c70a2--- /dev/null+++ b/util/bpm_install.h@@ -0,0 +1,58 @@+/* SPDX-License-Identifier: BSD-2-Clause */+/* Copyright (c) 2026 Authors of shirudo */++#ifndef SHIRUDO_BPM_INSTALL_H+#define SHIRUDO_BPM_INSTALL_H++#include <stdbool.h>++#include "bpm_oci.h"++/*+ * One install of a package version. What it reads and writes it reaches+ * from directories it opens once, below the state root the caller+ * checked: the package's directory in the store, the version it+ * extracts and the archive it stages. A mount or a foreign entry placed+ * under the state root meanwhile fails the install; it is not followed.+ */+struct bpm_install {+ const char *name;+ const char *version;+ int staging;+ int package;+ int dir; /* of the version, once extracted */+ int archive;+ bool extracted; /* the version directory is this install's */+ char archive_name[2 * BPM_MAX_NAME + 8];+};++/*+ * Open the package's directory and a new, empty archive for an install+ * of name at version, below the state root open as root. 0 or -errno;+ * bpm_install_close() ends the install either way.+ */+int bpm_install_open(struct bpm_install *in, int root, const char *name,+ const char *version);+/*+ * Unpack the archive, which the caller has written and checked through+ * in->archive, into the version's directory. -EEXIST, with that+ * directory left as it is, when the version is there already.+ */+int bpm_install_extract(struct bpm_install *in);+/* A file at the top of the extracted version, open for reading. */+int bpm_install_member(const struct bpm_install *in, const char *name);+/*+ * Unload what old_version of the package loaded, when it is set, by its+ * directives in reverse name order, then load the members of the new+ * version in name order. A failure undoes the loads made and loads the+ * old version again.+ */+int bpm_install_load(const struct bpm_install *in, const char *old_version);+/*+ * End the install with err: 0 keeps the archive beside the versions,+ * anything else removes it and the version this install extracted.+ * Closes what the install holds and returns err.+ */+int bpm_install_close(struct bpm_install *in, int err);++#endif /* SHIRUDO_BPM_INSTALL_H */diff --git a/util/bpm_package.c b/util/bpm_package.cindex 62f5ebfc..51e0e734 100644--- a/util/bpm_package.c+++ b/util/bpm_package.c@@ -716,9 +716,47 @@ static X509 *read_x509_memory(const __u8 *body, size_t len)return x;}-int bpm_pkg_extract(const char *archive, const char *dest)+/*+ * The directory rel names below dest, each component made when it is+ * not there. With base set it is the directory of rel's last component,+ * which *base then points at.+ */+static int extract_dir(int dest, const char *rel, const char **base)+{+ char name[NAME_MAX + 1];+ const char *slash;+ int dir, next;+ size_t len;++ dir = fcntl(dest, F_DUPFD_CLOEXEC, 0);+ if (dir < 0)+ return -errno;+ while (*rel) {+ slash = strchr(rel, '/');+ if (!slash && base)+ break;+ len = slash ? (size_t)(slash - rel) : strlen(rel);+ if (len >= sizeof(name)) {+ close(dir);+ return -ENAMETOOLONG;+ }+ memcpy(name, rel, len);+ name[len] = '\0';+ next = seal_mkdir_child(dir, name, 0700, false);+ close(dir);+ if (next < 0)+ return next;+ dir = next;+ rel += len + (slash ? 1 : 0);+ }+ if (base)+ *base = rel;+ return dir;+}++int bpm_pkg_extract(int archive, int dest){- gzFile gz = gzopen(archive, "rb");+ gzFile gz = package_gzdopen(archive);char root[256] = {};__u64 total = 0;__u32 entries = 0;@@ -727,18 +765,13 @@ int bpm_pkg_extract(const char *archive, const char *dest)if (!gz)return -EINVAL;- ret = seal_mkdir_p(dest, 0700);- if (ret) {- gzclose(gz);- return ret;- }for (;;) {- char name[PATH_MAX], rel[PATH_MAX], path[PATH_MAX], *slash;+ char name[PATH_MAX], rel[PATH_MAX], *slash;int n = gzread(gz, h, sizeof(h));__u64 size, remain, pad;const char *below;bool zero = true;- int type;+ int type, dir;if (n == 0)break;@@ -795,14 +828,13 @@ int bpm_pkg_extract(const char *archive, const char *dest)ret = -EINVAL;break;}- if (strsprintf(path, sizeof(path), "%s/%s", dest, rel) < 0) {- ret = -ENAMETOOLONG;- break;- }if (type == '5') {- ret = seal_mkdir_p(path, 0700);- if (ret)+ dir = extract_dir(dest, rel, NULL);+ if (dir < 0) {+ ret = dir;break;+ }+ close(dir);/* Read as the other walkers do, whatever a directory carries. */remain = size;while (remain) {@@ -819,21 +851,17 @@ int bpm_pkg_extract(const char *archive, const char *dest)if (ret)break;} else if (type == '0') {- char parent[PATH_MAX];+ const char *base = NULL;int fd;- if (strscpy(parent, path, sizeof(parent)) < 0) {- ret = -ENAMETOOLONG;+ dir = extract_dir(dest, rel, &base);+ if (dir < 0) {+ ret = dir;break;}- slash = strrchr(parent, '/');- if (slash) {- *slash = 0;- ret = seal_mkdir_p(parent, 0700);- if (ret)- break;- }- fd = seal_open(path, O_WRONLY | O_CREAT | O_EXCL, 0644);+ fd = seal_create_child(dir, base,+ O_WRONLY | O_CREAT | O_EXCL, 0644);+ close(dir);if (fd < 0) {ret = fd;break;diff --git a/util/bpm_package.h b/util/bpm_package.hindex 22090119..91ec9ace 100644--- a/util/bpm_package.h+++ b/util/bpm_package.h@@ -99,9 +99,12 @@ int bpm_pkg_read_member(const char *archive, const char *member,__u8 **out, size_t *out_len, size_t max);/** Unpack the regular files and directories under the single top-level- * directory of a .bee into dest; anything else fails the archive.+ * directory of the .bee open on archive, read from its start, into the+ * open directory dest; anything else fails the archive. Each member is+ * made below dest on its mount, a directory under a name already there+ * taken only when it is shirudo's own.*/-int bpm_pkg_extract(const char *archive, const char *dest);+int bpm_pkg_extract(int archive, int dest);int bpm_pkg_load_info(const char *archive, struct bpm_package_info *info);/* Room for the manifest of a tree publication, in bytes. */diff --git a/util/upatch.h b/util/upatch.hindex 02b60979..6e170ec0 100644--- a/util/upatch.h+++ b/util/upatch.h@@ -233,6 +233,11 @@ __u32 prog_specs_xdp_classes(const struct prog_spec *specs, __u32 nr_progs);int upatch_restore(const char *path);int upatch_install(const char *path);int upatch_remove(const char *path);+/*+ * The same from a file the caller holds open: fd is read, and path only+ * names it in messages and reports.+ */+int upatch_install_fd(const char *path, int fd);int upatch_remove_fd(const char *path, int fd);/* A missing optional kprobe module permits tree projection advancement. */