eBPF-based security platform
bpf: protect maps from non-Shirudo writes
John Fastabend5060e56ce448
diff --git a/Documentation/architecture.rst b/Documentation/architecture.rstindex 00e31350..b7cc8386 100644--- a/Documentation/architecture.rst+++ b/Documentation/architecture.rst@@ -221,17 +221,26 @@ with a non-zero ``signature_size``, so the only program userspace canload is a signed loader. Allowed without a signature are the commandsthat cannot introduce code: map create only from the executable``init`` recorded as shirudo (signed-loader map creation runs in kernel-context and is already allowed), map update and freeze (the-loader-data pattern), object pin, link create and raw tracepoint open+context and is already allowed), map update and freeze only from+shirudo's executable, object pin, link create and raw tracepoint open(a program fd is only obtainable from a signed load or from an-already-vetted program), and the read-only commands (``OBJ_GET``,-``*_GET_FD_BY_ID``, ``*_GET_NEXT_ID``, ``OBJ_GET_INFO_BY_FD``,+already-vetted program), and the read-only commands (``*_GET_FD_BY_ID``,+``*_GET_NEXT_ID``, ``OBJ_GET_INFO_BY_FD``,``MAP_LOOKUP_ELEM``, ``MAP_LOOKUP_BATCH``, ``MAP_GET_NEXT_KEY``,``PROG_QUERY``, ``PROG_TEST_RUN``, ``TASK_FD_QUERY``) that keep-``bpftool`` and ``shirudo status`` working. Everything else, including+``bpftool`` and ``shirudo status`` working. ``OBJ_GET`` is subject to+``lsm/bpf_map``: non-Shirudo callers can get only read-only map fds.+Everything else, including``LINK_DETACH``, ``LINK_UPDATE``, ``PROG_ATTACH``/``PROG_DETACH``,``BTF_LOAD`` and every map delete variant, is denied with ``-EACCES``.+``lsm/bpf_map`` denies writable map file descriptors when the caller's+executable identity is not shirudo. Root can retrieve read-only map fds+for 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.+``lsm/bpf_prog_load`` runs after the kernel's signature check and admitsa program only when the verdict is ``BPF_SIG_VERIFIED`` and thesignature was resolved from the keyring whose kind shirudo froze into@@ -244,7 +253,9 @@ bpffs and keyring guards. The identity map (the bpffs ``s_dev``,shirudo's executable ``(dev, ino)``, the keyring kind and serial, andthe serials of the keys the keyring holds) is written and``BPF_MAP_FREEZE``'d before any link is created, so userspace cannot-change it for the rest of the boot. ``lsm/inode_unlink``,+change it for the rest of the boot. Writable map fds and map updates+are restricted by the same executable-identity gate.+``lsm/inode_unlink``,``lsm/inode_setxattr`` and ``lsm/inode_removexattr`` on shirudo's bpffsallow the operation only when the calling task's ``mm->exe_file`` isshirudo's binary: root ``rm`` cannot drop a pin, and nobody else candiff --git a/Documentation/threat-model.rst b/Documentation/threat-model.rstindex 073eddcb..d5d6bc55 100644--- a/Documentation/threat-model.rst+++ b/Documentation/threat-model.rst@@ -128,7 +128,11 @@ T2 Detaching or replacing enforcement``sb_remount`` deny everyone, so neither ``rm`` nor ``umount`` normounting over the directory removes a pin. Infrastructure maps arefrozen at creation, so even with the LSM gone userspace could not- rewrite the identity map. From the initrd, the identity records+ rewrite the identity map. ``lsm/bpf_map`` denies writable map fds+ to every process except shirudo; map updates and freezes have the+ same executable gate. Root may inspect pinned maps but cannot alter+ serializer arrays or writable-mmap arena state through the syscall+ interface. From the initrd, the identity recordsthe root's binary as the executable that lasts and the initrd'sown copy beside it for that one run; the copy is gone with theinitrd, and its inode is on a file system nothing can reach after@@ -260,8 +264,8 @@ Each of these is known, documented and bounded; none is silent.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 and the- bpffs guards. Bound ``CAP_SYS_RESOURCE`` out of untrusted contexts+ that can open shirudo's binary impersonates it to the seal, bpffs+ and BPF map guards. Bound ``CAP_SYS_RESOURCE`` out of untrusted contextswith ``CapabilityBoundingSet=`` and container capability profiles.This is a property of the kernel's process model, not a shirudobug to fix.diff --git a/bpf/bpf2.c b/bpf/bpf2.cindex 29cc074b..93996d11 100644--- a/bpf/bpf2.c+++ b/bpf/bpf2.c@@ -30,6 +30,10 @@* loads from userspace" a kernel-enforced* invariant rather than a best-effort keyring_id* choice by the caller.+ * lsm/bpf_map -- denies writable map file descriptors to every+ * process except shirudo. Read-only map access+ * remains available; this also blocks writable+ * mmap of arena maps.* lsm/inode_unlink -- denies VFS unlink on shirudo's private* bpffs superblock unless the caller is shirudo* itself (its exe_file inode matches the@@ -84,6 +88,9 @@#ifndef EACCES#define EACCES 13#endif+#ifndef FMODE_WRITE+#define FMODE_WRITE 0x2+#endifchar _license[] SEC("license") = "Dual BSD/GPL";@@ -149,17 +156,14 @@ int BPF_PROG(shirudo_lsm_bpf, int cmd, union bpf_attr *attr,/** Vetted mutating cmds the signed-loader data-map + attach/pin- * pattern needs from userspace, plus MAP_UPDATE_ELEM for clearing- * a serializer's reserved output map before BPF_PROG_TEST_RUN.- * None can introduce unsigned code:- * a prog_fd is only obtainable via the signature-gated- * BPF_PROG_LOAD above or GET_FD_BY_ID of an already-vetted prog,- * and shirudo's own infra maps are BPF_MAP_FREEZE'd at creation- * (a userspace BPF_MAP_UPDATE_ELEM on them then fails -EPERM- * regardless of this verdict). gen_loader emits no link-create and- * bpf_sys_bpf() cannot BPF_OBJ_PIN, so shirudo's- * one-shot CLI must create + pin the link itself. Attaching an- * already-vetted program grants no new code-execution capability.+ * pattern needs from userspace. Map updates and freezes are restricted+ * below to shirudo itself; signed-loader map mutations run in kernel+ * context. A prog_fd is only obtainable via the signature-gated+ * BPF_PROG_LOAD above or GET_FD_BY_ID of an already-vetted prog.+ * gen_loader emits no link-create and bpf_sys_bpf() cannot+ * BPF_OBJ_PIN, so shirudo's one-shot CLI must create + pin the link+ * itself. Attaching an already-vetted program grants no new+ * code-execution capability.*/case BPF_MAP_CREATE:id = bpf_map_lookup_elem(&shirudo_bpffs_sb, &zero);@@ -169,6 +173,11 @@ int BPF_PROG(shirudo_lsm_bpf, int cmd, union bpf_attr *attr,case BPF_MAP_UPDATE_ELEM:case BPF_MAP_FREEZE:+ id = bpf_map_lookup_elem(&shirudo_bpffs_sb, &zero);+ if (!id || !shirudo_task_is_self(id))+ return -EACCES;+ return 0;+case BPF_OBJ_PIN:case BPF_LINK_CREATE:case BPF_RAW_TRACEPOINT_OPEN:@@ -219,6 +228,26 @@ int BPF_PROG(shirudo_lsm_bpf, int cmd, union bpf_attr *attr,}}+/*+ * Writable map fds let userspace alter array contents and writable+ * mmap lets it alter arena pages without another bpf() command. Keep+ * both paths exclusive to shirudo while leaving read-only map access+ * available to observers.+ */+SEC("lsm/bpf_map")+int BPF_PROG(shirudo_lsm_bpf_map, struct bpf_map *map, fmode_t fmode)+{+ struct shirudo_sb_id *id;+ __u32 zero = 0;++ if (!(fmode & FMODE_WRITE))+ return 0;+ id = bpf_map_lookup_elem(&shirudo_bpffs_sb, &zero);+ if (!id || !shirudo_task_is_self(id))+ return -EACCES;+ return 0;+}+/** Admission gate. Fires from a single call site inside the verifier* (bpf_check), after the kernel has verified any PKCS#7 signature anddiff --git a/testing/run-target-tests.sh b/testing/run-target-tests.shindex b404bc43..d96d6ccf 100755--- a/testing/run-target-tests.sh+++ b/testing/run-target-tests.sh@@ -37,6 +37,7 @@ for t in \tamperproof/t1110-lsm-deny.sh \tamperproof/t1112-prog-load-keyring-gate.sh \tamperproof/t1113-mount-lockdown.sh \+ tamperproof/t1130-map-lockdown.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 ef09ddc5..36f35dd1 100755--- a/testing/t0015-test-vm-cli.sh+++ b/testing/t0015-test-vm-cli.sh@@ -573,6 +573,7 @@ test_expect_success 'operator and target runners have disjoint explicit scopes'tamperproof/t1110-lsm-deny.sh \tamperproof/t1112-prog-load-keyring-gate.sh \tamperproof/t1113-mount-lockdown.sh \+ tamperproof/t1130-map-lockdown.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.shnew file mode 100644index 00000000..d0bc8dd4--- /dev/null+++ b/testing/tamperproof/t1130-map-lockdown.sh@@ -0,0 +1,195 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# 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.++cd "$(dirname "$0")/.."+. ./integration-lib.sh+target_guard+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"++FIXTURES=${SHIRUDO_TEST_FIXTURES_DIR:?target fixture directory is not set}+NAME=kernel-obs+LOAD="$FIXTURES/$NAME.upatch"+UNLOAD="$FIXTURES/$NAME.unload.upatch"+PIN="/run/shirudo/bpffs/upatches/$NAME/link_0"+MAPS="/run/shirudo/bpffs/upatches/$NAME/maps"+WORK=$(mktemp -d)++cleanup()+{+ if [ -e "$PIN" ] || [ -e "/run/shirudo/bpffs/upatches/$NAME/link" ]; then+ "$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck \+ >/dev/null 2>&1 || true+ fi+ rm -f "/var/lib/shirudo/upatches/$NAME.upatch"+ rm -rf "$WORK"+}+trap cleanup EXIT HUP INT TERM++[ -s "$LOAD" ] || test_skip_all "missing kernel-obs fixture"+[ -s "$UNLOAD" ] || test_skip_all "missing kernel-obs unload fixture"++cat >"$WORK/check.py" <<'PYTHON'+import ctypes+import errno+import os+import platform+import sys++BPF_MAP_UPDATE_ELEM = 2+BPF_MAP_FREEZE = 22+BPF_MAP_GET_FD_BY_ID = 14+BPF_OBJ_GET = 7+BPF_OBJ_GET_INFO_BY_FD = 15+BPF_F_RDONLY = 1 << 3+BPF_ANY = 0+PROT_READ = 1+PROT_WRITE = 2+MAP_SHARED = 1+PAGE_SIZE = os.sysconf("SC_PAGE_SIZE")+SYSCALLS = {"x86_64": 321, "aarch64": 280, "riscv64": 280}++try:+ BPF_SYSCALL = SYSCALLS[platform.machine()]+except KeyError as exc:+ machine = platform.machine()+ raise SystemExit(f"unsupported syscall architecture: {machine}") from exc++libc = ctypes.CDLL(None, use_errno=True)+libc.syscall.restype = ctypes.c_long+libc.mmap.restype = ctypes.c_void_p+libc.munmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t]+++class ObjGetAttr(ctypes.Structure):+ _fields_ = [("pathname", ctypes.c_uint64),+ ("bpf_fd", ctypes.c_uint32),+ ("file_flags", ctypes.c_uint32)]+++class ObjInfoAttr(ctypes.Structure):+ _fields_ = [("bpf_fd", ctypes.c_uint32),+ ("info_len", ctypes.c_uint32),+ ("info", ctypes.c_uint64)]+++class MapInfoPrefix(ctypes.Structure):+ _fields_ = [("type", ctypes.c_uint32),+ ("id", ctypes.c_uint32),+ ("key_size", ctypes.c_uint32),+ ("value_size", ctypes.c_uint32),+ ("max_entries", ctypes.c_uint32),+ ("map_flags", ctypes.c_uint32)]+++class MapFdByIdAttr(ctypes.Structure):+ _fields_ = [("map_id", ctypes.c_uint32),+ ("next_id", ctypes.c_uint32),+ ("open_flags", ctypes.c_uint32)]+++class MapElemAttr(ctypes.Structure):+ _fields_ = [("map_fd", ctypes.c_uint32),+ ("pad", ctypes.c_uint32),+ ("key", ctypes.c_uint64),+ ("value", ctypes.c_uint64),+ ("flags", ctypes.c_uint64)]+++def bpf(cmd, attr):+ ctypes.set_errno(0)+ result = libc.syscall(BPF_SYSCALL, cmd, ctypes.byref(attr),+ ctypes.sizeof(attr))+ return result, ctypes.get_errno()+++def obj_get(path, flags):+ encoded = os.fsencode(path) + b"\0"+ name = ctypes.create_string_buffer(encoded)+ attr = ObjGetAttr(ctypes.addressof(name), 0, flags)+ return bpf(BPF_OBJ_GET, attr)+++def map_id_from_fd(fd):+ info = MapInfoPrefix()+ attr = ObjInfoAttr(fd, ctypes.sizeof(info), ctypes.addressof(info))+ result, error = bpf(BPF_OBJ_GET_INFO_BY_FD, attr)+ if result < 0:+ raise AssertionError(f"map info: errno={error}")+ return info.id+++def map_fd_by_id(map_id, flags):+ attr = MapFdByIdAttr(map_id, 0, flags)+ return bpf(BPF_MAP_GET_FD_BY_ID, attr)+++def assert_denied(result, label):+ fd, error = result+ if fd >= 0:+ os.close(fd)+ raise AssertionError(f"{label}: unexpectedly allowed")+ if error not in (errno.EACCES, errno.EPERM):+ raise AssertionError(f"{label}: errno={error}, expected EACCES/EPERM")+++for map_name in ("shirudo_ser", "obs_i_arena"):+ path = os.path.join(sys.argv[1], map_name)+ assert_denied(obj_get(path, 0), f"writable fd for {map_name}")++ readonly_fd, error = obj_get(path, BPF_F_RDONLY)+ if readonly_fd < 0:+ raise AssertionError(f"read-only fd for {map_name}: errno={error}")+ try:+ map_id = map_id_from_fd(readonly_fd)+ assert_denied(map_fd_by_id(map_id, 0),+ f"writable fd by id for {map_name}")+ readonly_id_fd, error = map_fd_by_id(map_id, BPF_F_RDONLY)+ if readonly_id_fd < 0:+ raise AssertionError(+ f"read-only fd by id for {map_name}: errno={error}")+ os.close(readonly_id_fd)++ freeze_arg = ctypes.c_uint32(readonly_fd)+ result, error = bpf(BPF_MAP_FREEZE, freeze_arg)+ if result == 0 or error != errno.EACCES:+ raise AssertionError(+ f"freeze {map_name}: result={result}, errno={error}; "+ "expected LSM EACCES")+ if map_name == "shirudo_ser":+ key = ctypes.c_uint32(3)+ value = ctypes.create_string_buffer(PAGE_SIZE)+ attr = MapElemAttr(readonly_fd, 0, ctypes.addressof(key),+ ctypes.addressof(value), BPF_ANY)+ result, error = bpf(BPF_MAP_UPDATE_ELEM, attr)+ if result == 0 or error != errno.EACCES:+ raise AssertionError(+ f"serializer map update: result={result}, errno={error}; "+ "expected LSM EACCES")+ else:+ ctypes.set_errno(0)+ mapped = libc.mmap(None, PAGE_SIZE, PROT_READ | PROT_WRITE,+ MAP_SHARED, readonly_fd, 0)+ error = ctypes.get_errno()+ if mapped != ctypes.c_void_p(-1).value:+ libc.munmap(mapped, PAGE_SIZE)+ raise AssertionError("arena writable mmap unexpectedly allowed")+ if error not in (errno.EACCES, errno.EPERM):+ raise AssertionError(+ f"arena writable mmap: errno={error}, expected EACCES/EPERM")+ finally:+ os.close(readonly_fd)++print("direct root BPF map mutation denied")+PYTHON++test_expect_success 'root direct BPF map mutation is denied' '+ "$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck >/dev/null 2>&1 &&+ python3 "$WORK/check.py" "$MAPS"+'++test_done