eBPF-based security platform
seal: keep foreign entries out of sealed directories
Daniel Borkmanncd4841358031
diff --git a/Documentation/architecture.rst b/Documentation/architecture.rstindex a2b09fea..aa575ffb 100644--- a/Documentation/architecture.rst+++ b/Documentation/architecture.rst@@ -324,7 +324,10 @@ Filesystem seal. Initialization labels existing state undermarks a protected target; its public value does not authorize a caller.The ``file_open`` (for write), ``inode_unlink``, ``inode_rename``,``inode_setattr``, ``inode_setxattr`` and ``inode_removexattr`` hooks require-the caller's committed task authority. Runtime and config files use dm-verity+the caller's committed task authority, and so do ``inode_create``,+``inode_mkdir``, ``inode_symlink``, ``inode_mknod``, ``inode_link`` and a+rename into a marked directory: a sealed directory takes new entries from+shirudo alone. Runtime and config files use dm-verityand receive no seal writes.Only an authorized caller may set the exact seal xattr, including on anunlabelled inode. A binary carrying a copied label gains no authority.@@ -348,10 +351,12 @@ cannot sleep to read the parent xattr, so it uses an inode-storage directorymark populated by directory opens, post-xattr hooks and directory creationunder a marked parent. Shirudo's writers hold an open parent directory andcreate files relative to it; they also apply the label after creation when-the kernel could not. Cached marks can be absent after inode eviction, and-link or rename can introduce an existing unlabelled inode. This does not-authorize every directory-entry change against the parent or revoke-existing writable descriptors and mappings.+the kernel could not. Cached marks can be absent after inode eviction, when+a creation, link or rename can introduce an unlabelled inode; shirudo opens+sealed state without following symbolic links, refuses an entry under a+labelled directory that lacks the label, and ``init`` ignores such an entry+instead of labelling it. Existing writable descriptors and mappings are not+revoked.``ptrace_access_check`` and ``perf_event_alloc`` deny against tasks alreadymarked when those hooks run. The perf allocation check is not serialized withdiff --git a/Documentation/threat-model.rst b/Documentation/threat-model.rstindex f2d4f8a5..038189d5 100644--- a/Documentation/threat-model.rst+++ b/Documentation/threat-model.rst@@ -160,10 +160,18 @@ T3 Tampering with shirudo's files and processpreserve operations on files the caller cannot read. Scratch allocationfailure also requires authority.New inodes inherit their parent's label in the creation transaction- when the parent has a cached seal mark. Shirudo's writers hold the- parent directory open to populate and retain that mark. Directory- eviction and foreign link or rename operations remain subject to- residual risk 15; existing writable references are not revoked.+ when the parent has a cached seal mark, and a marked directory takes+ new entries from shirudo alone: ``inode_create``, ``inode_mkdir``,+ ``inode_symlink``, ``inode_mknod``, ``inode_link`` and a rename into+ it require the caller's authority, so root brings in neither an+ inode with contents nor a link for shirudo to follow. Shirudo's+ writers hold the parent directory open to populate and retain that+ mark, open nothing in sealed state through a symbolic link, and take+ no entry without the label for shirudo's own: ``init`` labels the+ tree on its first run and afterwards ignores a foreign entry rather+ than labelling, following, restoring or failing on it. Directory+ eviction remains subject to residual risk 15; existing writable+ references are not revoked.The authority the seal grants shirudo is not root's to aim: a pathroot names for shirudo to write, a report, an export, evidence ora download, is opened as output, never a labelled inode, never@@ -217,9 +225,9 @@ T5 Silent state changeunreachable for the moment, leaves a register that claims morethan happened and never a detach it does not know; a re-run of``init`` restores nothing once this boot's init event is on- record, and refuses ``tampered`` for an archived artifact that is- not loaded, since root can rename a signed artifact into the- archive and nothing would measure it. An eventlog+ record, refuses ``tampered`` for an archived artifact that carries+ the label but is not loaded, and ignores one without the label,+ which someone else brought in and nothing would measure. An eventlogthat would overflow refuses ``eventlog_full`` before anythinghappens. Every state-changing command reads the register first andrefuses ``tampered`` when ``--expect-chain`` disagrees or the index@@ -491,11 +499,13 @@ Each of these is known, documented and bounded; none is silent.it has seen since the inode came into memory: one opened, onerelabelled, or one created under a marked parent. shirudo opens adirectory before creating in it and puts the label on afterwards- where the kernel could not. Another process creating under a labelled- directory the seal has not seen since the inode was evicted gets an- unlabelled inode, as every creation did before, until the next- ``init`` labels the tree. Rename and link bring an existing inode- in without creating one, so they bring it in unlabelled.+ where the kernel could not. While the mark is absent another process+ can create under a labelled directory, or rename or link an inode+ with its contents into it, and the entry carries no label: shirudo+ opens sealed state without following a symbolic link, refuses an+ entry under a labelled directory that lacks the label, and ``init``+ ignores it rather than labelling it, so such an entry is inert until+ root removes it.Deferred mitigations~~~~~~~~~~~~~~~~~~~~@@ -509,11 +519,9 @@ the separator, and measuring the anchor through ``systemd-pcrextend`` sosystemd's measurement log explains it (residual risk 11); signed PCRpolicies for the kernel and initrd PCRs so a verifier needs no goldenvalues; an in-kernel detach so the pin removal is signed BPF rather-than userspace (residual risk 1); and refusing creation, rename-and link into a labelled directory from any process but shirudo, which-would keep foreign entries out of the tree altogether, and a-``d_instantiate`` hook the BPF LSM can sleep in, which would mark a-directory the moment its dentry is bound (residual risk 15).+than userspace (residual risk 1); and a ``d_instantiate`` hook the BPF+LSM can sleep in, which would mark a directory the moment its dentry is+bound and close the eviction gap (residual risk 15).6) Out of scope---------------diff --git a/Makefile.shirudo b/Makefile.shirudoindex 7644ed2b..b63620d5 100644--- a/Makefile.shirudo+++ b/Makefile.shirudo@@ -670,7 +670,7 @@ testing/helper/test-chain: testing/helper/test-chain.c $(REGISTER_OBJS)$(Q)$(CC) $(CFLAGS) -o $@ $^ $(REGISTER_LIBS)testing/helper/test-tpm-wire: testing/helper/test-tpm-wire.c util/tpm_wire.o util/hex.o \- util/crypto_openssl.o util/io.o util/malloc.o util/log.o \+ util/crypto_openssl.o util/io.o util/seal.o util/malloc.o util/log.o \util/string.o@printf ' CC $@\n'$(Q)$(CC) $(CFLAGS) -o $@ $^ -lcrypto -lssl@@ -684,7 +684,7 @@ testing/helper/tpmsim-cmd: testing/helper/tpmsim-cmd.c@printf ' CC $@\n'$(Q)$(CC) $(CFLAGS_BASE) -Iinclude $(TPMSIM_CFLAGS) -o $@ $< $(TPMSIM_LIBS) -lcrypto-testing/helper/test-config: testing/helper/test-config.c util/config.o util/io.o util/log.o util/hex.o \+testing/helper/test-config: testing/helper/test-config.c util/config.o util/io.o util/seal.o util/log.o util/hex.o \util/image_config.o util/string.o util/malloc.o@printf ' CC $@\n'$(Q)$(CC) $(CFLAGS) -o $@ $^@@ -762,7 +762,7 @@ testing/helper/test-upatch-decode: testing/helper/test-upatch-decode.c \@printf ' CC $@\n'$(Q)$(CC) $(CFLAGS) -o $@ $^ $(DYNAMIC_LIBS)-testing/helper/test-exec-churn: testing/helper/test-exec-churn.c util/io.o util/malloc.o \+testing/helper/test-exec-churn: testing/helper/test-exec-churn.c util/io.o util/seal.o util/malloc.o \util/log.o util/string.o@printf ' CC $@\n'$(Q)$(CC) $(CFLAGS) -o $@ $^@@ -773,7 +773,7 @@ testing/upatch/kernel-obs/exec/exec-paths: testing/upatch/kernel-obs/exec/exec_ptesting/helper/test-config-image: testing/helper/test-config-image.c \util/config_image.o util/crypto_openssl.o util/malloc.o \- util/io.o util/hex.o util/log.o \+ util/io.o util/seal.o util/hex.o util/log.o \util/string.o@printf ' CC $@\n'$(Q)$(CC) $(CFLAGS) -o $@ $^ -lcrypto -lssl@@ -797,7 +797,7 @@ testing/helper/test-image-keys: testing/helper/test-image-keys.c \testing/helper/test-image-config: testing/helper/test-image-config.c \util/image_bootstrap.o util/hex.o util/config_measure.o \util/crypto_openssl.o util/config.o util/image_config.o \- util/io.o util/log.o util/malloc.o \+ util/io.o util/seal.o util/log.o util/malloc.o \util/string.o@printf ' CC $@\n'$(Q)$(CC) $(CFLAGS) -o $@ $^ $(LIBCRYPTO_LIBS) $(LIBSSL_LIBS)@@ -856,7 +856,8 @@ testing/fuzz/fuzz-oci-manifest: testing/fuzz/fuzz-oci-manifest.c \testing/fuzz/fuzz-bpm-index: testing/fuzz/fuzz-bpm-index.c \$(FUZZ_BASE) $(FUZZ_PACKAGE)testing/fuzz/fuzz-tree: testing/fuzz/fuzz-tree.c $(FUZZ_BASE) \- util/bpm_tree.c util/crypto_openssl.c util/io.c+ util/bpm_tree.c util/crypto_openssl.c util/io.c \+ $(FUZZ_SEAL)testing/fuzz/fuzz-upatch: testing/fuzz/fuzz-upatch.c $(FUZZ_BASE) \util/upatch.ctesting/fuzz/fuzz-prog-metadata: testing/fuzz/fuzz-prog-metadata.c \@@ -866,7 +867,8 @@ testing/fuzz/fuzz-bpm-tar: testing/fuzz/fuzz-bpm-tar.c $(FUZZ_BASE) \testing/fuzz/fuzz-bpm-package: testing/fuzz/fuzz-bpm-package.c $(FUZZ_BASE) \$(FUZZ_PACKAGE)testing/fuzz/fuzz-tpm-wire: testing/fuzz/fuzz-tpm-wire.c $(FUZZ_BASE) \- util/tpm_wire.c util/crypto_openssl.c util/io.c+ util/tpm_wire.c util/crypto_openssl.c util/io.c \+ $(FUZZ_SEAL)testing/fuzz/fuzz-attest: testing/fuzz/fuzz-attest.c $(FUZZ_BASE) \util/attest.c util/chain.c util/tpm.c \util/tpm_wire.c util/eventlog.c util/timefmt.c \@@ -894,12 +896,14 @@ testing/fuzz/fuzz-serializer: FUZZ_LIBS += $(LIBBPF_A) $(LIBELF_LIBS)testing/fuzz/fuzz-cms: testing/fuzz/fuzz-cms.c $(FUZZ_BASE) util/keys.c \util/crypto_openssl.c util/io.c $(FUZZ_SEAL)testing/fuzz/fuzz-decoder: testing/fuzz/fuzz-decoder.c $(FUZZ_BASE) \- util/upatch_decode.c util/upatch.c util/io.c+ util/upatch_decode.c util/upatch.c util/io.c \+ $(FUZZ_SEAL)testing/fuzz/fuzz-decoder: FUZZ_CFLAGS += $(LUAJIT_CFLAGS) -DSHIRUDO_HAVE_LUAJITtesting/fuzz/fuzz-decoder: FUZZ_LIBS += $(LUAJIT_LIBS)testing/fuzz/fuzz-otel: testing/fuzz/fuzz-otel.c $(FUZZ_BASE) \util/upatch_maps_otel.c util/crypto_openssl.c \- util/tls_openssl.c util/io.c util/version_id.c+ util/tls_openssl.c util/io.c util/version_id.c \+ $(FUZZ_SEAL)testing/fuzz/fuzz-beefile: testing/fuzz/fuzz-beefile.c $(FUZZ_BASE) \tools/shirudo-build/bpm-build.c $(FUZZ_PACKAGE) \util/upatch.c util/timefmt.c util/paths.c \@@ -911,7 +915,8 @@ testing/fuzz/fuzz-oci-ref: testing/fuzz/fuzz-oci-ref.c $(FUZZ_BASE) \testing/fuzz/fuzz-registry-auth: testing/fuzz/fuzz-registry-auth.c \$(FUZZ_BASE) $(FUZZ_OCI)testing/fuzz/fuzz-config: testing/fuzz/fuzz-config.c $(FUZZ_BASE) \- $(FUZZ_CONFIG) util/io.c util/bpm_source_config.c+ $(FUZZ_CONFIG) util/seal.c util/io.c \+ util/bpm_source_config.cFUZZ_TREE_STATE := util/bpm_tree_state.c util/io.c $(FUZZ_SEAL) \util/kernel_build_id.c util/kernel_release.c \util/crypto_openssl.c testing/fuzz/chain.cdiff --git a/bpf/lib/shirudo_tamper.h b/bpf/lib/shirudo_tamper.hindex dfac84cf..675f98fb 100644--- a/bpf/lib/shirudo_tamper.h+++ b/bpf/lib/shirudo_tamper.h@@ -40,6 +40,7 @@ enum shirudo_tamper_point {SHIRUDO_TAMPER_SEAL_PTRACE,SHIRUDO_TAMPER_SEAL_PERF,SHIRUDO_TAMPER_EXEC_TRACED,+ SHIRUDO_TAMPER_SEAL_ENTRY,SHIRUDO_TAMPER_MAX};diff --git a/bpf/seal.h b/bpf/seal.hindex 0d36f527..f5a2dcb7 100644--- a/bpf/seal.h+++ b/bpf/seal.h@@ -342,7 +342,59 @@ int BPF_PROG(shirudo_seal_inode_unlink, struct inode *dir,return ret ? ret : seal_dentry(dentry, SHIRUDO_TAMPER_SEAL_UNLINK);}-/* Protect both the source and an existing destination of a rename. */+/*+ * A sealed directory takes new entries from shirudo alone. The label a+ * creation inherits stops writes to the new inode, but a rename or a+ * link brings an inode in with its contents, and a symbolic link sends+ * whoever follows it elsewhere. The mark stands in for the label these+ * hooks cannot read.+ */+static __always_inline int seal_dir_entry(struct inode *dir)+{+ if (!bpf_inode_storage_get(&seal_dir_marks, dir, NULL, 0))+ return 0;+ return seal_caller(SHIRUDO_TAMPER_SEAL_ENTRY);+}++SEC("lsm/inode_create")+int BPF_PROG(shirudo_seal_inode_create, const struct mnt_idmap *idmap,+ struct inode *dir, struct dentry *dentry, umode_t mode, int ret)+{+ return ret ? ret : seal_dir_entry(dir);+}++SEC("lsm/inode_mkdir")+int BPF_PROG(shirudo_seal_inode_mkdir, const struct mnt_idmap *idmap,+ struct inode *dir, struct dentry *dentry, umode_t mode, int ret)+{+ return ret ? ret : seal_dir_entry(dir);+}++SEC("lsm/inode_symlink")+int BPF_PROG(shirudo_seal_inode_symlink, const struct mnt_idmap *idmap,+ struct inode *dir, struct dentry *dentry, const char *old_name,+ int ret)+{+ return ret ? ret : seal_dir_entry(dir);+}++SEC("lsm/inode_mknod")+int BPF_PROG(shirudo_seal_inode_mknod, const struct mnt_idmap *idmap,+ struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev,+ int ret)+{+ return ret ? ret : seal_dir_entry(dir);+}++SEC("lsm/inode_link")+int BPF_PROG(shirudo_seal_inode_link, const struct mnt_idmap *idmap,+ struct dentry *old_dentry, struct inode *dir,+ struct dentry *new_dentry, int ret)+{+ return ret ? ret : seal_dir_entry(dir);+}++/* Protect the source, the destination directory and an existing target. */SEC("lsm.s/inode_rename")int BPF_PROG(shirudo_seal_inode_rename, struct inode *old_dir,struct dentry *old_dentry, struct inode *new_dir,@@ -354,6 +406,9 @@ int BPF_PROG(shirudo_seal_inode_rename, struct inode *old_dir,if (ret)return ret;err = seal_dentry(old_dentry, SHIRUDO_TAMPER_SEAL_RENAME);+ if (err)+ return err;+ err = seal_dir_entry(new_dir);if (err)return err;if (!target)diff --git a/builtin-init.c b/builtin-init.cindex 495f6125..abc96899 100644--- a/builtin-init.c+++ b/builtin-init.c@@ -908,15 +908,22 @@ static int boot_restore(bool recorded,rc = -ENAMETOOLONG;goto next;}- if (upatch_open(path, &u) == 0) {- memcpy(set[cnt].name, u.hdr.name,- SHIRUDO_UPATCH_NAME_MAX);- set[cnt].name[SHIRUDO_UPATCH_NAME_MAX] = '\0';- hex_encode(u.hdr.payload_sha256,- SHIRUDO_UPATCH_PAYLOAD_HASH_LEN,- set[cnt].payload_hex);- upatch_close(&u);+ if (!seal_owns(path)) {+ pr_warn("boot-restore: %s is not shirudo's own "+ "(foreign entry); ignored", names[i]->d_name);+ goto next;+ }+ if (upatch_open(path, &u) != 0) {+ pr_warn("boot-restore: %s is not an artifact shirudo "+ "archived (foreign entry); ignored",+ names[i]->d_name);+ goto next;}+ memcpy(set[cnt].name, u.hdr.name, SHIRUDO_UPATCH_NAME_MAX);+ set[cnt].name[SHIRUDO_UPATCH_NAME_MAX] = '\0';+ hex_encode(u.hdr.payload_sha256, SHIRUDO_UPATCH_PAYLOAD_HASH_LEN,+ set[cnt].payload_hex);+ upatch_close(&u);fd = upatch_open_first_link(set[cnt].name);if (fd >= 0) {close(fd);diff --git a/testing/run-target-tests.sh b/testing/run-target-tests.shindex b8fc6981..6ecf0ffc 100755--- a/testing/run-target-tests.sh+++ b/testing/run-target-tests.sh@@ -72,6 +72,7 @@ for t in \tamperproof/t1142-archive-restore.sh \tamperproof/t1143-attach-scope.sh \tamperproof/t1144-signed-metadata.sh \+ tamperproof/t1145-foreign-entries.sh \tamperproof/t1150-verity-devices.sh \tamperproof/t1151-verity-process.sh \tamperproof/t1153-verity-hidden.sh \diff --git a/testing/t0047-seal-create.sh b/testing/t0047-seal-create.shindex 5bf77de7..bfd0a1a0 100755--- a/testing/t0047-seal-create.sh+++ b/testing/t0047-seal-create.sh@@ -82,11 +82,33 @@ test_expect_success 'a symlink gets the label itself, its target untouched' './$H get "$W/plain/target" | grep -qx "label=none"'-test_expect_success 'a directory that exists already is left as it is' '+# What sits under a labelled directory without its label is someone+# else's: never created under, written through or followed.+test_expect_success 'a directory that exists already without the label is refused' 'mkdir "$W/sealed/old" &&- ./$H mkdir "$W/sealed/old/new" | grep -qx "rc=0" &&- ./$H get "$W/sealed/old" | grep -qx "label=none" &&- ./$H get "$W/sealed/old/new" | grep -qx "label=none"+ ! ./$H mkdir "$W/sealed/old/new" | grep -qx "rc=0" &&+ test ! -e "$W/sealed/old/new" &&+ ./$H get "$W/sealed/old" | grep -qx "label=none"+'++test_expect_success 'a file that exists already without the label is refused' '+ echo keep >"$W/sealed/foreign" &&+ ! ./$H open "$W/sealed/foreign" x | grep -qx "rc=0" &&+ [ "$(cat "$W/sealed/foreign")" = keep ] &&+ ./$H get "$W/sealed/foreign" | grep -qx "label=none"+'++test_expect_success 'a symbolic link under a labelled directory is not followed' '+ echo keep >"$W/plain/elsewhere" &&+ ln -s "$W/plain/elsewhere" "$W/sealed/away" &&+ ! ./$H open "$W/sealed/away" x | grep -qx "rc=0" &&+ ./$H write "$W/sealed/away" x | grep -qx "rc=0" &&+ test ! -L "$W/sealed/away" &&+ ./$H get "$W/sealed/away" | grep -qx "label=$LABEL" &&+ [ "$(cat "$W/plain/elsewhere")" = keep ] &&+ ln -s "$W/plain" "$W/sealed/dir" &&+ ! ./$H mkdir "$W/sealed/dir/new" | grep -qx "rc=0" &&+ test ! -e "$W/plain/new"'test_donediff --git a/testing/tamperproof/t1142-archive-restore.sh b/testing/tamperproof/t1142-archive-restore.shindex 8d1c3b21..60d151af 100755--- a/testing/tamperproof/t1142-archive-restore.sh+++ b/testing/tamperproof/t1142-archive-restore.sh@@ -2,16 +2,16 @@# SPDX-License-Identifier: BSD-2-Clause# Copyright (c) 2026 Authors of shirudo#-# t1142 -- an artifact renamed into the archive after the register was+# t1142 -- an artifact brought into the archive after the register was# bound. Rename brings an inode into a sealed directory without creating-# one, so root can place any operator-signed .upatch there; a re-run of-# init used to restore it, attached and pinned, without a register event,-# since this boot's init event was already on record. init must now-# refuse the restore and leave the artifact unloaded, also when the-# state directory is hidden behind a mount that carries no eventlog, and-# must not take a root file system for the initramfs because root wrote-# /etc/initrd-release. Cleaned up through the artifact's own unload-# directive, which removes the archive copy.+# one, so root used to place any operator-signed .upatch there and a+# re-run of init restored it, attached and pinned, without a register+# event. The seal now refuses the rename; one that slips in while the+# directory's mark is evicted carries no label, and init leaves it alone+# instead of labelling, following or restoring it. The restore also+# must not take a state directory hidden behind a mount that carries no+# eventlog for the real one, nor a root file system for the initramfs+# because root wrote /etc/initrd-release.cd "$(dirname "$0")/..". ./integration-lib.sh@@ -37,6 +37,7 @@ restore() {[ ! -e "$STAGE/cert-planted" ] || rm -f "$CERT" || truermdir -p /sysroot/var/lib/shirudo 2>/dev/null || true"$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck >/dev/null 2>&1 || true+ rm -f "$ARCHIVE/$NAME.upatch"rm -rf "$STAGE""$SHIRUDO_BIN" init >/dev/null 2>&1 || true}@@ -48,23 +49,52 @@ chain() {}CHAIN=$(chain)-test_expect_success 'root can rename a signed artifact into the archive' '+counter() {+ "$SHIRUDO_BIN" status --json 2>/dev/null |+ python3 -c "import json,sys; print(json.load(sys.stdin)[\"tamper_attempts\"][\"counters\"][\"SealEntry\"])"+}++# Rename while the directory's mark is evicted, the gap the seal keeps+# (residual risk 15); the entry comes in unlabelled.+plant() {+ i=0+ while [ "$i" -lt 8 ]; do+ sync && echo 2 >/proc/sys/vm/drop_caches &&+ mv "$1" "$2" 2>/dev/null && return 0+ i=$((i + 1))+ done+ return 1+}++labelled() {+ python3 -c "import os,sys+try:+ os.getxattr(sys.argv[1], \"security.bpf.shirudo\", follow_symlinks=False)+except OSError:+ sys.exit(1)" "$1"+}++test_expect_success 'root cannot rename a signed artifact into the archive' '+ before=$(counter) &&mkdir -p "$STAGE" && cp "$LOAD" "$STAGE/$NAME.upatch" &&- mv "$STAGE/$NAME.upatch" "$ARCHIVE/$NAME.upatch" &&- [ -e "$ARCHIVE/$NAME.upatch" ]+ ! mv "$STAGE/$NAME.upatch" "$ARCHIVE/$NAME.upatch" 2>/dev/null &&+ [ ! -e "$ARCHIVE/$NAME.upatch" ] &&+ [ "$(counter)" -gt "$before" ]'-test_expect_success 'a re-run of init refuses to restore it unmeasured' '- ! "$SHIRUDO_BIN" init >/dev/null 2>"$STAGE/init.err" &&- grep -q "archived but not loaded after the register was bound" \+test_expect_success 'one that slips in while the mark is evicted is ignored by init' '+ plant "$STAGE/$NAME.upatch" "$ARCHIVE/$NAME.upatch" &&+ ! labelled "$ARCHIVE/$NAME.upatch" &&+ "$SHIRUDO_BIN" init >/dev/null 2>"$STAGE/init.err" &&+ grep -q "$NAME.upatch is not shirudo.s own (foreign entry); ignored" \"$STAGE/init.err" &&[ ! -e "$PIN" ] &&+ ! labelled "$ARCHIVE/$NAME.upatch" &&[ "$(chain)" = "$CHAIN" ]'-test_expect_success 'the unload directive removes the planted copy and init completes again' '- "$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck --report=- 2>/dev/null |- report_field category | grep -qx already_unloaded &&+test_expect_success 'the foreign entry is root'"'"'s to remove' '+ rm "$ARCHIVE/$NAME.upatch" &&[ ! -e "$ARCHIVE/$NAME.upatch" ] &&"$SHIRUDO_BIN" init >/dev/null 2>&1 &&[ "$(chain)" = "$CHAIN" ]diff --git a/testing/tamperproof/t1145-foreign-entries.sh b/testing/tamperproof/t1145-foreign-entries.shnew file mode 100755index 00000000..0d98853e--- /dev/null+++ b/testing/tamperproof/t1145-foreign-entries.sh@@ -0,0 +1,113 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t1145 -- entries root brings into sealed state. A sealed directory+# takes new entries from shirudo alone: a file, directory, symbolic link+# or device root creates there is refused, and so is a rename or hard+# link, which would bring an inode in with its contents. One that slips+# in while the directory's mark is evicted carries no label: shirudo+# never follows it, adopts it or reads it as its own, and a re-run of+# init completes with it in place. Non-destructive.++cd "$(dirname "$0")/.."+. ./integration-lib.sh+target_guard++FIXTURES=${SHIRUDO_TEST_FIXTURES_DIR:?target fixture directory is not set}+NAME=shirudo-test-scope-kprobe+LOAD="$FIXTURES/$NAME.upatch"+S=/var/lib/shirudo+ARCHIVE=$S/upatches+STAGE=/var/lib/t1145-stage+PIN="/run/shirudo/bpffs/upatches/$NAME/link"+[ -s "$LOAD" ] || test_skip_all "missing scope fixture"+[ ! -e "$PIN" ] || test_skip_all "$NAME is loaded"+[ -d "$ARCHIVE" ] || test_skip_all "no archive at $ARCHIVE"++# Under the library's errexit a failing step would end the cleanup.+restore() {+ rm -f "$ARCHIVE/t1145.upatch" "$ARCHIVE/t1145-link.upatch" \+ "$ARCHIVE/t1145-linked.upatch" "$S/t1145-link" \+ "$S/incoming/t1145-stage" 2>/dev/null || true+ rmdir "$S/t1145-dir" 2>/dev/null || true+ rm -rf "$STAGE"+}+trap restore EXIT++counter() {+ "$SHIRUDO_BIN" status --json 2>/dev/null |+ python3 -c "import json,sys; print(json.load(sys.stdin)[\"tamper_attempts\"][\"counters\"][\"SealEntry\"])"+}++chain() {+ "$SHIRUDO_BIN" status --json 2>/dev/null |+ python3 -c "import json,sys; print(json.load(sys.stdin)[\"tpm\"][\"chain\"])"+}++labelled() {+ python3 -c "import os,sys+try:+ os.getxattr(sys.argv[1], \"security.bpf.shirudo\", follow_symlinks=False)+except OSError:+ sys.exit(1)" "$1"+}++# Rename while the directory's mark is evicted, the gap the seal keeps+# (residual risk 15); the entry comes in unlabelled.+plant() {+ i=0+ while [ "$i" -lt 8 ]; do+ sync && echo 2 >/proc/sys/vm/drop_caches &&+ mv "$1" "$2" 2>/dev/null && return 0+ i=$((i + 1))+ done+ return 1+}++CHAIN=$(chain)++test_expect_success 'root cannot create a file, a directory or a symbolic link in sealed state' '+ before=$(counter) &&+ ! touch "$ARCHIVE/t1145.upatch" 2>/dev/null &&+ ! mkdir "$S/t1145-dir" 2>/dev/null &&+ ! ln -s /tmp "$S/t1145-link" 2>/dev/null &&+ [ ! -e "$ARCHIVE/t1145.upatch" ] && [ ! -e "$S/t1145-dir" ] &&+ [ ! -L "$S/t1145-link" ] &&+ [ "$(counter)" -ge $((before + 3)) ]+'++test_expect_success 'root cannot rename or hard-link content into sealed state' '+ before=$(counter) &&+ mkdir -p "$STAGE" && cp "$LOAD" "$STAGE/t1145.upatch" &&+ ! mv "$STAGE/t1145.upatch" "$ARCHIVE/t1145.upatch" 2>/dev/null &&+ ! ln "$STAGE/t1145.upatch" "$ARCHIVE/t1145-linked.upatch" 2>/dev/null &&+ [ ! -e "$ARCHIVE/t1145.upatch" ] &&+ [ ! -e "$ARCHIVE/t1145-linked.upatch" ] &&+ [ -s "$STAGE/t1145.upatch" ] &&+ [ "$(counter)" -ge $((before + 2)) ]+'++# The archive entry is a link to a signed artifact root keeps elsewhere:+# init must neither follow it nor label it.+test_expect_success 'a link that slipped in while the mark was evicted is not followed' '+ mkdir -p "$STAGE" && cp "$LOAD" "$STAGE/$NAME.upatch" &&+ ln -s "$STAGE/$NAME.upatch" "$STAGE/t1145-link.upatch" &&+ plant "$STAGE/t1145-link.upatch" "$ARCHIVE/t1145-link.upatch" &&+ [ -L "$ARCHIVE/t1145-link.upatch" ] &&+ "$SHIRUDO_BIN" init >/dev/null 2>"$STAGE/init.err" &&+ grep -q "t1145-link.upatch is not shirudo.s own (foreign entry); ignored" \+ "$STAGE/init.err" &&+ [ ! -e "$PIN" ] &&+ ! labelled "$ARCHIVE/t1145-link.upatch" &&+ [ "$(chain)" = "$CHAIN" ] &&+ rm "$ARCHIVE/t1145-link.upatch"+'++test_expect_success 'root cannot plant a link where shirudo stages' '+ [ -d "$S/incoming" ] &&+ ! ln -s "$STAGE" "$S/incoming/t1145-stage" 2>/dev/null &&+ [ ! -L "$S/incoming/t1145-stage" ]+'++test_donediff --git a/util/bpm_package.c b/util/bpm_package.cindex f02d80ad..0d4a5a56 100644--- a/util/bpm_package.c+++ b/util/bpm_package.c@@ -6,6 +6,7 @@*/#include <errno.h>+#include <fcntl.h>#include <stdbool.h>#include <stdint.h>#include <stdio.h>@@ -13,6 +14,7 @@#include <string.h>#include <strings.h>#include <sys/stat.h>+#include <unistd.h>#include <zlib.h>#include <openssl/bio.h>#include <openssl/evp.h>@@ -27,6 +29,7 @@#include "bpm_tree.h"#include "crypto.h"#include "hex.h"+#include "io.h"#include "json.h"#include "log.h"#include "macros.h"@@ -613,7 +616,7 @@ int bpm_pkg_extract(const char *archive, const char *dest)break;} else if (type == '0') {char parent[PATH_MAX];- FILE *fp;+ int fd;strscpy(parent, path, sizeof(parent));slash = strrchr(parent, '/');@@ -623,9 +626,9 @@ int bpm_pkg_extract(const char *archive, const char *dest)if (rc)break;}- fp = fopen(path, "wb");- if (!fp) {- rc = -errno;+ fd = seal_open(path, O_WRONLY | O_CREAT | O_EXCL, 0644);+ if (fd < 0) {+ rc = fd;break;}remain = size;@@ -634,16 +637,17 @@ int bpm_pkg_extract(const char *archive, const char *dest)size_t want = remain > sizeof(buf) ? sizeof(buf) : (size_t)remain;n = gzread(gz, buf, (__u32)want);- if (n <= 0 || fwrite(buf, 1, (size_t)n, fp) != (size_t)n) {+ if (n <= 0 || write_complete(fd, buf, (size_t)n)) {rc = -EIO;break;}remain -= (size_t)n;}- fclose(fp);+ if (!rc && fchmod(fd, 0644))+ rc = -errno;+ close(fd);if (rc)break;- chmod(path, 0644);} else {rc = -EPERM;break;diff --git a/util/image_guards.c b/util/image_guards.cindex f8be3604..3da9efac 100644--- a/util/image_guards.c+++ b/util/image_guards.c@@ -44,6 +44,11 @@ shirudo_seal_guards[SHIRUDO_SEAL_HOOK_COUNT] = {SHIRUDO_SEAL_POST_RMXATTR_PIN },{ "shirudo_seal_inode_init_security",SHIRUDO_SEAL_INIT_SECURITY_PIN },+ { "shirudo_seal_inode_create", SHIRUDO_SEAL_CREATE_PIN },+ { "shirudo_seal_inode_mkdir", SHIRUDO_SEAL_MKDIR_PIN },+ { "shirudo_seal_inode_symlink", SHIRUDO_SEAL_SYMLINK_PIN },+ { "shirudo_seal_inode_mknod", SHIRUDO_SEAL_MKNOD_PIN },+ { "shirudo_seal_inode_link", SHIRUDO_SEAL_LINK_PIN },{ "shirudo_seal_ptrace_access_check",SHIRUDO_SEAL_PTRACE_PIN },{ "shirudo_seal_perf_event_alloc",diff --git a/util/image_guards.h b/util/image_guards.hindex b441e349..22aba36d 100644--- a/util/image_guards.h+++ b/util/image_guards.h@@ -8,7 +8,7 @@#include <stdint.h>-#define SHIRUDO_SEAL_HOOK_COUNT 14+#define SHIRUDO_SEAL_HOOK_COUNT 19#define SHIRUDO_IMAGE_SEAL_HOOK_COUNT 2#define SHIRUDO_MOUNT_HOOK_COUNT 4#define SHIRUDO_OBSERVER_HOOK_COUNT 4diff --git a/util/io.c b/util/io.cindex 398666ed..f1537264 100644--- a/util/io.c+++ b/util/io.c@@ -16,6 +16,9 @@#include "log.h"#include "malloc.h"#include "paths.h"+#include "seal.h"++static bool under(const char *path, const char *dir);int write_complete(int fd, const void *buf, size_t len){@@ -44,9 +47,12 @@ int read_file(const char *path, size_t max, void *out, size_t *len)size_t left;int fd, rc;- fd = open(path, O_RDONLY | O_CLOEXEC);+ if (under(path, SHIRUDO_VAR_LIB))+ fd = seal_open_read(path);+ else+ fd = open(path, O_RDONLY | O_CLOEXEC);if (fd < 0)- return -errno;+ return fd == -1 ? -errno : fd;if (fstat(fd, &st) != 0) {rc = -errno;goto out;diff --git a/util/paths.h b/util/paths.hindex 0820529f..44fcc983 100644--- a/util/paths.h+++ b/util/paths.h@@ -99,6 +99,11 @@#define SHIRUDO_SEAL_POST_SETXATTR_PIN SHIRUDO_BPFFS_DIR "/seal_inode_post_setxattr_link"#define SHIRUDO_SEAL_POST_RMXATTR_PIN SHIRUDO_BPFFS_DIR "/seal_inode_post_removexattr_link"#define SHIRUDO_SEAL_INIT_SECURITY_PIN SHIRUDO_BPFFS_DIR "/seal_inode_init_security_link"+#define SHIRUDO_SEAL_CREATE_PIN SHIRUDO_BPFFS_DIR "/seal_inode_create_link"+#define SHIRUDO_SEAL_MKDIR_PIN SHIRUDO_BPFFS_DIR "/seal_inode_mkdir_link"+#define SHIRUDO_SEAL_SYMLINK_PIN SHIRUDO_BPFFS_DIR "/seal_inode_symlink_link"+#define SHIRUDO_SEAL_MKNOD_PIN SHIRUDO_BPFFS_DIR "/seal_inode_mknod_link"+#define SHIRUDO_SEAL_LINK_PIN SHIRUDO_BPFFS_DIR "/seal_inode_link_link"#define SHIRUDO_BPFFS_UPATCHES_DIR SHIRUDO_BPFFS_DIR "/upatches"#define SHIRUDO_IDENTITY_PIN SHIRUDO_BPFFS_DIR "/identity"#define SHIRUDO_TAMPER_PIN SHIRUDO_BPFFS_DIR "/tamper"diff --git a/util/seal.c b/util/seal.cindex fc294acf..4958cce0 100644--- a/util/seal.c+++ b/util/seal.c@@ -41,10 +41,20 @@ int seal_label(const char *path)*/static dev_t seal_root_dev;static int seal_walk_error;+static bool seal_first_init;+static ssize_t seal_lget(const char *path, char label[SEAL_LABEL_LEN]);++/*+ * The first init labels what the install left; from then on everything+ * shirudo makes is labelled as it is made, so an entry without the label,+ * or one of a kind shirudo never makes, came from someone else: it is+ * left alone, never labelled, followed or read as shirudo's own.+ */static int seal_label_cb(const char *path, const struct stat *sb,int typeflag, struct FTW *ftwbuf){+ char label[SEAL_LABEL_LEN];int rc;(void)typeflag;@@ -57,10 +67,18 @@ static int seal_label_cb(const char *path, const struct stat *sb,*/if (sb->st_dev != seal_root_dev)return 0;- if (!S_ISREG(sb->st_mode) && !S_ISDIR(sb->st_mode))- rc = -EINVAL;- else- rc = seal_label(path);+ if (!S_ISREG(sb->st_mode) && !S_ISDIR(sb->st_mode)) {+ pr_warn("seal: %s is not a file or directory of shirudo's "+ "(foreign entry); ignored", path);+ return 0;+ }+ if (!seal_first_init) {+ if (seal_lget(path, label) <= 0)+ pr_warn("seal: %s carries no label (foreign entry); "+ "ignored", path);+ return 0;+ }+ rc = seal_label(path);if (rc) {pr_err("seal: label %s: %s", path, strerror(-rc));seal_walk_error = rc;@@ -71,12 +89,14 @@ static int seal_label_cb(const char *path, const struct stat *sb,int seal_label_tree(void){+ char label[SEAL_LABEL_LEN];struct stat st;if (stat(SHIRUDO_VAR_LIB, &st) != 0)return -errno;seal_root_dev = st.st_dev;seal_walk_error = 0;+ seal_first_init = seal_lget(SHIRUDO_VAR_LIB, label) <= 0;if (nftw(SHIRUDO_VAR_LIB, seal_label_cb, 16, FTW_PHYS | FTW_MOUNT) != 0)return seal_walk_error ? seal_walk_error : -errno;return 0;@@ -107,6 +127,79 @@ static ssize_t seal_lget(const char *path, char label[SEAL_LABEL_LEN])SEAL_LABEL_LEN));}+/*+ * Whether the inode behind fd is of the directory open as dfd: under a+ * labelled directory an entry must carry the same label, so a file or+ * directory someone renamed or linked in, or made while the seal could+ * not label it, is refused rather than taken for shirudo's own. 0 when+ * it is, or the directory carries no label, -EPERM when it is not.+ */+static int seal_same(int dfd, int fd)+{+ char parent[SEAL_LABEL_LEN], own[SEAL_LABEL_LEN];+ ssize_t plen, olen;++ plen = seal_fget(dfd, parent);+ if (plen <= 0)+ return (int)plen;+ olen = seal_fget(fd, own);+ if (olen < 0)+ return (int)olen;+ if (olen == plen && !memcmp(parent, own, (size_t)plen))+ return 0;+ return -EPERM;+}++/*+ * Open a directory by walking its components, following no symbolic+ * link and taking no foreign entry for shirudo's own; with create, make+ * what is missing, labelled as its parent is.+ */+static int seal_open_dir(const char *path, bool create, mode_t mode)+{+ char buf[PATH_MAX], *comp, *save;+ int dfd, nfd, rc = 0;+ bool created;++ if (strscpy(buf, path, sizeof(buf)) < 0)+ return -ENAMETOOLONG;+ dfd = open(buf[0] == '/' ? "/" : ".",+ O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ if (dfd < 0)+ return -errno;+ for (comp = strtok_r(buf, "/", &save); comp;+ comp = strtok_r(NULL, "/", &save)) {+ created = create && mkdirat(dfd, comp, mode) == 0;+ if (create && !created && errno != EEXIST) {+ rc = -errno;+ break;+ }+ nfd = openat(dfd, comp, O_RDONLY | O_DIRECTORY | O_NOFOLLOW |+ O_CLOEXEC);+ if (nfd < 0) {+ rc = -errno;+ if (rc == -ELOOP || rc == -ENOTDIR)+ pr_err("%s: %s is not a directory of shirudo's "+ "(foreign entry in sealed state)", path,+ comp);+ break;+ }+ rc = created ? seal_inherit(dfd, nfd) : seal_same(dfd, nfd);+ if (rc == -EPERM)+ pr_err("%s: %s carries no label (foreign entry in "+ "sealed state); refusing", path, comp);+ close(dfd);+ dfd = nfd;+ if (rc)+ break;+ }+ if (rc) {+ close(dfd);+ return rc;+ }+ return dfd;+}+static int seal_open_parent(const char *path, const char **name){const char *slash = strrchr(path, '/');@@ -117,6 +210,8 @@ static int seal_open_parent(const char *path, const char **name)if (!slash) {*name = path;fd = open(".", O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ if (fd < 0)+ return -errno;} else {len = slash == path ? 1 : (size_t)(slash - path);if (len >= sizeof(dir))@@ -124,10 +219,10 @@ static int seal_open_parent(const char *path, const char **name)memcpy(dir, path, len);dir[len] = '\0';*name = slash + 1;- fd = open(dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ fd = seal_open_dir(dir, false, 0);+ if (fd < 0)+ return fd;}- if (fd < 0)- return -errno;if (!**name) {close(fd);return -EINVAL;@@ -239,54 +334,78 @@ int seal_open(const char *path, int flags, mode_t mode)dfd = seal_open_parent(path, &name);if (dfd < 0)return dfd;- fd = openat(dfd, name, flags | O_CLOEXEC, mode);- if (fd < 0) {+ fd = openat(dfd, name, (flags & ~(O_CREAT | O_TRUNC)) | O_NOFOLLOW |+ O_CLOEXEC, mode);+ if (fd >= 0) {+ if (flags & O_EXCL) {+ rc = -EEXIST;+ } else {+ rc = seal_same(dfd, fd);+ if (rc == -EPERM)+ pr_err("%s: carries no label (foreign entry "+ "in sealed state); refusing", path);+ if (!rc && (flags & O_TRUNC) && ftruncate(fd, 0))+ rc = -errno;+ }+ } else if (errno == ENOENT && (flags & O_CREAT)) {+ fd = openat(dfd, name, flags | O_EXCL | O_NOFOLLOW | O_CLOEXEC,+ mode);+ rc = fd < 0 ? -errno : seal_inherit(dfd, fd);+ } else {rc = -errno;- close(dfd);- return rc;+ if (rc == -ELOOP)+ pr_err("%s: is a symbolic link (foreign entry in "+ "sealed state); refusing", path);}- rc = seal_inherit(dfd, fd);close(dfd);if (rc) {- close(fd);+ if (fd >= 0)+ close(fd);return rc;}return fd;}-int seal_mkdir_p(const char *path, mode_t mode)+int seal_open_read(const char *path){- char buf[PATH_MAX], *comp, *save;- int dfd, nfd, rc = 0;- bool created;+ const char *name;+ int dfd, fd, rc;- if (strscpy(buf, path, sizeof(buf)) < 0)- return -ENAMETOOLONG;- dfd = open(buf[0] == '/' ? "/" : ".",- O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ dfd = seal_open_parent(path, &name);if (dfd < 0)- return -errno;- for (comp = strtok_r(buf, "/", &save); comp;- comp = strtok_r(NULL, "/", &save)) {- created = mkdirat(dfd, comp, mode) == 0;- if (!created && errno != EEXIST) {- rc = -errno;- break;- }- nfd = openat(dfd, comp, O_RDONLY | O_DIRECTORY | O_CLOEXEC);- if (nfd < 0) {- rc = -errno;- break;- }- if (created)- rc = seal_inherit(dfd, nfd);- close(dfd);- dfd = nfd;- if (rc)- break;- }+ return dfd;+ fd = openat(dfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);+ rc = fd < 0 ? -errno : seal_same(dfd, fd);close(dfd);- return rc;+ if (rc) {+ if (fd >= 0)+ close(fd);+ if (rc == -EPERM || rc == -ELOOP)+ pr_err("%s: not shirudo's own (foreign entry in sealed "+ "state); refusing to read it", path);+ return rc;+ }+ return fd;+}++bool seal_owns(const char *path)+{+ int fd = seal_open_read(path);++ if (fd < 0)+ return false;+ close(fd);+ return true;+}++int seal_mkdir_p(const char *path, mode_t mode)+{+ int fd = seal_open_dir(path, true, mode);++ if (fd < 0)+ return fd;+ close(fd);+ return 0;}int seal_write_file(const char *path, const void *data, size_t len,diff --git a/util/seal.h b/util/seal.hindex b83ff563..02214a41 100644--- a/util/seal.h+++ b/util/seal.h@@ -8,6 +8,7 @@#ifndef SHIRUDO_SEAL_H#define SHIRUDO_SEAL_H+#include <stdbool.h>#include <stddef.h>#include <sys/types.h>@@ -24,8 +25,10 @@int seal_label(const char *path);/*- * Label writable state before attaching the seal. Refuse non-file entries- * and stop on the first failed label; partial sealing is an init failure.+ * Label writable state before attaching the seal: everything on the+ * first init, nothing afterwards, when an entry without the label or of+ * a kind shirudo never makes is someone else's and is ignored. Stop on+ * the first failed label; partial sealing is an init failure.*/int seal_label_tree(void);@@ -46,6 +49,16 @@ int seal_open(const char *path, int flags, mode_t mode);/* mkdir -p, every directory created labelled as its parent is. */int seal_mkdir_p(const char *path, mode_t mode);+/*+ * Open an entry of sealed state for reading, as shirudo's own: not+ * through a symbolic link, and under a labelled directory only when it+ * carries that label. -EPERM for a foreign entry.+ */+int seal_open_read(const char *path);++/* Whether seal_open_read() would succeed. */+bool seal_owns(const char *path);+int seal_write_file(const char *path, const void *data, size_t len,mode_t mode);diff --git a/util/tamper.c b/util/tamper.cindex 592c3752..fae86ef4 100644--- a/util/tamper.c+++ b/util/tamper.c@@ -78,6 +78,8 @@ static const struct {"perf event bound to a shirudo task" },[SHIRUDO_TAMPER_EXEC_TRACED] = { "ExecTraced","exec of shirudo by a traced task" },+ [SHIRUDO_TAMPER_SEAL_ENTRY] = { "SealEntry",+ "entry created, linked or renamed into a sealed directory" },};const char *tamper_name(enum shirudo_tamper_point point)