eBPF-based security platform
bpf: block PR_SET_MM impersonation of shirudo
John Fastabend21d891ee7349
diff --git a/Documentation/architecture.rst b/Documentation/architecture.rstindex b7cc8386..14b53a22 100644--- a/Documentation/architecture.rst+++ b/Documentation/architecture.rst@@ -237,9 +237,14 @@ Everything else, including``lsm/bpf_map`` denies writable map file descriptors when the caller'sexecutable identity is not shirudo. Root can retrieve read-only map fdsfor observation, but direct map updates and writable mappings of arena-maps are denied. As with the other ``bpf2`` executable-identity gates,-a process with ``CAP_SYS_RESOURCE`` can spoof ``mm->exe_file``; this-remains a residual risk.+maps are denied. The ``task_prctl`` and ``file_permission`` hooks scope+the kernel's executable-file check during ``PR_SET_MM_EXE_FILE`` and+``PR_SET_MM_MAP``. They deny only when the resolved file matches the+device and inode of Shirudo's frozen executable identity, including the+initrd copy. Other ``PR_SET_MM`` targets and ordinary executable-file+checks are unaffected. A process that directly executes the recorded+Shirudo binary is still identified as Shirudo; its command interface is+the authorization boundary for those operations.``lsm/bpf_prog_load`` runs after the kernel's signature check and admitsa program only when the verdict is ``BPF_SIG_VERIFIED`` and thediff --git a/Documentation/threat-model.rst b/Documentation/threat-model.rstindex d5d6bc55..fcbe2cb0 100644--- a/Documentation/threat-model.rst+++ b/Documentation/threat-model.rst@@ -262,13 +262,15 @@ Each of these is known, documented and bounded; none is silent.honest substitution; closing this fully needs an in-kernel detach sothe compare runs against signed ``.rodata``.-2. ``CAP_SYS_RESOURCE`` can rewrite ``mm->exe_file`` with- ``prctl(PR_SET_MM_EXE_FILE)``. A root process with that capability- that can open shirudo's binary impersonates it to the seal, bpffs- and BPF map guards. Bound ``CAP_SYS_RESOURCE`` out of untrusted contexts- with ``CapabilityBoundingSet=`` and container capability profiles.- This is a property of the kernel's process model, not a shirudo- bug to fix.+2. ``CAP_SYS_RESOURCE`` can rewrite ``mm->exe_file``. Shirudo's+ ``task_prctl`` and ``file_permission`` LSM hooks deny+ ``PR_SET_MM_EXE_FILE`` and ``PR_SET_MM_MAP`` when the resolved file+ is either frozen Shirudo executable inode, while leaving other+ targets alone. A process that directly executes the recorded+ Shirudo binary is still identified as Shirudo, so its command+ interface remains the authorization boundary. Bound+ ``CAP_SYS_RESOURCE`` out of untrusted contexts with+ ``CapabilityBoundingSet=`` and container capability profiles.3. A lazy (``MNT_DETACH``) unmount of an ancestor of``/run/shirudo/bpffs`` tears the subtree down without firingdiff --git a/bpf/bpf2.c b/bpf/bpf2.cindex 93996d11..24e80d39 100644--- a/bpf/bpf2.c+++ b/bpf/bpf2.c@@ -44,8 +44,9 @@* while letting `shirudo upatch unload` remove* a pin to detach a program. The exe-inode check* is the interim of the xattr-based identity- * seal will use; both are defeatable only with- * CAP_SYS_RESOURCE (threat-model residual #12).+ * seal will use. The task_prctl and+ * file_permission hooks below prevent changing+ * mm->exe_file to either recorded Shirudo inode.* lsm/key_permission -- guards the trust anchor in the kernel's* keyrings: the sealed keyring init froze and the* keys it holds may be viewed and searched by@@ -75,6 +76,12 @@* the pinned links and detaches ALL enforcement,* since shirudo is agentless and the pins are the* links' only reference. See the hook block below.+ * lsm/task_prctl,+ * lsm/file_permission,+ * tracepoint/sys_exit_prctl -- scope PR_SET_MM executable changes and deny+ * only when the resolved file is one of the frozen+ * Shirudo executable inodes. Task storage is cleared+ * at syscall exit when an earlier kernel check fails.*/#include "vmlinux.h"@@ -88,9 +95,22 @@#ifndef EACCES#define EACCES 13#endif+#ifndef ENOMEM+#define ENOMEM 12+#endif+#ifndef ENOSYS+#define ENOSYS 38+#endif#ifndef FMODE_WRITE#define FMODE_WRITE 0x2#endif+#ifndef MAY_EXEC+#define MAY_EXEC 0x1+#endif++#define PR_SET_MM 35+#define PR_SET_MM_EXE_FILE 13+#define PR_SET_MM_MAP 14char _license[] SEC("license") = "Dual BSD/GPL";@@ -125,6 +145,17 @@ struct {__type(value, struct shirudo_sb_id);} shirudo_bpffs_sb SEC(".maps");+struct shirudo_prctl_state {+ __u32 pending;+};++struct {+ __uint(type, BPF_MAP_TYPE_TASK_STORAGE);+ __uint(map_flags, BPF_F_NO_PREALLOC);+ __type(key, int);+ __type(value, struct shirudo_prctl_state);+} shirudo_prctl_state_map SEC(".maps");+static __always_inline boolshirudo_task_is_self(const struct shirudo_sb_id *id);@@ -327,6 +358,84 @@ static __always_inline bool shirudo_task_is_self(const struct shirudo_sb_id *id)exe_ino == id->alt_exe_ino;}+static __always_inline bool shirudo_file_is_self(+ const struct shirudo_sb_id *id,+ struct file *file)+{+ struct inode *inode;+ __u32 dev;+ __u64 ino;++ if (!file)+ return false;+ inode = BPF_CORE_READ(file, f_inode);+ if (!inode)+ return false;+ dev = BPF_CORE_READ(inode, i_sb, s_dev);+ ino = BPF_CORE_READ(inode, i_ino);+ if (dev == id->exe_dev && ino == id->exe_ino)+ return true;+ return id->alt_exe_ino && dev == id->alt_exe_dev &&+ ino == id->alt_exe_ino;+}++SEC("lsm/task_prctl")+int BPF_PROG(shirudo_lsm_task_prctl, int option, unsigned long arg2,+ unsigned long arg3, unsigned long arg4, unsigned long arg5,+ int ret)+{+ struct task_struct *task = bpf_get_current_task_btf();+ struct shirudo_prctl_state *state;++ (void)arg3;+ (void)arg4;+ (void)arg5;+ if ((ret && ret != -ENOSYS) || option != PR_SET_MM ||+ (arg2 != PR_SET_MM_EXE_FILE && arg2 != PR_SET_MM_MAP))+ return ret ? ret : -ENOSYS;+ state = bpf_task_storage_get(&shirudo_prctl_state_map, task, NULL,+ BPF_LOCAL_STORAGE_GET_F_CREATE);+ if (!state)+ return -ENOMEM;+ state->pending = 1;+ return -ENOSYS;+}++SEC("lsm/file_permission")+int BPF_PROG(shirudo_lsm_file_permission, struct file *file, int mask,+ int ret)+{+ struct task_struct *task = bpf_get_current_task_btf();+ struct shirudo_prctl_state *state;+ struct shirudo_sb_id *id;+ __u32 zero = 0;++ if (ret || !(mask & MAY_EXEC))+ return ret;+ state = bpf_task_storage_get(&shirudo_prctl_state_map, task, NULL, 0);+ if (!state || !state->pending)+ return ret;+ state->pending = 0;+ bpf_task_storage_delete(&shirudo_prctl_state_map, task);+ id = bpf_map_lookup_elem(&shirudo_bpffs_sb, &zero);+ if (!id)+ return -EACCES;+ return shirudo_file_is_self(id, file) ? -EPERM : 0;+}++SEC("tracepoint/syscalls/sys_exit_prctl")+int shirudo_trace_sys_exit_prctl(struct trace_event_raw_sys_exit *ctx)+{+ struct task_struct *task = bpf_get_current_task_btf();+ struct shirudo_prctl_state *state;++ (void)ctx;+ state = bpf_task_storage_get(&shirudo_prctl_state_map, task, NULL, 0);+ if (state)+ bpf_task_storage_delete(&shirudo_prctl_state_map, task);+ return 0;+}+/** Verdict for an operation targeting an inode in superblock target_dev:* allow (0) if it is not shirudo's bpffs, or if the calling task'sdiff --git a/builtin-init.c b/builtin-init.cindex 2dc66436..3f6283d2 100644--- a/builtin-init.c+++ b/builtin-init.c@@ -742,6 +742,17 @@ static int init_lsm(bool attach_filesystem_seal){ "shirudo_lsm_sb_mount", SHIRUDO_SB_MOUNT_LINK_PIN },{ "shirudo_lsm_sb_remount", SHIRUDO_SB_REMOUNT_LINK_PIN },};+ static const struct {+ const char *prog;+ const char *pin;+ } prctl_hooks[] = {+ { "shirudo_lsm_file_permission",+ SHIRUDO_FILE_PERMISSION_LINK_PIN },+ { "shirudo_trace_sys_exit_prctl",+ SHIRUDO_PRCTL_EXIT_LINK_PIN },+ { "shirudo_lsm_task_prctl", SHIRUDO_TASK_PRCTL_LINK_PIN },+ };+ struct bpf_link *prctl_links[ARRAY_SIZE(prctl_hooks)] = {};struct bpf_link *mount_links[ARRAY_SIZE(mount_hooks)] = {};const struct shirudo_embedded_bpf *blob = shirudo_bpf2_blob();struct bpf_program *p_bpf, *p_unlink, *p_setx, *p_rmx, *p_pload;@@ -876,6 +887,25 @@ static int init_lsm(bool attach_filesystem_seal)goto out;}+ /* Install the narrow prctl guard before enabling the bpf() gates. */+ for (i = 0; i < (int)ARRAY_SIZE(prctl_hooks); i++) {+ struct bpf_program *p = bpf_object__find_program_by_name(+ obj, prctl_hooks[i].prog);++ if (!p) {+ pr_err("program %s missing in bpf2 object",+ prctl_hooks[i].prog);+ err = -ENOENT;+ goto out;+ }+ err = attach_pin(p, prctl_hooks[i].pin, &prctl_links[i]);+ if (err) {+ pr_err("attach %s: %s", prctl_hooks[i].prog,+ strerror(-err));+ goto out;+ }+ }+p_unlink = bpf_object__find_program_by_name(obj,"shirudo_lsm_inode_unlink");p_setx = bpf_object__find_program_by_name(obj,@@ -895,12 +925,11 @@ static int init_lsm(bool attach_filesystem_seal)}/*- * Order: the bpffs guards (inode_unlink/setxattr/removexattr), then- * seal's filesystem and exec-identity hooks, then the bpf() gates- * (bpf_prog_load admission, then lsm/bpf) LAST. Pinning a link- * creates a bpffs inode, gated by neither guard set; seal's unsigned- * load and the identity-map freeze must both precede the load gates- * going live.+ * The prctl identity guard is already active. Order the remaining+ * hooks as bpffs guards, seal's filesystem and exec-identity hooks,+ * then the bpf() gates (bpf_prog_load admission, then lsm/bpf) LAST.+ * Pinning a link creates a bpffs inode, gated by neither guard set;+ * seal's unsigned load and the identity-map freeze precede the gates.*/err = attach_pin(p_unlink, SHIRUDO_INODE_UNLINK_LINK_PIN, &link_unlink);if (err) {@@ -973,6 +1002,11 @@ static int init_lsm(bool attach_filesystem_seal)", filesystem seal unavailable on this kernel");err = 0;out:+ for (i = 0; i < (int)ARRAY_SIZE(prctl_links); i++) {+ if (err && prctl_links[i])+ bpf_link__unpin(prctl_links[i]);+ bpf_link__destroy(prctl_links[i]);+ }for (i = 0; i < (int)ARRAY_SIZE(seal_links); i++)bpf_link__destroy(seal_links[i]);for (i = 0; i < (int)ARRAY_SIZE(mount_links); i++)diff --git a/testing/run-target-tests.sh b/testing/run-target-tests.shindex d96d6ccf..6da3bcbf 100755--- a/testing/run-target-tests.sh+++ b/testing/run-target-tests.sh@@ -38,6 +38,7 @@ for t in \tamperproof/t1112-prog-load-keyring-gate.sh \tamperproof/t1113-mount-lockdown.sh \tamperproof/t1130-map-lockdown.sh \+ tamperproof/t1131-pr-set-mm-identity.sh \tamperproof/t1121-bpf-keyring.sh \tamperproof/t1125-key-permission.sh \tamperproof/t1106-keyring-swap.shdiff --git a/testing/t0015-test-vm-cli.sh b/testing/t0015-test-vm-cli.shindex 36f35dd1..9a528fac 100755--- a/testing/t0015-test-vm-cli.sh+++ b/testing/t0015-test-vm-cli.sh@@ -574,6 +574,7 @@ test_expect_success 'operator and target runners have disjoint explicit scopes'tamperproof/t1112-prog-load-keyring-gate.sh \tamperproof/t1113-mount-lockdown.sh \tamperproof/t1130-map-lockdown.sh \+ tamperproof/t1131-pr-set-mm-identity.sh \tamperproof/t1121-bpf-keyring.sh \tamperproof/t1125-key-permission.sh \tamperproof/t1106-keyring-swap.shdiff --git a/testing/tamperproof/t1130-map-lockdown.sh b/testing/tamperproof/t1130-map-lockdown.shindex d0bc8dd4..69bd7ec5 100644--- a/testing/tamperproof/t1130-map-lockdown.sh+++ b/testing/tamperproof/t1130-map-lockdown.sh@@ -4,7 +4,7 @@## t1130 -- direct BPF syscalls from a root process with a different# executable cannot acquire writable map fds or mutate Shirudo's maps.-# CAP_SYS_RESOURCE can spoof the executable identity and remains a risk.+# PR_SET_MM executable spoofing is covered separately by t1131.cd "$(dirname "$0")/..". ./integration-lib.shdiff --git a/testing/tamperproof/t1131-pr-set-mm-identity.py b/testing/tamperproof/t1131-pr-set-mm-identity.pynew file mode 100644index 00000000..89167657--- /dev/null+++ b/testing/tamperproof/t1131-pr-set-mm-identity.py@@ -0,0 +1,139 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++import ctypes+import errno+import os+import sys++PR_SET_MM = 35+PR_SET_MM_EXE_FILE = 13+PR_SET_MM_MAP = 14+SHIRUDO = os.path.abspath(sys.argv[1])+SHIRUDO_ID = os.stat(SHIRUDO).st_dev, os.stat(SHIRUDO).st_ino+OTHER = next(os.path.realpath(path) for path in+ ("/bin/true", "/usr/bin/true", sys.executable)+ if os.path.isfile(path) and os.access(path, os.X_OK) and+ (os.stat(path).st_dev, os.stat(path).st_ino) != SHIRUDO_ID)++libc = ctypes.CDLL(None, use_errno=True)+libc.prctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong,+ ctypes.c_ulong, ctypes.c_ulong]+libc.prctl.restype = ctypes.c_int+++class PrctlMmMap(ctypes.Structure):+ _fields_ = [("start_code", ctypes.c_uint64),+ ("end_code", ctypes.c_uint64),+ ("start_data", ctypes.c_uint64),+ ("end_data", ctypes.c_uint64),+ ("start_brk", ctypes.c_uint64),+ ("brk", ctypes.c_uint64),+ ("start_stack", ctypes.c_uint64),+ ("arg_start", ctypes.c_uint64),+ ("arg_end", ctypes.c_uint64),+ ("env_start", ctypes.c_uint64),+ ("env_end", ctypes.c_uint64),+ ("auxv", ctypes.c_void_p),+ ("auxv_size", ctypes.c_uint32),+ ("exe_fd", ctypes.c_uint32)]+++def proc_stat_values():+ stat = open("/proc/self/stat", encoding="ascii").read()+ fields = stat[stat.rfind(")") + 2:].split()+ indexes = {"start_code": 23, "end_code": 24, "start_stack": 25,+ "start_data": 42, "end_data": 43, "start_brk": 44,+ "brk": 45, "arg_start": 46, "arg_end": 47,+ "env_start": 48, "env_end": 49}+ return {name: int(fields[index]) for name, index in indexes.items()}+++def current_mm_map(exe_fd):+ values = proc_stat_values()+ auxv_data = open("/proc/self/auxv", "rb").read()+ auxv = ctypes.create_string_buffer(auxv_data)+ values["auxv"] = ctypes.addressof(auxv)+ values["auxv_size"] = len(auxv_data)+ values["exe_fd"] = exe_fd+ return PrctlMmMap(**values), auxv+++def call_prctl(option, arg2, arg3=0, arg4=0, arg5=0):+ ctypes.set_errno(0)+ result = libc.prctl(option, arg2, arg3, arg4, arg5)+ return result, ctypes.get_errno()+++def file_identity(path):+ st = os.stat(path)+ return st.st_dev, st.st_ino+++def child_succeeds(fn):+ pid = os.fork()+ if pid == 0:+ try:+ fn()+ except Exception as exc:+ print(f"child assertion failed: {exc}", file=sys.stderr)+ os._exit(1)+ os._exit(0)+ _, status = os.waitpid(pid, 0)+ return os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0+++def exe_file_result(path, expect_denied):+ before = file_identity("/proc/self/exe")+ fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC)+ try:+ result, err = call_prctl(PR_SET_MM, PR_SET_MM_EXE_FILE, fd)+ finally:+ os.close(fd)+ after = file_identity("/proc/self/exe")+ if expect_denied:+ assert result == -1 and err == errno.EPERM, (result, err)+ assert after == before, (before, after)+ else:+ assert result == 0, (result, err)+ assert after == file_identity(path), (after, file_identity(path))+++def mm_map_result(path, expect_denied):+ before = file_identity("/proc/self/exe")+ fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC)+ try:+ mm, auxv = current_mm_map(fd)+ result, err = call_prctl(PR_SET_MM, PR_SET_MM_MAP,+ ctypes.addressof(mm), ctypes.sizeof(mm))+ assert auxv is not None+ finally:+ os.close(fd)+ after = file_identity("/proc/self/exe")+ if expect_denied:+ assert result == -1 and err == errno.EPERM, (result, err)+ assert after == before, (before, after)+ else:+ assert result == 0, (result, err)+ assert after == file_identity(path), (after, file_identity(path))+++assert child_succeeds(lambda: exe_file_result(SHIRUDO, True)), \+ "PR_SET_MM_EXE_FILE accepted Shirudo's executable"+assert child_succeeds(lambda: exe_file_result(OTHER, False)), \+ "PR_SET_MM_EXE_FILE rejected an unrelated executable"+assert child_succeeds(lambda: mm_map_result(SHIRUDO, True)), \+ "PR_SET_MM_MAP accepted Shirudo's executable"+assert child_succeeds(lambda: mm_map_result(OTHER, False)), \+ "PR_SET_MM_MAP rejected an unrelated executable"+++def invalid_fd_then_exec():+ result, err = call_prctl(PR_SET_MM, PR_SET_MM_EXE_FILE, 1 << 30)+ assert result == -1 and err == errno.EBADF, (result, err)+ os.execve(SHIRUDO, [SHIRUDO, "status", "--json"], os.environ.copy())+++assert child_succeeds(invalid_fd_then_exec), \+ "failed PR_SET_MM left state that blocked ordinary Shirudo execution"+print("PR_SET_MM identity guard passed")diff --git a/testing/tamperproof/t1131-pr-set-mm-identity.sh b/testing/tamperproof/t1131-pr-set-mm-identity.shnew file mode 100644index 00000000..11d6e1a3--- /dev/null+++ b/testing/tamperproof/t1131-pr-set-mm-identity.sh@@ -0,0 +1,24 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t1131 -- PR_SET_MM cannot assign Shirudo's frozen executable identity,+# while unrelated executable-file changes retain normal kernel behavior.++cd "$(dirname "$0")/.."+. ./integration-lib.sh+target_guard+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"++python3 -c '+import sys+status = open("/proc/self/status", encoding="ascii").read().splitlines()+caps = next(line.split()[1] for line in status if line.startswith("CapEff:"))+sys.exit(0 if int(caps, 16) & (1 << 24) else 1)+' || test_skip_all "CAP_SYS_RESOURCE unavailable"++test_expect_success 'PR_SET_MM guards only the recorded Shirudo executable' '+ python3 tamperproof/t1131-pr-set-mm-identity.py "$SHIRUDO_BIN"+'++test_donediff --git a/util/paths.h b/util/paths.hindex d3629cd4..1901d20b 100644--- a/util/paths.h+++ b/util/paths.h@@ -64,6 +64,10 @@#define SHIRUDO_INODE_SETXATTR_LINK_PIN SHIRUDO_BPFFS_DIR "/bpf2_inode_setxattr_link"#define SHIRUDO_INODE_RMXATTR_LINK_PIN SHIRUDO_BPFFS_DIR "/bpf2_inode_removexattr_link"#define SHIRUDO_KEY_PERMISSION_LINK_PIN SHIRUDO_BPFFS_DIR "/bpf2_key_permission_link"+#define SHIRUDO_TASK_PRCTL_LINK_PIN SHIRUDO_BPFFS_DIR "/bpf2_task_prctl_link"+#define SHIRUDO_FILE_PERMISSION_LINK_PIN \+ SHIRUDO_BPFFS_DIR "/bpf2_file_permission_link"+#define SHIRUDO_PRCTL_EXIT_LINK_PIN SHIRUDO_BPFFS_DIR "/bpf2_prctl_exit_link"#define SHIRUDO_SEAL_FILE_OPEN_PIN SHIRUDO_BPFFS_DIR "/seal_file_open_link"#define SHIRUDO_SEAL_BPRM_CHECK_PIN SHIRUDO_BPFFS_DIR "/seal_bprm_check_security_link"#define SHIRUDO_SEAL_BPRM_COMMITTED_PIN SHIRUDO_BPFFS_DIR "/seal_bprm_committed_creds_link"