eBPF-based security platform
testing: add kernel-obs privilege coverage
John Fastabendd6615b53df36
diff --git a/testing/kernel-obs/kernel-obs-priv.sh b/testing/kernel-obs/kernel-obs-priv.shnew file mode 100755index 00000000..a1a95586--- /dev/null+++ b/testing/kernel-obs/kernel-obs-priv.sh@@ -0,0 +1,79 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++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"+MODPROBE_FILE=/proc/sys/kernel/modprobe+WORK=$(mktemp -d)+MODPROBE_BACKUP="$WORK/kernel.modprobe"++cleanup()+{+ if [ -s "$MODPROBE_BACKUP" ] || [ -e "$MODPROBE_BACKUP" ]; then+ cat "$MODPROBE_BACKUP" >"$MODPROBE_FILE" || true+ fi+ 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"+[ -w "$MODPROBE_FILE" ] || test_skip_all "kernel.modprobe is not writable"++load_observability()+{+ if "$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck --report=- \+ >"$WORK/load.log" 2>&1; then+ return 0+ fi+ cat "$WORK/load.log" >&2+ if [ -d /mnt/shirudo-out ]; then+ cp "$WORK/load.log" /mnt/shirudo-out/kernel-obs-priv-load.log+ fi+ return 1+}++export_priv()+{+ "$SHIRUDO_BIN" upatch map "$NAME" priv --json="$1" >/dev/null+}++test_expect_success 'kernel-obs upatch loads with the priv serializer' '+ load_observability &&+ test -e "/run/shirudo/bpffs/upatches/$NAME/serializers/priv"+'++test_expect_success 'non-executable mappings do not produce exec protection records' '+ SHIRUDO_TEST_WORK_DIR="$WORK/events" \+ python3 kernel-obs/priv_events.py negative &&+ export_priv "$WORK/negative.ndjson" &&+ python3 kernel-obs/priv_events.py check-negative "$WORK/negative.ndjson"+'++test_expect_success 'privilege events produce attributed priv records' '+ cat "$MODPROBE_FILE" >"$MODPROBE_BACKUP" &&+ printf '%s\n' /bin/false >"$MODPROBE_FILE" &&+ SHIRUDO_TEST_WORK_DIR="$WORK/events" \+ python3 kernel-obs/priv_events.py generate "$WORK/expected.json" &&+ cat "$MODPROBE_BACKUP" >"$MODPROBE_FILE" &&+ rm -f "$MODPROBE_BACKUP" &&+ export_priv "$WORK/priv.ndjson" &&+ python3 kernel-obs/priv_events.py check \+ "$WORK/expected.json" "$WORK/priv.ndjson"+'++test_donediff --git a/testing/kernel-obs/priv_events.py b/testing/kernel-obs/priv_events.pynew file mode 100644index 00000000..e392c181--- /dev/null+++ b/testing/kernel-obs/priv_events.py@@ -0,0 +1,383 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++import ctypes+import errno+import json+import os+import platform+import signal+import socket+import struct+import sys++PAGE_SIZE = os.sysconf("SC_PAGE_SIZE")+PROT_READ = 1+PROT_WRITE = 2+PROT_EXEC = 4+MAP_PRIVATE = 2+MAP_ANONYMOUS = 0x20+PTRACE_ATTACH = 16+PTRACE_DETACH = 17+PR_SET_NAME = 15++SYSCALLS = {+ "x86_64": {"bpf": 321, "finit_module": 313, "init_module": 175},+ "aarch64": {"bpf": 280, "finit_module": 273, "init_module": 105},+ "riscv64": {"bpf": 280, "finit_module": 273, "init_module": 105},+}++libc = ctypes.CDLL(None, use_errno=True)+libc.syscall.restype = ctypes.c_long+libc.ptrace.restype = ctypes.c_long+libc.prctl.restype = ctypes.c_int+libc.mount.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p,+ ctypes.c_ulong, ctypes.c_void_p]+libc.umount2.argtypes = [ctypes.c_char_p, ctypes.c_int]+libc.mmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int,+ ctypes.c_int, ctypes.c_int, ctypes.c_long]+libc.mmap.restype = ctypes.c_void_p+libc.munmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t]+libc.mprotect.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int]+++def syscall_numbers():+ machine = platform.machine()+ if machine not in SYSCALLS:+ raise RuntimeError(f"unsupported syscall architecture: {machine}")+ return SYSCALLS[machine]+++def executable_identity():+ info = os.stat("/proc/self/exe")+ return {"dev": (os.major(info.st_dev) << 20) | os.minor(info.st_dev),+ "ino": info.st_ino}+++def setuid_event():+ os.seteuid(65534)+ try:+ os.seteuid(0)+ finally:+ if os.geteuid() != 0:+ os.seteuid(0)+++def ptrace_event():+ ready_read, ready_write = os.pipe()+ child = os.fork()+ if child == 0:+ os.close(ready_read)+ if libc.prctl(PR_SET_NAME, ctypes.c_char_p(b"priv-child"), 0, 0, 0) < 0:+ os.write(ready_write, b"0")+ os._exit(1)+ os.write(ready_write, b"1")+ os.close(ready_write)+ while True:+ signal.pause()+ os.close(ready_write)+ try:+ if os.read(ready_read, 1) != b"1":+ raise RuntimeError("ptrace child failed to set its process name")+ os.close(ready_read)+ ctypes.set_errno(0)+ if libc.ptrace(PTRACE_ATTACH, child, None, None) < 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ waited, status = os.waitpid(child, os.WUNTRACED)+ if waited != child or not os.WIFSTOPPED(status):+ raise RuntimeError("ptrace child did not stop after attach")+ if libc.ptrace(PTRACE_DETACH, child, None, None) < 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ finally:+ try:+ os.close(ready_read)+ except OSError:+ pass+ try:+ os.kill(child, signal.SIGKILL)+ except ProcessLookupError:+ pass+ try:+ os.waitpid(child, 0)+ except ChildProcessError:+ pass+ return child+++def userns_event():+ children = []+ for _ in range(2):+ child = os.fork()+ if child == 0:+ try:+ os.unshare(os.CLONE_NEWUSER)+ except Exception:+ os._exit(1)+ os._exit(0)+ children.append(child)+ waited, status = os.waitpid(child, 0)+ if waited != child or not os.WIFEXITED(status) or os.WEXITSTATUS(status):+ raise RuntimeError("user namespace creation failed")+ return children+++def mount_event(workdir):+ path = os.path.join(workdir, "mountpoint")+ os.mkdir(path)+ encoded = os.fsencode(path)+ if libc.mount(b"none", encoded, b"tmpfs", 0, None) < 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ try:+ return path+ finally:+ if libc.umount2(encoded, 0) < 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+++def module_load_events(workdir):+ path = os.path.join(workdir, "invalid-module.ko")+ with open(path, "wb") as image:+ image.write(b"not a kernel module")+ fd = os.open(path, os.O_RDONLY)+ try:+ number = syscall_numbers()["finit_module"]+ ctypes.set_errno(0)+ result = libc.syscall(number, ctypes.c_int(fd),+ ctypes.c_char_p(b""), ctypes.c_int(0))+ if result >= 0:+ raise RuntimeError("invalid module image was unexpectedly accepted")+ finally:+ os.close(fd)++ image = ctypes.create_string_buffer(b"\x7fELF" + b"\0" * 123)+ number = syscall_numbers()["init_module"]+ ctypes.set_errno(0)+ result = libc.syscall(number, ctypes.byref(image),+ ctypes.c_ulong(ctypes.sizeof(image)),+ ctypes.c_char_p(b""))+ if result >= 0:+ raise RuntimeError("invalid init_module image was unexpectedly accepted")+ return path+++def module_request_event():+ try:+ sock = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, 31)+ except OSError:+ return+ sock.close()+ raise RuntimeError("test Netlink protocol unexpectedly opened")+++def bpf_event():+ attr = bytearray(72)+ struct.pack_into("=IIIIIII", attr, 0, 1, 4, 4, 1, 0, 0, 0)+ attr[28:44] = b"privtest\0".ljust(16, b"\0")+ buf = ctypes.create_string_buffer(bytes(attr))+ number = syscall_numbers()["bpf"]+ ctypes.set_errno(0)+ result = libc.syscall(number, ctypes.c_int(0), ctypes.byref(buf),+ ctypes.c_uint(len(attr)))+ if result >= 0:+ os.close(result)+ raise RuntimeError("unsigned BPF map creation unexpectedly succeeded")+ error = ctypes.get_errno()+ if error not in (errno.EPERM, errno.EACCES):+ raise OSError(error, os.strerror(error))+++def mmap_exec_event():+ fd = os.open("/bin/true", os.O_RDONLY)+ try:+ address = libc.mmap(None, PAGE_SIZE, PROT_READ | PROT_EXEC,+ MAP_PRIVATE, fd, 0)+ if address == ctypes.c_void_p(-1).value:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ if libc.munmap(address, PAGE_SIZE) < 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ finally:+ os.close(fd)+++def mprotect_exec_event():+ address = libc.mmap(None, PAGE_SIZE, PROT_READ | PROT_WRITE,+ MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)+ if address == ctypes.c_void_p(-1).value:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ try:+ if libc.mprotect(address, PAGE_SIZE, PROT_READ | PROT_EXEC) < 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ finally:+ if libc.munmap(address, PAGE_SIZE) < 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+++def nonexec_mapping_events():+ fd = os.open("/bin/true", os.O_RDONLY)+ try:+ address = libc.mmap(None, PAGE_SIZE, PROT_READ, MAP_PRIVATE, fd, 0)+ if address == ctypes.c_void_p(-1).value:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ if libc.munmap(address, PAGE_SIZE) < 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ finally:+ os.close(fd)+ address = libc.mmap(None, PAGE_SIZE, PROT_READ | PROT_WRITE,+ MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)+ if address == ctypes.c_void_p(-1).value:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ try:+ if libc.mprotect(address, PAGE_SIZE, PROT_READ) < 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ finally:+ if libc.munmap(address, PAGE_SIZE) < 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+++def generate(expected_path):+ workdir = os.environ["SHIRUDO_TEST_WORK_DIR"]+ os.makedirs(workdir, exist_ok=True)+ pid = os.getpid()+ identity = executable_identity()+ setuid_event()+ ptrace_child = ptrace_event()+ children = userns_event()+ mountpoint = mount_event(workdir)+ module_path = module_load_events(workdir)+ module_request_event()+ bpf_event()+ mmap_exec_event()+ mprotect_exec_event()+ with open(expected_path, "w", encoding="utf-8") as output:+ json.dump({"pid": pid, "identity": identity,+ "ptrace_child": ptrace_child,+ "userns_children": children,+ "mountpoint": mountpoint,+ "module_path": module_path}, output)+++def records_from(path):+ with open(path, encoding="utf-8") as stream:+ documents = [json.loads(line) for line in stream]+ document = next(doc for doc in documents if doc.get("map") == "priv")+ assert document["schema"] == 2, document+ assert document["upatch"] == "kernel-obs", document+ assert document["interval"]["overflow"] == 0, document+ assert document["interval"]["lost"] == 0, document+ return document["records"]+++def check_negative(path):+ records = records_from(path)+ assert not any(record["kind"] in ("mprotect_exec", "cred_anomaly")+ for record in records), records+++def check_positive(expected_path, records_path):+ with open(expected_path, encoding="utf-8") as source:+ expected = json.load(source)+ records = records_from(records_path)+ kinds = {"setuid_root", "ptrace_attach", "mount", "kernel_read_file",+ "kernel_load_data", "module_request", "userns_create", "bpf",+ "mmap_exec", "mprotect_exec"}+ identity = expected["identity"]+ selected = [record for record in records+ if record["kind"] in kinds and+ int(record["executable"]["dev"]) == identity["dev"] and+ int(record["executable"]["ino"]) == identity["ino"]]+ found = {record["kind"] for record in selected}+ if found != kinds:+ available = [+ {"kind": record.get("kind"),+ "executable": record.get("executable"),+ "pid": record.get("pid")}+ for record in records if record.get("kind") in kinds+ ]+ raise AssertionError({"missing": sorted(kinds - found),+ "expected_executable": identity,+ "available_records": available})+ assert not any(record["kind"] == "cred_anomaly" for record in records), records+ for record in selected:+ assert int(record["count"]) > 0, record+ assert int(record["pid"]) > 0, record+ assert int(record["first_seen_unix_nano"]) > 0, record+ assert int(record["last_seen_unix_nano"]) >= \+ int(record["first_seen_unix_nano"]), record+ assert len({str(record["cgroup_id"]) for record in selected}) == 1, selected++ def kind(name):+ matches = [record for record in selected if record["kind"] == name]+ assert matches, (name, selected)+ return matches++ setuid = kind("setuid_root")[0]+ assert setuid["euid"] == 65534 and setuid["uid"] == 0, setuid+ assert setuid["pid"] == expected["pid"], setuid++ ptrace = kind("ptrace_attach")[0]+ assert ptrace["name"] == "priv-child", ptrace+ assert ptrace["subtype"] & 2, ptrace+ assert int(ptrace["aux"]) == expected["ptrace_child"], ptrace+ assert ptrace["pid"] == expected["pid"], ptrace++ mount = kind("mount")[0]+ assert mount["name"] == "tmpfs", mount+ assert mount["detail"] == expected["mountpoint"], mount+ assert mount["subtype"] == int(mount["aux"]), mount++ kernel_read = kind("kernel_read_file")[0]+ assert kernel_read["name"] == "invalid-module.ko", kernel_read+ assert kernel_read["detail"] == expected["module_path"], kernel_read+ kind("kernel_load_data")++ module_request = kind("module_request")[0]+ assert module_request["name"] == "net-pf-16-proto-31", module_request++ userns = kind("userns_create")[0]+ assert int(userns["count"]) >= 2, userns+ assert userns["pid"] in expected["userns_children"], userns++ bpf = kind("bpf")[0]+ assert bpf["subtype"] == 0, bpf+ assert bpf["pid"] == expected["pid"], bpf++ mmap_exec = kind("mmap_exec")[0]+ assert mmap_exec["subtype"] & PROT_EXEC, mmap_exec+ mprotect_exec = kind("mprotect_exec")[0]+ assert mprotect_exec["subtype"] & PROT_EXEC, mprotect_exec+ assert int(mprotect_exec["aux"]) >= PAGE_SIZE, mprotect_exec+++def main():+ if len(sys.argv) < 2:+ raise SystemExit("usage: priv_events.py negative | generate FILE | check EXPECTED NDJSON | check-negative NDJSON")+ mode = sys.argv[1]+ if mode == "negative":+ nonexec_mapping_events()+ elif mode == "generate" and len(sys.argv) == 3:+ generate(sys.argv[2])+ elif mode == "check" and len(sys.argv) == 4:+ check_positive(sys.argv[2], sys.argv[3])+ elif mode == "check-negative" and len(sys.argv) == 3:+ check_negative(sys.argv[2])+ else:+ raise SystemExit("invalid priv_events.py arguments")+++if __name__ == "__main__":+ main()diff --git a/testing/run-target-obs-tests.sh b/testing/run-target-obs-tests.shindex 8b93b95f..ca918966 100755--- a/testing/run-target-obs-tests.sh+++ b/testing/run-target-obs-tests.sh@@ -10,6 +10,7 @@ fail=0: "${SHIRUDO_TEST_SUITE_FAILURES_FILE:=}"for test_script in \kernel-obs/t1210-kernel-obs.sh \+ kernel-obs/kernel-obs-priv.sh \kernel-obs/t1211-kernel-obs-dns-matrix.shdoif sh "$test_script"; then