eBPF-based security platform
bpm: confine package deletion to the boot state directory
KP Singh5afadf05eadd
diff --git a/Documentation/contribute/testing/proof-coverage.rst b/Documentation/contribute/testing/proof-coverage.rstindex 4ff2cea2..bb1dcb16 100644--- a/Documentation/contribute/testing/proof-coverage.rst+++ b/Documentation/contribute/testing/proof-coverage.rst@@ -1617,7 +1617,7 @@ a proof covers.* - Files- Why no proof reads them- * - :src:`util/harden.c`, :src:`util/identity.c`,+ * - :src:`util/bpm_cleanup.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 6b9671cf..24acb9be 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -1005,8 +1005,8 @@ OCI registry. The macOS workflow checks the Lima template withUnit suites and fuzz targets~~~~~~~~~~~~~~~~~~~~~~~~~~~~-The unit suites in :src:`testing/unit/` cover 42 of the modules in-:src:`util/`: ``attest``, ``bpm_oci``, ``bpm_package``, ``bpm_state``,+The unit suites in :src:`testing/unit/` cover 43 of the modules in+:src:`util/`: ``attest``, ``bpm_cleanup``, ``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/operate/run/deliver-packages.rst b/Documentation/operate/run/deliver-packages.rstindex d217368e..e4e589a7 100644--- a/Documentation/operate/run/deliver-packages.rst+++ b/Documentation/operate/run/deliver-packages.rst@@ -438,7 +438,7 @@ runtime drop-ins (:ref:`unit-drop-ins`). An enforcing target refusesthat binary, so without the drop-ins nothing is delivered.``bpm install``, ``upgrade``, ``uninstall``, ``repo update`` and-``tree sync`` take ``/var/lib/shirudo/locks/bpm.lock`` and wait for it+``tree sync`` lock the verified state root on an enforcing target and wait for itwithout a time limit. Every ``shirudo`` command on a target also holdsthe config operation lock for its whole run, and a command that waitslonger than 30 seconds for it fails. A long download therefore delaysdiff --git a/Documentation/reference/cli/bpm.rst b/Documentation/reference/cli/bpm.rstindex 0ef23f7f..fa1bfb32 100644--- a/Documentation/reference/cli/bpm.rst+++ b/Documentation/reference/cli/bpm.rst@@ -112,8 +112,9 @@ Usage- no- no-The lock is ``/var/lib/shirudo/locks/bpm.lock``. A locked subcommand waits-for it. The helper subcommands execute ``shirudo-build`` (see+On an enforcing target the lock is an exclusive flock on the state directory+whose device and inode init recorded at boot. Before enforcement BPM uses+``/var/lib/shirudo/locks/bpm.lock``. A locked subcommand waits for it. The helper subcommands execute ``shirudo-build`` (see:doc:`shirudo`). ``shirudo bpm --help`` and ``--list-cmds`` show ``build``and ``push`` only where the helper resolves. Elsewhere they are unknownsubcommands. ``config update``, ``tree append`` and ``tree show`` always@@ -554,8 +555,13 @@ run, so a new version in a registered index reaches every target thatruns the timer.``uninstall <name>`` applies the package's shipped unload directives in-reverse name order, each measured, removes the package directory and-drops it from the state.+reverse name order. BPM opens the directives from the installed version+and reads each from the descriptor it checked. A missing directive for+an active load stops uninstall. An interrupted uninstall can finish if+the remaining load members are inactive or the directory is already+empty. Successful uninstall 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.``list`` prints the installed packages under the heading ``Installedpackages:`` as a table with the columns ``NAME``, ``VERSION`` anddiff --git a/Documentation/reference/files.rst b/Documentation/reference/files.rstindex eec70aa9..d12dcb33 100644--- a/Documentation/reference/files.rst+++ b/Documentation/reference/files.rst@@ -136,7 +136,7 @@ the label as foreign. In the initrd, ``init`` binds* - ``locks/bpm.lock``- ``bpm``- ``0600``- - Lock of ``repo update``, ``tree sync``, ``install``,+ - Before enforcement, lock of ``repo update``, ``tree sync``, ``install``,``uninstall`` and ``upgrade``.* - ``bpm/state.json``- ``bpm install``, ``uninstall``, ``upgrade``diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rstindex ade78b74..4cc46cc4 100644--- a/Documentation/security/threat-model.rst+++ b/Documentation/security/threat-model.rst@@ -1952,10 +1952,16 @@ R22 Labeled inodes are interchangeabledecoy and undo the pins of a load still in flight in another, whichthen measures an upatch nothing runs. The register lock is the rootof the private bpffs, which takes no mount and no entry from root, so- a command in any namespace waits for the same inode (``t6128``). The- bpm lock, ``locks/bpm.lock``, still rests on a label: two package or- tree commands under a decoy can interleave their own state, while- each step they measure still waits for the register lock.+ a command in any namespace waits for the same inode (``t6128``).+ BPM commands on an enforcing target lock the state+ root directory itself. Init records its device and inode in the frozen+ identity map before enforcement starts. BPM verifies both on the open+ directory, 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.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 7c2ffd88..3b99433e 100644--- a/Makefile.shirudo+++ b/Makefile.shirudo@@ -269,6 +269,7 @@ UTIL_SRCS := \util/bpm_tree_state.c \util/bpm_oci.c \util/curl.c \+ util/bpm_cleanup.c \util/bpm_package.c \util/bpm_state.c \util/kconfig.c \diff --git a/bpf/lib/identity.h b/bpf/lib/identity.hindex 4212300f..ac78a1bf 100644--- a/bpf/lib/identity.h+++ b/bpf/lib/identity.h@@ -25,6 +25,8 @@ struct sb_id {__s32 dm_verity_keys[IDENTITY_KEYS_MAX];__u32 nv_index;__u32 config_pcr;+ __u64 state_dev;+ __u64 state_ino;};struct {diff --git a/builtin-bpm.c b/builtin-bpm.cindex 09218e2d..fe6c3371 100644--- a/builtin-bpm.c+++ b/builtin-bpm.c@@ -10,7 +10,6 @@#include <dirent.h>#include <errno.h>#include <fcntl.h>-#include <ftw.h>#include <limits.h>#include <stdbool.h>#include <stdio.h>@@ -34,6 +33,7 @@#include <shirudo/string.h>#include "builtin.h"+#include "util/bpm_cleanup.h"#include "util/bpm_oci.h"#include "util/bpm_package.h"#include "util/bpm_state.h"@@ -46,6 +46,7 @@#include "util/help.h"#include "util/hex.h"#include "util/io.h"+#include "util/identity.h"#include "util/initrd.h"#include "util/java_agent.h"#include "util/image_config.h"@@ -70,7 +71,37 @@ struct bpm_source {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);-static int remove_tree(const char *path);+static int package_store_open(void)+{+ int state, bpm, packages;++ state = state_root_open();+ if (state < 0)+ return state;+ bpm = seal_open_child(state, "bpm", O_RDONLY | O_DIRECTORY);+ close(state);+ if (bpm < 0)+ return bpm;+ packages = seal_open_child(bpm, "packages", O_RDONLY | O_DIRECTORY);+ close(bpm);+ 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)@@ -454,10 +485,24 @@ static int save_source(const struct bpm_source *s)static int with_bpm_lock(void){- int ret;+ int fd, ret;- ret = seal_mkdir_p(LOCKS_DIR, 0700);- return ret ? ret : seal_lock(BPM_LOCK_PATH);+ ret = enforcement_active();+ if (ret < 0)+ return ret;+ if (!ret) {+ ret = seal_mkdir_p(LOCKS_DIR, 0700);+ return ret ? ret : seal_lock(BPM_LOCK_PATH);+ }+ fd = state_root_open();+ if (fd < 0)+ return fd;+ ret = lock_exclusive(fd);+ if (ret) {+ close(fd);+ return ret;+ }+ return fd;}static int bpm_fail(const char *action, int ret)@@ -1134,8 +1179,6 @@ static void sort_old_pairs(char (*unloads)[PATH_MAX], char (*loads)[PATH_MAX],}}-#define INSTALL_PATHS_MAX 128-static int package_install(const struct bpm_source *s, const struct bpm_index_entry *entry,const char *old_path, const char *old_version){@@ -1153,11 +1196,11 @@ static int package_install(const struct bpm_source *s, const struct bpm_index_enint nloaded = 0, nactive = 0, nold = 0, nold_removed = 0;/* 1.5 MiB of paths, which a stack frame should not carry. */- loaded = xcalloc(3 * INSTALL_PATHS_MAX, PATH_MAX);+ loaded = xcalloc(3 * BPM_MAX_UPATCHES, PATH_MAX);if (!loaded)return -ENOMEM;- old_loads = loaded + INSTALL_PATHS_MAX;- old_unloads = old_loads + INSTALL_PATHS_MAX;+ old_loads = loaded + BPM_MAX_UPATCHES;+ old_unloads = old_loads + BPM_MAX_UPATCHES;ret = bpm_oci_parse_endpoint(s->endpoint, &c);if (ret)goto out;@@ -1291,7 +1334,7 @@ static int package_install(const struct bpm_source *s, const struct bpm_index_en}if (stat(up, &st) || !S_ISREG(st.st_mode))continue;- if (nloaded >= INSTALL_PATHS_MAX) {+ if (nloaded >= BPM_MAX_UPATCHES) {ret = -E2BIG;break;}@@ -1325,7 +1368,7 @@ static int package_install(const struct bpm_source *s, const struct bpm_index_enchar load[NAME_MAX + 1];if (bpm_upatch_member(de->d_name, len) !=- BPM_UPATCH_UNLOAD || nold >= INSTALL_PATHS_MAX)+ BPM_UPATCH_UNLOAD || nold >= BPM_MAX_UPATCHES)continue;if (bpm_upatch_pair(de->d_name, len, load,sizeof(load)) ||@@ -1400,9 +1443,14 @@ out:if (ret && archive[0])unlink(archive);/* What failed to install must not block the next attempt. */- if (ret && extracted)- remove_tree(package_dir);- xfree(loaded, 3 * INSTALL_PATHS_MAX * PATH_MAX);+ 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;}@@ -2723,90 +2771,15 @@ out:return ret;}-static int remove_tree_entry(const char *path, const struct stat *st,- int type, struct FTW *ftw)-{- if (type == FTW_DP || type == FTW_D)- return rmdir(path) ? -1 : 0;- return unlink(path) ? -1 : 0;-}--static int remove_tree(const char *path)-{- if (nftw(path, remove_tree_entry, 32, FTW_DEPTH | FTW_PHYS))- return errno ? -errno : -EIO;- return 0;-}--static int path_compare_desc(const void *left, const void *right)-{- return strcmp(right, left);-}--/*- * Detach a package's upatches through the signed unload directives it- * shipped, in reverse name order, then remove the package tree. The- * caller drops the state entry only after this succeeded, so a failed- * detach leaves the package listed and loadable again.- */static int package_uninstall(const struct bpm_state_entry *st){- char dir[PATH_MAX], updir[PATH_MAX];- char (*unloads)[PATH_MAX];- struct dirent *de;- int n = 0, ret = 0;- DIR *d;+ int store, ret;- if (strsprintf(updir, sizeof(updir), "%s/upatches", st->path) < 0)- return -ENAMETOOLONG;- unloads = xcalloc(128, PATH_MAX);- if (!unloads)- return -ENOMEM;- /*- * A tree already gone, from an uninstall that died before it- * wrote the state, leaves nothing to unload: the retry converges.- */- d = opendir(updir);- if (!d && errno != ENOENT) {- ret = -errno;- goto out;- }- while (d && (de = readdir(d))) {- if (bpm_upatch_member(de->d_name, strlen(de->d_name)) !=- BPM_UPATCH_UNLOAD)- continue;- if (n >= 128) {- ret = -E2BIG;- break;- }- if (strsprintf(unloads[n], PATH_MAX, "%s/%s", updir, de->d_name) < 0) {- ret = -ENAMETOOLONG;- break;- }- n++;- }- if (d)- closedir(d);- if (ret)- goto out;- qsort(unloads, (size_t)n, PATH_MAX, path_compare_desc);- for (int i = 0; i < n; i++) {- if (upatch_remove(unloads[i])) {- pr_err("bpm uninstall: unload %s failed", unloads[i]);- ret = -EIO;- goto out;- }- }- if (strsprintf(dir, sizeof(dir), "%s/%s", BPM_PACKAGES_DIR,- st->name) < 0) {- ret = -ENAMETOOLONG;- goto out;- }- ret = remove_tree(dir);- if (ret == -ENOENT)- ret = 0;-out:- xfree(unloads, 128 * PATH_MAX);+ store = package_store_open();+ if (store < 0)+ return store;+ ret = bpm_uninstall_at(store, st);+ close(store);return ret;}diff --git a/builtin-init.c b/builtin-init.cindex d549bbd7..de957b83 100644--- a/builtin-init.c+++ b/builtin-init.c@@ -680,6 +680,10 @@ static int identity_devices(struct identity *id)if (stat(RUN_DIR, &st))return -errno;id->run_dev = kernel_dev(st.st_dev);+ if (stat(VAR_LIB, &st))+ return -errno;+ id->state_dev = st.st_dev;+ id->state_ino = st.st_ino;return 0;}diff --git a/builtin-upatch.c b/builtin-upatch.cindex 051e9bea..fc5584b2 100644--- a/builtin-upatch.c+++ b/builtin-upatch.c@@ -1595,6 +1595,21 @@ static int obj_pin(int fd, const char *path)return ret >= 0 ? 0 : -errno;}+static int open_upatch_pin_dir(const char *name)+{+ char path[PATH_MAX];+ int root, fd;++ if (upatch_pin_path(path, sizeof(path), name, NULL))+ return -ENAMETOOLONG;+ root = bpffs_root_open();+ if (root < 0)+ return root == -ENOENT ? -ENODEV : root;+ fd = open_beneath_same_mount(root, path + sizeof(BPFFS_DIR), O_RDONLY | O_DIRECTORY);+ close(root);+ return fd;+}+/** A pin a load left when it died before its link is bound to maps nothing* reaches any more: replace it.@@ -3343,14 +3358,15 @@ static int remove_pin_dir(const char *name)* one read. A copy on disk, under a name another command can take, or a* file read again, could set them apart.*/-static int read_upatch(const char *src, __u8 **buf, size_t *len,+static int read_upatch(const char *src, int fd, __u8 **buf, size_t *len,struct upatch *u){int ret;*buf = NULL;*len = 0;- ret = read_file(src, UPATCH_FILE_MAX, buf, len);+ ret = fd < 0 ? read_file(src, UPATCH_FILE_MAX, buf, len) :+ read_fd(fd, src, UPATCH_FILE_MAX, buf, len);if (ret)return ret;ret = upatch_open_memory(*buf, *len, u);@@ -3524,7 +3540,7 @@ static int upatch_load(const struct load_args *args)"load") != 0)goto done;- err = read_upatch(file, &buf, &len, &u);+ err = read_upatch(file, -1, &buf, &len, &u);if (err) {pr_err("upatch load: read %s: %s", file, strerror(-err));rep_fail(&rep, "parse", "parser_rejected", -err,@@ -3729,7 +3745,7 @@ static int java_unload_locked(const char *name,return 0;}-static int cmd_upatch_unload(int argc, const char **argv)+static int cmd_upatch_unload(int argc, const char **argv, int fd){const char *file, *expect_chain, *expect_version_id, *report;struct op_report rep = { .op = "upatch_unload", .phase = "done" };@@ -3757,7 +3773,7 @@ static int cmd_upatch_unload(int argc, const char **argv)* signature check covers must be the bytes acted on after it, and a* file of root's is root's to rewrite between the two.*/- err = read_upatch(file, &buf, &len, &u);+ err = read_upatch(file, fd, &buf, &len, &u);if (err) {pr_err("upatch unload: read %s: %s", file, strerror(-err));rep_fail(&rep, "parse", "parser_rejected", -err,@@ -3980,6 +3996,34 @@ static int purge_is_loaded(const char *name, __u32 type)return ret ? ret : 1;}+/* The load member of an older package may have no unload directive. */+int upatch_member_active_fd(int fd)+{+ char name[UPATCH_NAME_MAX + 1];+ struct upatch u;+ int ret;++ ret = upatch_open_fd(fd, &u);+ if (ret)+ return ret;+ upatch_header_name(&u, name);+ if (upatch_is_unload(&u) || !upatch_name_signed(&u) || !upatch_name_valid(name)) {+ ret = -EINVAL;+ } else if (u.hdr.type == UPATCH_TYPE_JAVA) {+ ret = purge_is_loaded(name, u.hdr.type);+ } else {+ ret = open_upatch_pin_dir(name);+ if (ret >= 0) {+ close(ret);+ ret = 1;+ } else if (ret == -ENOENT) {+ ret = 0;+ }+ }+ upatch_close(&u);+ return ret;+}+static int upatch_purge_locked(const char *name, const struct cert *signer,const char *reason){@@ -4078,11 +4122,16 @@ int upatch_install(const char *path)return upatch_load(&args);}-int upatch_remove(const char *path)+int upatch_remove_fd(const char *path, int fd){const char *argv[] = { "unload", "--no-precheck", path };- return cmd_upatch_unload(3, argv);+ return cmd_upatch_unload(3, argv, fd);+}++int upatch_remove(const char *path)+{+ return upatch_remove_fd(path, -1);}/*@@ -5350,7 +5399,7 @@ int cmd_upatch(int argc, const char **argv)if (strcmp(canonical, "load") == 0)return cmd_upatch_load(argc - 1, argv + 1);if (strcmp(canonical, "unload") == 0)- return cmd_upatch_unload(argc - 1, argv + 1);+ return cmd_upatch_unload(argc - 1, argv + 1, -1);if (strcmp(canonical, "list") == 0)return cmd_upatch_list(argc - 1, argv + 1);if (strcmp(canonical, "get") == 0)diff --git a/testing/unit/bpm_cleanup.c b/testing/unit/bpm_cleanup.cnew file mode 100644index 00000000..bee041b2--- /dev/null+++ b/testing/unit/bpm_cleanup.c@@ -0,0 +1,161 @@+// SPDX-License-Identifier: BSD-2-Clause+/* Copyright (c) 2026 Authors of shirudo */++#include <errno.h>+#include <fcntl.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <unistd.h>++#include <shirudo/string.h>++#include "bpm_cleanup.h"+#include "bpm_state.h"+#include "upatch.h"+#include "unit.h"++static int calls;+static char order[4];+static bool refuse;+static int active;++int upatch_member_active_fd(int fd)+{+ char byte;++ return pread(fd, &byte, 1, 0) == 1 && byte == 'l' ? active : -EINVAL;+}++int upatch_remove_fd(const char *path, int fd)+{+ char byte;++ if (calls >= (int)sizeof(order) - 1 || pread(fd, &byte, 1, 0) != 1)+ return 1;+ order[calls++] = byte;+ return refuse;+}++struct package {+ char dir[PATH_MAX];+ struct bpm_state_entry st;+ int fd;+};++static void new_package(struct package *p)+{+ strscpy_literal(p->dir, "/tmp/shirudo-bpm-cleanup-XXXXXX");+ ASSERT_TRUE(mkdtemp(p->dir));+ p->fd = open(p->dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ ASSERT_TRUE(p->fd >= 0);+ strscpy_literal(p->st.name, "sample");+ strscpy_literal(p->st.version, "1");+ ASSERT_TRUE(strsprintf(p->st.path, sizeof(p->st.path), "%s/sample/1", p->dir) > 0);+ ASSERT_EQ(mkdirat(p->fd, "sample", 0700), 0);+ ASSERT_EQ(mkdirat(p->fd, "sample/1", 0700), 0);+ ASSERT_EQ(mkdirat(p->fd, "sample/1/upatches", 0700), 0);+ refuse = false;+ calls = 0;+ memset(order, 0, sizeof(order));+}++static void put_file(int parent, const char *name, char byte)+{+ int fd = openat(parent, name, 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 void finish_package(struct package *p)+{+ close(p->fd);+ ASSERT_EQ(rmdir(p->dir), 0);+}++static void uninstall_retires_all_versions_after_detach(void)+{+ struct package p = {};++ new_package(&p);+ put_file(p.fd, "sample/1/upatches/a.unload.upatch", 'a');+ put_file(p.fd, "sample/1/upatches/z.unload.upatch", 'z');+ put_file(p.fd, "sample/sample-1.bee", 'x');+ ASSERT_EQ(mkdirat(p.fd, "sample/2", 0700), 0);+ put_file(p.fd, "sample/2/old", 'k');++ refuse = true;+ EXPECT_EQ(bpm_uninstall_at(p.fd, &p.st), -EIO);+ EXPECT_EQ(faccessat(p.fd, "sample/1/upatches/a.unload.upatch", F_OK, 0), 0);+ EXPECT_EQ(faccessat(p.fd, "sample/sample-1.bee", F_OK, 0), 0);+ refuse = false;+ calls = 0;+ ASSERT_EQ(bpm_uninstall_at(p.fd, &p.st), 0);+ EXPECT_STREQ(order, "za");+ EXPECT_EQ(faccessat(p.fd, "sample", F_OK, 0), -1);+ EXPECT_EQ(errno, ENOENT);+ EXPECT_EQ(bpm_uninstall_at(p.fd, &p.st), 0);+ EXPECT_EQ(calls, 2);+ finish_package(&p);+}++static void unpaired_load_must_be_inactive(void)+{+ struct package p = {};++ new_package(&p);+ put_file(p.fd, "sample/1/upatches/load.upatch", 'l');+ active = 1;+ EXPECT_EQ(bpm_uninstall_at(p.fd, &p.st), -ENODATA);+ active = -EIO;+ EXPECT_EQ(bpm_uninstall_at(p.fd, &p.st), -EIO);+ EXPECT_EQ(faccessat(p.fd, "sample/1/upatches/load.upatch", F_OK, 0), 0);+ active = 0;+ ASSERT_EQ(bpm_uninstall_at(p.fd, &p.st), 0);+ EXPECT_EQ(calls, 0);+ finish_package(&p);+}++static void retry_finishes_a_partly_removed_package(void)+{+ struct package p = {};++ new_package(&p);+ put_file(p.fd, "sample/1/upatches/notes", 'n');+ ASSERT_EQ(bpm_uninstall_at(p.fd, &p.st), 0);+ EXPECT_EQ(calls, 0);+ finish_package(&p);++ new_package(&p);+ ASSERT_EQ(unlinkat(p.fd, "sample/1/upatches", AT_REMOVEDIR), 0);+ ASSERT_EQ(bpm_uninstall_at(p.fd, &p.st), 0);+ finish_package(&p);+}++static void cleanup_requires_a_single_child_directory(void)+{+ struct package p = {};++ new_package(&p);+ EXPECT_EQ(bpm_pkg_remove_at(p.fd, "."), -EINVAL);+ EXPECT_EQ(bpm_pkg_remove_at(p.fd, "../1"), -EINVAL);+ EXPECT_EQ(bpm_pkg_remove_at(p.fd, "sample/1/upatches"), -EINVAL);+ ASSERT_EQ(symlinkat("sample", p.fd, "alias"), 0);+ EXPECT_LT(bpm_pkg_remove_at(p.fd, "alias"), 0);+ EXPECT_EQ(faccessat(p.fd, "sample/1/upatches", F_OK, 0), 0);+ ASSERT_EQ(unlinkat(p.fd, "alias", 0), 0);+ ASSERT_EQ(bpm_pkg_remove_at(p.fd, "sample"), 0);+ finish_package(&p);+}++static const struct unit_case cases[] = {+ UNIT_CASE(uninstall_retires_all_versions_after_detach),+ UNIT_CASE(unpaired_load_must_be_inactive),+ UNIT_CASE(retry_finishes_a_partly_removed_package),+ UNIT_CASE(cleanup_requires_a_single_child_directory),+ {}+};++UNIT_SUITE(bpm_cleanup, cases);diff --git a/testing/unit/identity.c b/testing/unit/identity.cindex 7dc48ebe..8e53fba6 100644--- a/testing/unit/identity.c+++ b/testing/unit/identity.c@@ -1,7 +1,12 @@// SPDX-License-Identifier: BSD-2-Clause/* Copyright (c) 2026 Authors of shirudo */+#include <errno.h>+#include <fcntl.h>#include <linux/bpf.h>+#include <stdlib.h>+#include <sys/stat.h>+#include <unistd.h>#include "identity.h"#include "unit.h"@@ -41,7 +46,34 @@ static void unterminated_name_matches_nothing(void)EXPECT_FALSE(guard_name_matches(name, "x"));}+static void state_root_requires_the_recorded_directory(void)+{+ char path[] = "/tmp/shirudo-state-XXXXXX";+ struct identity id = {};+ struct stat st;+ int root, other;++ ASSERT_TRUE(mkdtemp(path));+ root = open(path, O_DIRECTORY | O_RDONLY | O_CLOEXEC);+ ASSERT_TRUE(root >= 0);+ ASSERT_EQ(fstat(root, &st), 0);+ id.state_dev = st.st_dev;+ id.state_ino = st.st_ino;+ ASSERT_EQ(mkdirat(root, "other", 0700), 0);+ other = openat(root, "other", O_DIRECTORY | O_RDONLY | O_CLOEXEC);+ ASSERT_TRUE(other >= 0);+ EXPECT_EQ(identity_check_state_root(&id, root), 0);+ EXPECT_EQ(identity_check_state_root(&id, other), -EXDEV);+ id.state_dev++;+ EXPECT_EQ(identity_check_state_root(&id, root), -EXDEV);+ close(other);+ ASSERT_EQ(unlinkat(root, "other", AT_REMOVEDIR), 0);+ close(root);+ ASSERT_EQ(rmdir(path), 0);+}+static const struct unit_case cases[] = {+ UNIT_CASE(state_root_requires_the_recorded_directory),UNIT_CASE(kernel_name_is_the_start_of_a_long_one),UNIT_CASE(short_name_is_the_whole_one),UNIT_CASE(unterminated_name_matches_nothing),diff --git a/testing/unit/io.c b/testing/unit/io.cindex 5f452227..763d2e81 100644--- a/testing/unit/io.c+++ b/testing/unit/io.c@@ -147,6 +147,19 @@ static void bpffs_mounted_at_wants_the_root_of_a_bpffs(void)EXPECT_EQ(bpffs_mounted_at("/dev/null"), -ENOTDIR);}+static void open_beneath_same_mount_stops_at_proc(void)+{+ int root = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ int fd;++ ASSERT_TRUE(root >= 0);+ fd = open_beneath(root, "proc", O_RDONLY | O_DIRECTORY);+ ASSERT_TRUE(fd >= 0);+ close(fd);+ EXPECT_EQ(open_beneath_same_mount(root, "proc", O_RDONLY | O_DIRECTORY), -EXDEV);+ close(root);+}+static int etc_fd = -1;static int remove_entry(const char *path, const struct stat *st, int type,@@ -592,6 +605,29 @@ static void check_trusted_follows_its_prefix_linked_elsewhere(void)remove_etc();}+static void open_beneath_same_mount_refuses_a_bind(void)+{+ char source[PATH_MAX], alias[PATH_MAX];+ int fd;++ need_root("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);+ make_etc();+ make_dir("source", 0700);+ make_dir("alias", 0700);+ ASSERT_TRUE(strsprintf(source, sizeof(source), "%s/source", etc_dir) > 0);+ ASSERT_TRUE(strsprintf(alias, sizeof(alias), "%s/alias", etc_dir) > 0);+ ASSERT_EQ(mount(source, alias, NULL, MS_BIND, NULL), 0);+ fd = open_beneath(etc_fd, "alias", O_RDONLY | O_DIRECTORY);+ ASSERT_TRUE(fd >= 0);+ close(fd);+ EXPECT_EQ(open_beneath_same_mount(etc_fd, "alias", O_RDONLY | O_DIRECTORY), -EXDEV);+ ASSERT_EQ(umount(alias), 0);+ remove_etc();+}+/* The same, the directory linked to on a file system of its own. */static void check_trusted_follows_its_prefix_onto_another_mount(void){@@ -827,6 +863,8 @@ static void read_file_takes_a_file_renamed_over_or_refuses_it(void)}static const struct unit_case cases[] = {+ UNIT_CASE(open_beneath_same_mount_stops_at_proc),+ UNIT_CASE(open_beneath_same_mount_refuses_a_bind),UNIT_CASE(lines_len_ends_at_the_last_newline),UNIT_CASE(append_line_adds_one_record),UNIT_CASE(append_line_drops_what_did_not_finish),diff --git a/util/bpm_cleanup.c b/util/bpm_cleanup.cnew file mode 100644index 00000000..f1efcf2b--- /dev/null+++ b/util/bpm_cleanup.c@@ -0,0 +1,231 @@+// 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/string.h>++#include "bpm_cleanup.h"+#include "bpm_package.h"+#include "bpm_state.h"+#include "log.h"+#include "malloc.h"+#include "seal.h"+#include "upatch.h"++static int remove_package_entry(int parent, const char *name, __u32 depth);++static int empty_package_dir(DIR *dir, __u32 depth, bool directives)+{+ struct dirent *entry;+ int ret;++ for (;;) {+ errno = 0;+ entry = readdir(dir);+ if (!entry)+ return -errno;+ if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))+ continue;+ if ((bpm_upatch_member(entry->d_name, strlen(entry->d_name)) ==+ BPM_UPATCH_UNLOAD) != directives)+ continue;+ ret = remove_package_entry(dirfd(dir), entry->d_name, depth + 1);+ if (ret && ret != -ENOENT)+ return ret;+ }+}++/* Takes ownership of fd, also on failure. */+static int remove_open_dir(int parent, const char *name, int fd, __u32 depth)+{+ DIR *dir;+ int ret;++ dir = fdopendir(fd);+ if (!dir) {+ ret = -errno;+ close(fd);+ return ret;+ }+ ret = empty_package_dir(dir, depth, false);+ if (!ret) {+ /* A stop with a load member left must leave its directive too. */+ rewinddir(dir);+ ret = empty_package_dir(dir, depth, true);+ }+ if (!ret && unlinkat(parent, name, AT_REMOVEDIR))+ ret = -errno;+ closedir(dir);+ return ret;+}++static int remove_package_entry(int parent, const char *name, __u32 depth)+{+ int fd;++ /* A ustar member's path fits in 256 bytes. */+ if (depth > 256)+ return -ENAMETOOLONG;+ fd = seal_open_child(parent, name, O_RDONLY | O_DIRECTORY);+ if (fd == -ENOTDIR && depth)+ return unlinkat(parent, name, 0) ? -errno : 0;+ if (fd < 0)+ return fd;+ return remove_open_dir(parent, name, fd, depth);+}++int bpm_pkg_remove_at(int parent, const char *name)+{+ return remove_package_entry(parent, name, 0);+}++struct package_directive {+ char path[PATH_MAX];+ int fd;+};++static int directive_compare_desc(const void *left, const void *right)+{+ const struct package_directive *a = left, *b = right;++ return strcmp(b->path, a->path);+}++static int check_unpaired_load(int dir, const char *name)+{+ char pair[NAME_MAX + 1];+ int fd, ret;++ ret = bpm_upatch_pair(name, strlen(name), pair, sizeof(pair));+ if (ret)+ return ret;+ fd = seal_open_child(dir, pair, O_RDONLY | O_NONBLOCK);+ if (fd >= 0) {+ close(fd);+ return 0;+ }+ if (fd != -ENOENT)+ return fd;+ fd = seal_open_child(dir, name, O_RDONLY | O_NONBLOCK);+ if (fd < 0)+ return fd;+ ret = upatch_member_active_fd(fd);+ close(fd);+ if (ret > 0) {+ pr_err("bpm uninstall: active %s is missing %s", name, pair);+ return -ENODATA;+ }+ return ret;+}++/* Keep the files we checked open through signature verification. */+static int open_directives(DIR *dir, const char *version_path,+ struct package_directive *unloads, size_t *count)+{+ struct dirent *entry;+ struct package_directive *u;+ struct stat st;+ enum bpm_upatch_member kind;+ int ret;++ for (;;) {+ errno = 0;+ entry = readdir(dir);+ if (!entry)+ return -errno;+ kind = bpm_upatch_member(entry->d_name, strlen(entry->d_name));+ if (kind == BPM_UPATCH_LOAD) {+ ret = check_unpaired_load(dirfd(dir), entry->d_name);+ if (ret)+ return ret;+ }+ if (kind != BPM_UPATCH_UNLOAD)+ continue;+ if (*count == BPM_MAX_UPATCHES)+ return -E2BIG;+ u = &unloads[*count];+ if (strsprintf(u->path, sizeof(u->path), "%s/upatches/%s",+ version_path, entry->d_name) < 0)+ return -ENAMETOOLONG;+ u->fd = seal_open_child(dirfd(dir), entry->d_name, O_RDONLY | O_NONBLOCK);+ if (u->fd < 0)+ return u->fd;+ (*count)++;+ if (fstat(u->fd, &st))+ return -errno;+ if (!S_ISREG(st.st_mode))+ return -EINVAL;+ }+}++static int unload_version(int version, const char *path)+{+ struct package_directive *unloads;+ size_t count = 0, i;+ int fd, ret;+ DIR *dir;++ fd = seal_open_child(version, "upatches", O_RDONLY | O_DIRECTORY);+ if (fd < 0)+ return fd == -ENOENT ? 0 : fd;+ dir = fdopendir(fd);+ if (!dir) {+ ret = -errno;+ close(fd);+ return ret;+ }+ unloads = xcalloc(BPM_MAX_UPATCHES, sizeof(*unloads));+ if (!unloads) {+ closedir(dir);+ return -ENOMEM;+ }+ ret = open_directives(dir, path, unloads, &count);+ closedir(dir);+ if (!ret) {+ qsort(unloads, count, sizeof(*unloads), directive_compare_desc);+ for (i = 0; i < count; i++) {+ if (upatch_remove_fd(unloads[i].path, unloads[i].fd)) {+ pr_err("bpm uninstall: unload %s failed", unloads[i].path);+ ret = -EIO;+ break;+ }+ }+ }+ for (i = 0; i < count; i++)+ close(unloads[i].fd);+ xfree(unloads, BPM_MAX_UPATCHES * sizeof(*unloads));+ return ret;+}++int bpm_uninstall_at(int store, const struct bpm_state_entry *st)+{+ int package, version, ret = 0;++ if (!bpm_name_ok(st->name) || !bpm_version_ok(st->version))+ return -EINVAL;+ package = seal_open_child(store, st->name, O_RDONLY | O_DIRECTORY);+ if (package < 0)+ return package == -ENOENT ? 0 : package;+ version = seal_open_child(package, st->version, O_RDONLY | O_DIRECTORY);+ if (version >= 0) {+ ret = unload_version(version, st->path);+ close(version);+ } else if (version != -ENOENT) {+ ret = version;+ }+ /* Upgrade keeps older versions and their archives in this directory. */+ if (!ret)+ ret = remove_open_dir(store, st->name, package, 0);+ else+ close(package);+ return ret;+}diff --git a/util/bpm_cleanup.h b/util/bpm_cleanup.hnew file mode 100644index 00000000..8ba9ce62--- /dev/null+++ b/util/bpm_cleanup.h@@ -0,0 +1,14 @@+/* SPDX-License-Identifier: BSD-2-Clause */+/* Copyright (c) 2026 Authors of shirudo */++#ifndef SHIRUDO_BPM_CLEANUP_H+#define SHIRUDO_BPM_CLEANUP_H++struct bpm_state_entry;++/* Remove one directory below parent without crossing a mount. */+int bpm_pkg_remove_at(int parent, const char *name);+/* Unload the active version, then retire the complete package directory. */+int bpm_uninstall_at(int store, const struct bpm_state_entry *st);++#endif /* SHIRUDO_BPM_CLEANUP_H */diff --git a/util/bpm_package.h b/util/bpm_package.hindex a7fd39ae..22090119 100644--- a/util/bpm_package.h+++ b/util/bpm_package.h@@ -16,6 +16,8 @@#include "bpm_oci.h"#include "bpm_tree.h"+#define BPM_MAX_UPATCHES 128+struct trusted_set;struct bpm_index_entry {diff --git a/util/bpm_state.c b/util/bpm_state.cindex 1d7688c7..d57304db 100644--- a/util/bpm_state.c+++ b/util/bpm_state.c@@ -2,6 +2,9 @@/* Copyright (c) 2026 Authors of shirudo */#include <errno.h>+#include <fcntl.h>+#include <sys/stat.h>+#include <unistd.h>#include <string.h>#include <shirudo/misc.h>@@ -9,6 +12,7 @@#include "bpm_state.h"#include "io.h"+#include "identity.h"#include "json.h"#include "malloc.h"#include "paths.h"@@ -99,13 +103,36 @@ int bpm_state_emit(const struct bpm_state_entry *st, int n, char *buf,return 0;}+static int read_state_file(char **body, size_t *len)+{+ int active, root, bpm, fd, ret;++ active = enforcement_active();+ if (active <= 0)+ return active ? active : read_file(BPM_STATE_PATH, STATE_FILE_MAX, body, len);+ root = state_root_open();+ if (root < 0)+ return root == -ENOENT ? -ENODEV : root;+ bpm = seal_open_child(root, "bpm", O_RDONLY | O_DIRECTORY);+ close(root);+ if (bpm < 0)+ return bpm;+ fd = seal_open_child(bpm, "state.json", O_RDONLY | O_NONBLOCK);+ close(bpm);+ if (fd < 0)+ return fd;+ ret = read_fd(fd, BPM_STATE_PATH, STATE_FILE_MAX, body, len);+ close(fd);+ return ret;+}+int bpm_state_read(struct bpm_state_entry *st, int *n){size_t len;char *body;int ret;- ret = read_file(BPM_STATE_PATH, STATE_FILE_MAX, &body, &len);+ ret = read_state_file(&body, &len);if (ret == -ENOENT) {*n = 0;return 0;@@ -117,6 +144,34 @@ int bpm_state_read(struct bpm_state_entry *st, int *n)return ret;}+static int write_state_file(const char *buf, size_t len)+{+ int active, root, bpm, ret;++ active = enforcement_active();+ if (active < 0)+ return active;+ if (!active) {+ ret = seal_mkdir_p(BPM_VAR_DIR, 0700);+ return ret ? ret : seal_write_file(BPM_STATE_PATH, buf, len, 0600);+ }+ root = state_root_open();+ if (root < 0)+ return root;+ if (mkdirat(root, "bpm", 0700) && errno != EEXIST) {+ ret = -errno;+ close(root);+ return ret;+ }+ bpm = seal_open_child(root, "bpm", O_RDONLY | O_DIRECTORY);+ close(root);+ if (bpm < 0)+ return bpm;+ ret = seal_replace_locked_at(bpm, "state.json", buf, len, 0600);+ close(bpm);+ return ret;+}+int bpm_state_write(const struct bpm_state_entry *st, int n){size_t len = 0;@@ -128,9 +183,7 @@ int bpm_state_write(const struct bpm_state_entry *st, int n)return -ENOMEM;ret = bpm_state_emit(st, n, buf, STATE_EMIT_MAX, &len);if (!ret)- ret = seal_mkdir_p(BPM_VAR_DIR, 0700);- if (!ret)- ret = seal_write_file(BPM_STATE_PATH, buf, len, 0600);+ ret = write_state_file(buf, len);xfree(buf, STATE_EMIT_MAX);return ret;}diff --git a/util/identity.c b/util/identity.cindex 4a2a86cc..115ef676 100644--- a/util/identity.c+++ b/util/identity.c@@ -24,6 +24,7 @@#include "integrity.h"#include "io.h"#include "paths.h"+#include "seal.h"#include "tamper.h"const struct guard_map shirudo_guard_maps[GUARD_MAP_COUNT] = {@@ -148,19 +149,18 @@ int identity_read(struct identity *out)* enters it, so the one directory that holds the identity pin and lies* on the device it records is the bpffs root, reached through any mount.*/-int bpffs_root_open(void)+static int bpffs_open_identity(struct identity *id){- struct identity id;struct stat st;int fd, ret;fd = open(BPFFS_DIR, O_RDONLY | O_DIRECTORY | O_CLOEXEC);if (fd < 0)return -errno;- ret = identity_read_at(fd, IDENTITY_PIN_NAME, &id);+ ret = identity_read_at(fd, IDENTITY_PIN_NAME, id);if (!ret && fstat(fd, &st))ret = -errno;- if (!ret && kernel_dev(st.st_dev) != id.sb_dev)+ if (!ret && kernel_dev(st.st_dev) != id->sb_dev)ret = -EXDEV;if (ret) {close(fd);@@ -168,3 +168,41 @@ int bpffs_root_open(void)}return fd;}++int bpffs_root_open(void)+{+ struct identity id;++ return bpffs_open_identity(&id);+}++int identity_check_state_root(const struct identity *id, int fd)+{+ struct stat st;++ if (fstat(fd, &st))+ return -errno;+ if (!S_ISDIR(st.st_mode) || st.st_dev != id->state_dev || st.st_ino != id->state_ino)+ return -EXDEV;+ return 0;+}++int state_root_open(void)+{+ struct identity id;+ int bpffs, fd, ret;++ bpffs = bpffs_open_identity(&id);+ if (bpffs < 0)+ return bpffs;+ close(bpffs);+ fd = seal_open_state_root();+ if (fd < 0)+ return fd;+ ret = identity_check_state_root(&id, fd);+ if (ret) {+ close(fd);+ return ret;+ }+ return fd;+}diff --git a/util/identity.h b/util/identity.hindex cd6aa35c..6052ae4d 100644--- a/util/identity.h+++ b/util/identity.h@@ -37,6 +37,8 @@ struct identity {__s32 dm_verity_keys[IDENTITY_KEYS_MAX];__u32 nv_index;__u32 config_pcr;+ __u64 state_dev;+ __u64 state_ino;};#define TASK_TRUSTED 1@@ -75,7 +77,7 @@ struct task_policy {BUILD_BUG_ON(sizeof(struct device_authority) != 48);BUILD_BUG_ON(sizeof(struct task_authority) != 8);-BUILD_BUG_ON(sizeof(struct identity) != 648);+BUILD_BUG_ON(sizeof(struct identity) != 664);BUILD_BUG_ON(sizeof(struct task_policy) != 16);/* The bpffs mount init made, which the unmount guard keeps mounted. */@@ -142,5 +144,8 @@ int identity_read_at(int dirfd, const char *name, struct identity *out);* not on that bpffs, another -errno when it cannot be opened or read.*/int bpffs_root_open(void);+/* The sealed state directory whose device and inode init froze this boot. */+int state_root_open(void);+int identity_check_state_root(const struct identity *id, int fd);#endif /* SHIRUDO_UTIL_IDENTITY_H */diff --git a/util/io.c b/util/io.cindex e19639cb..d5ac713a 100644--- a/util/io.c+++ b/util/io.c@@ -130,12 +130,12 @@ int append_line(int fd, const char *path, const char *line, size_t len)* mounts or links elsewhere, /proc/<pid>/fd before an exec say, is* followed.*/-int open_beneath(int dirfd, const char *rel, int flags)+static int open_resolved(int dirfd, const char *rel, int flags, __u64 resolve){struct open_how how = {.flags = (__u64)flags | O_CLOEXEC,.resolve = RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS |- RESOLVE_NO_MAGICLINKS,+ RESOLVE_NO_MAGICLINKS | resolve,};long fd;@@ -145,6 +145,16 @@ int open_beneath(int dirfd, const char *rel, int flags)return fd < 0 ? -errno : (int)fd;}+int open_beneath(int dirfd, const char *rel, int flags)+{+ return open_resolved(dirfd, rel, flags, 0);+}++int open_beneath_same_mount(int dirfd, const char *rel, int flags)+{+ return open_resolved(dirfd, rel, flags, RESOLVE_NO_XDEV);+}+/* The whole regular file behind the descriptor, from its start, xmalloc'd. */static int read_whole(int fd, size_t max, void *out, size_t *len){diff --git a/util/io.h b/util/io.hindex b08e52d9..339fb89d 100644--- a/util/io.h+++ b/util/io.h@@ -36,6 +36,8 @@ int append_line(int fd, const char *path, const char *line, size_t len);int read_file(const char *path, size_t max, void *out, size_t *len);int read_fd(int fd, const char *label, size_t max, void *out, size_t *len);int open_beneath(int dirfd, const char *rel, int flags);+/* Also refuse mount crossings, including bind mounts of the same file system. */+int open_beneath_same_mount(int dirfd, const char *rel, int flags);int read_text_line(FILE *f, char **line, size_t *cap, size_t max);/*diff --git a/util/seal.c b/util/seal.cindex ab4a9ddc..7c9084f3 100644--- a/util/seal.c+++ b/util/seal.c@@ -9,6 +9,8 @@#include <fcntl.h>#include <ftw.h>#include <limits.h>+#include <linux/magic.h>+#include <sys/vfs.h>#include <stdbool.h>#include <stdio.h>#include <string.h>@@ -276,6 +278,53 @@ static int seal_open_dir(const char *path, bool create, mode_t mode)return dfd;}+/* The initrd may bind the state root itself across file systems. */+int seal_open_state_root(void)+{+ char label[SEAL_LABEL_LEN];+ struct statfs fs;+ ssize_t len;+ int fd, ret;++ fd = seal_open_dir(VAR_LIB, false, 0);+ if (fd < 0)+ return fd;+ if (fstatfs(fd, &fs)) {+ ret = -errno;+ } else if (fs.f_type == BPF_FS_MAGIC) {+ ret = -EXDEV;+ } else {+ len = seal_fget(fd, label);+ if (len == SEAL_LABEL_LEN && !memcmp(label, SEAL_LABEL, sizeof(label)))+ return fd;+ ret = len < 0 ? (int)len : -EPERM;+ }+ close(fd);+ return ret;+}++static bool is_child_name(const char *name)+{+ return name && *name && !strchr(name, '/') && strcmp(name, ".") && strcmp(name, "..");+}++int seal_open_child(int parent, const char *name, int flags)+{+ int fd, ret;++ if (!is_child_name(name))+ return -EINVAL;+ fd = open_beneath_same_mount(parent, name, flags);+ if (fd < 0)+ return fd;+ ret = seal_same(parent, fd);+ if (ret) {+ close(fd);+ return ret;+ }+ return fd;+}+static int seal_open_parent(const char *path, const char **name){const char *slash = strrchr(path, '/');@@ -614,27 +663,11 @@ int seal_mkdir_p(const char *path, mode_t mode)return 0;}-static int write_file(const char *path, const void *data, size_t len,- mode_t mode, bool exact)+static int commit_file(int dfd, const char *name, const char *tmp, int fd,+ const void *data, size_t len, mode_t mode, bool exact){- char tmp[NAME_MAX + 1];- const char *name;- int dfd, fd, ret;+ int ret;- dfd = seal_open_parent(path, &name);- if (dfd < 0)- return dfd;- if (strsprintf(tmp, sizeof(tmp), "%s.tmp", name) < 0) {- close(dfd);- return -ENAMETOOLONG;- }- fd = openat(dfd, tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC |- O_NOFOLLOW, mode);- if (fd < 0) {- ret = -errno;- close(dfd);- return ret;- }ret = seal_inherit(dfd, fd);if (!ret && exact && fchmod(fd, mode))ret = -errno;@@ -650,6 +683,47 @@ static int write_file(const char *path, const void *data, size_t len,ret = -errno;if (ret)unlinkat(dfd, tmp, 0);+ return ret;+}++static int write_file_at(int dfd, const char *name, const void *data, size_t len,+ mode_t mode, bool exact, bool exclusive)+{+ char tmp[NAME_MAX + 1];+ int fd, flags = O_TRUNC;++ if (strsprintf(tmp, sizeof(tmp), "%s.tmp", name) < 0)+ return -ENAMETOOLONG;+ if (exclusive) {+ /* The caller holds the lock. Discard an interrupted write. */+ if (unlinkat(dfd, tmp, 0) && errno != ENOENT)+ return -errno;+ flags = O_EXCL;+ }+ fd = openat(dfd, tmp, O_WRONLY | O_CREAT | O_CLOEXEC | O_NOFOLLOW | flags, mode);+ if (fd < 0)+ return -errno;+ return commit_file(dfd, name, tmp, fd, data, len, mode, exact);+}++int seal_replace_locked_at(int parent, const char *name, const void *data, size_t len,+ mode_t mode)+{+ if (!is_child_name(name))+ return -EINVAL;+ return write_file_at(parent, name, data, len, mode, false, true);+}++static int write_file(const char *path, const void *data, size_t len,+ mode_t mode, bool exact)+{+ const char *name;+ int dfd, ret;++ dfd = seal_open_parent(path, &name);+ if (dfd < 0)+ return dfd;+ ret = write_file_at(dfd, name, data, len, mode, exact, false);close(dfd);return ret;}diff --git a/util/seal.h b/util/seal.hindex 7a825843..59c95691 100644--- a/util/seal.h+++ b/util/seal.h@@ -62,6 +62,11 @@ int seal_mkdir_p(const char *path, mode_t mode);*/int seal_open_read(const char *path);+/* Open VAR_LIB itself and require its seal on the opened directory. */+int seal_open_state_root(void);+/* One child of parent, on its mount and carrying its label. */+int seal_open_child(int parent, const char *name, int flags);+/** seal_open_read() of an entry whose directory must carry the label:* one of root's making, which no task without authority can label,@@ -75,6 +80,10 @@ bool seal_owns(const char *path);/* Whether the directory path names an entry of carries the seal label. */bool seal_parent_labeled(const char *path);+/* Under the caller's lock, stage a new file beside a single child name. */+int seal_replace_locked_at(int parent, const char *name, const void *data, size_t len,+ mode_t mode);+int seal_write_file(const char *path, const void *data, size_t len,mode_t mode);/* The same, with exactly that mode whatever the umask, before the rename. */diff --git a/util/upatch.h b/util/upatch.hindex 71be868c..1d37e67a 100644--- a/util/upatch.h+++ b/util/upatch.h@@ -233,6 +233,9 @@ __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);+int upatch_remove_fd(const char *path, int fd);+/* 1 when the load member is active, 0 when absent, or -errno. */+int upatch_member_active_fd(int fd);/* A missing optional kprobe module permits tree projection advancement. */#define UPATCH_INSTALL_TARGET_MISSING 2