eBPF-based security platform
testing: check which executables can manage Shirudo
KP Singhe09748f457fa
diff --git a/Makefile.shirudo b/Makefile.shirudoindex d085141a..b09e57ef 100644--- a/Makefile.shirudo+++ b/Makefile.shirudo@@ -285,7 +285,7 @@ DEPS := $(DEP_OBJS:.o=.d)# ----- top-level goals --------------------------------------------.PHONY: all install install-common install-target install-operator clean distclean check test \- test-helpers \+ test-helpers verity-test-helpers \bpf libbpfall: shirudo@@ -536,8 +536,22 @@ TPMSIM_CFLAGS := $(shell pkg-config --cflags libtpms 2>/dev/null)TPMSIM_LIBS := $(shell pkg-config --libs libtpms 2>/dev/null)TPMSIM_HELPER := $(if $(TPMSIM_LIBS),testing/helper/tpmsim-cmd,)+# Target fixtures must run without the host ELF interpreter or sanitizer.+VERITY_TEST_HELPERS := build/verity-tests/shirudo-policy-probe++build/verity-tests/shirudo-policy-probe: \+ testing/tamperproof/t1140-verity-helper.c util/identity.h+ @printf ' CC $@\n'+ $(Q)mkdir -p $(dir $@)+ $(Q)$(CC) -O2 $(DEBUG_CFLAGS) -std=gnu11 $(WARNINGS) \+ -Iinclude -D_GNU_SOURCE -static -o $@ $<+++verity-test-helpers: $(VERITY_TEST_HELPERS)+# Compiled test helpers (also usable as fuzz entry points).-TEST_HELPERS := testing/helper/test-json-parser \+TEST_HELPERS := $(VERITY_TEST_HELPERS) \+ testing/helper/test-json-parser \testing/helper/test-string \testing/helper/test-conditions \testing/helper/test-config-image \diff --git a/testing/tamperproof/t1140-verity-authority.sh b/testing/tamperproof/t1140-verity-authority.shnew file mode 100755index 00000000..fb84510e--- /dev/null+++ b/testing/tamperproof/t1140-verity-authority.sh@@ -0,0 +1,58 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++cd "$(dirname "$0")/.."+. ./integration-lib.sh+verity_required() {+ printf 'Bail out! %s\n' "$*" >&2+ exit 1+}+target_guard++: "${SHIRUDO_TEST_RUNTIME_PROBE:=/run/shirudo/runtime/usr/bin/shirudo-policy-probe}"+: "${SHIRUDO_TEST_TASKS_PIN:=/run/shirudo/bpffs/task_authority}"+[ -x "$SHIRUDO_TEST_RUNTIME_PROBE" ] ||+ verity_required "runtime image has no authority test fixture"+[ -e "$SHIRUDO_TEST_TASKS_PIN" ] ||+ verity_required "image-mode task authority map is not pinned"++WORK=$(mktemp -d)+trap 'rm -rf "$WORK"' EXIT HUP INT TERM+cp "$SHIRUDO_TEST_RUNTIME_PROBE" "$WORK/outside-probe"+chmod +x "$WORK/outside-probe"+printf "invalid executable\n" >"$WORK/invalid-executable"+chmod +x "$WORK/invalid-executable"++# The fixture must be statically linked, or its interpreter and RPATH must+# resolve into the runtime image. It is included only in the test image.+test_expect_success 'an executable on the runtime image receives authority' '+ "$SHIRUDO_TEST_RUNTIME_PROBE" mark "$SHIRUDO_TEST_TASKS_PIN" 1+'+test_expect_success 'fork inherits committed task authority' '+ "$SHIRUDO_TEST_RUNTIME_PROBE" fork "$SHIRUDO_TEST_TASKS_PIN"+'+test_expect_success 'failed exec preserves the running executable authority' '+ "$SHIRUDO_TEST_RUNTIME_PROBE" failed-exec "$SHIRUDO_TEST_TASKS_PIN"+'+test_expect_success 'failed exec after staging an outside image preserves authority' '+ "$SHIRUDO_TEST_RUNTIME_PROBE" failed-exec "$SHIRUDO_TEST_TASKS_PIN" \+ "$WORK/invalid-executable"+'+test_expect_success 'successful exec outside the image clears authority' '+ "$SHIRUDO_TEST_RUNTIME_PROBE" exec "$SHIRUDO_TEST_TASKS_PIN" \+ "$WORK/outside-probe" 0+'+test_expect_success 'successful exec inside the image reevaluates authority' '+ "$WORK/outside-probe" exec "$SHIRUDO_TEST_TASKS_PIN" \+ "$SHIRUDO_TEST_RUNTIME_PROBE" 1+'+test_expect_success 'a copied executable has no image authority' '+ "$WORK/outside-probe" mark "$SHIRUDO_TEST_TASKS_PIN" 0+'+test_expect_success 'trusted tasks reject outside and modified executable mappings' '+ "$SHIRUDO_TEST_RUNTIME_PROBE" mappings "$SHIRUDO_TEST_RUNTIME_PROBE" \+ "$WORK/outside-probe"+'++test_donediff --git a/testing/tamperproof/t1140-verity-helper.c b/testing/tamperproof/t1140-verity-helper.cnew file mode 100644index 00000000..edc44244--- /dev/null+++ b/testing/tamperproof/t1140-verity-helper.c@@ -0,0 +1,173 @@+// SPDX-License-Identifier: BSD-2-Clause+/* Copyright (c) 2026 Authors of shirudo */++#include "../../include/shirudo/misc.h"++#include <errno.h>+#include <fcntl.h>+#include <linux/bpf.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/mman.h>+#include <sys/stat.h>+#include <sys/syscall.h>+#include <sys/wait.h>+#include <unistd.h>++#include "../../util/identity.h"++static __u64 probe_word = 0x5348495255444fUL;++static int check_mark(const char *pin, int expected)+{+ struct shirudo_task_authority authority = {};+ union bpf_attr attr = {};+ int fd, pidfd, rc;++ pidfd = syscall(SYS_pidfd_open, getpid(), 0);+ if (pidfd < 0)+ return 1;+ attr.pathname = (uintptr_t)pin;+ attr.file_flags = BPF_F_RDONLY;+ fd = syscall(SYS_bpf, BPF_OBJ_GET, &attr, sizeof(attr));+ if (fd < 0) {+ close(pidfd);+ return 1;+ }+ memset(&attr, 0, sizeof(attr));+ attr.map_fd = fd;+ attr.key = (uintptr_t)&pidfd;+ attr.value = (uintptr_t)&authority;+ rc = syscall(SYS_bpf, BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));+ if (rc && errno != ENOENT)+ rc = 1;+ else+ rc = !!authority.trusted != expected;+ close(pidfd);+ close(fd);+ return rc;+}++static int check_mappings(const char *trusted, const char *outside)+{+ long length = sysconf(_SC_PAGESIZE);+ void *mapping;+ int fd;++ errno = 0;+ mapping = mmap(NULL, length, PROT_READ | PROT_EXEC,+ MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);+ if (mapping != MAP_FAILED || errno != EACCES)+ return 1;+ mapping = mmap(NULL, length, PROT_READ | PROT_WRITE,+ MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);+ if (mapping == MAP_FAILED)+ return 1;+ errno = 0;+ if (!mprotect(mapping, length, PROT_READ | PROT_EXEC) ||+ errno != EACCES)+ return 1;+ munmap(mapping, length);+ fd = open(outside, O_RDONLY);+ if (fd < 0)+ return 1;+ errno = 0;+ mapping = mmap(NULL, length, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);+ close(fd);+ if (mapping != MAP_FAILED || errno != EACCES)+ return 1;+ fd = open(trusted, O_RDONLY);+ if (fd < 0)+ return 1;+ mapping = mmap(NULL, length, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);+ if (mapping == MAP_FAILED) {+ close(fd);+ return 1;+ }+ errno = 0;+ if (!mprotect(mapping, length, PROT_READ | PROT_WRITE) ||+ errno != EACCES)+ return 1;+ munmap(mapping, length);+ mapping = mmap(NULL, length, PROT_READ | PROT_WRITE,+ MAP_PRIVATE, fd, 0);+ close(fd);+ if (mapping == MAP_FAILED)+ return 1;+ if (mprotect(mapping, length, PROT_READ))+ return 1;+ errno = 0;+ if (!mprotect(mapping, length, PROT_READ | PROT_EXEC) ||+ errno != EACCES)+ return 1;+ munmap(mapping, length);+ return 0;+}++int main(int argc, char **argv)+{+ char *failed[2] = {};+ pid_t child;+ int status;++ if (argc < 3)+ return 2;+ if (!strcmp(argv[1], "unlink"))+ return unlink(argv[2]) ? 1 : 0;+ if (!strcmp(argv[1], "mkdir"))+ return mkdir(argv[2], 0700) ? 1 : 0;+ if (!strcmp(argv[1], "rmdir"))+ return rmdir(argv[2]) ? 1 : 0;+ if (!strcmp(argv[1], "create")) {+ int fd = open(argv[2], O_WRONLY | O_CREAT | O_EXCL, 0600);++ return fd < 0 ? 1 : !!close(fd);+ }+ if (!strcmp(argv[1], "wait")) {+ FILE *ready = fopen(argv[2], "w");++ if (!ready)+ return 1;+ if (fprintf(ready, "%ld %llx\n", (long)getpid(),+ (__u64)(uintptr_t)&probe_word) < 0 ||+ fclose(ready))+ return 1;+ for (;;)+ pause();+ }+ if (!strcmp(argv[1], "mark") && argc == 4)+ return check_mark(argv[2], atoi(argv[3]));+ if (!strcmp(argv[1], "failed-exec")) {+ failed[0] = (char *)"missing";+ execv(argc == 4 ? argv[3] :+ "/no-such-shirudo-test-executable", failed);+ if (errno != (argc == 4 ? ENOEXEC : ENOENT))+ return 1;+ return check_mark(argv[2], 1);+ }+ if (!strcmp(argv[1], "fork")) {+ child = fork();+ if (child < 0)+ return 1;+ if (!child)+ _exit(check_mark(argv[2], 1));+ if (waitpid(child, &status, 0) != child)+ return 1;+ return !WIFEXITED(status) || WEXITSTATUS(status);+ }+ if (!strcmp(argv[1], "exec") && argc == 5) {+ char *next[5] = {};++ next[0] = argv[3];+ next[1] = (char *)"mark";+ next[2] = argv[2];+ next[3] = argv[4];+ execv(argv[3], next);+ return 1;+ }+ if (!strcmp(argv[1], "mappings") && argc == 4)+ return check_mappings(argv[2], argv[3]);+ return 2;+}diff --git a/testing/tamperproof/t1150-verity-devices.py b/testing/tamperproof/t1150-verity-devices.pynew file mode 100644index 00000000..30998fbb--- /dev/null+++ b/testing/tamperproof/t1150-verity-devices.py@@ -0,0 +1,198 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++import ctypes+import errno+import fcntl+import os+import pathlib+import platform+import stat+import struct+import sys+import tempfile++ROOTS = ("/run/shirudo/runtime", "/run/shirudo/config")+DENIED = (errno.EPERM, errno.EACCES)+libc = ctypes.CDLL(None, use_errno=True)+libc.mount.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p,+ ctypes.c_ulong, ctypes.c_char_p)+libc.umount2.argtypes = (ctypes.c_char_p, ctypes.c_int)+libc.unshare.argtypes = (ctypes.c_int,)+libc.syscall.restype = ctypes.c_long+++class DmIoctl(ctypes.Structure):+ _fields_ = [("version", ctypes.c_uint32 * 3),+ ("data_size", ctypes.c_uint32),+ ("data_start", ctypes.c_uint32),+ ("target_count", ctypes.c_uint32),+ ("open_count", ctypes.c_int32),+ ("flags", ctypes.c_uint32),+ ("event_nr", ctypes.c_uint32),+ ("padding", ctypes.c_uint32),+ ("dev", ctypes.c_uint64),+ ("name", ctypes.c_char * 128),+ ("uuid", ctypes.c_char * 129),+ ("data", ctypes.c_char * 7)]+++assert ctypes.sizeof(DmIoctl) == 312+++def dm_request(fd, command, name, table=False, replacement=None, uuid=False,+ direction=3, encoded_size=312):+ buf = bytearray(4096)+ param = DmIoctl.from_buffer(buf)+ param.version[:] = (4, 0, 0)+ param.data_size = len(buf)+ param.data_start = ctypes.sizeof(DmIoctl)+ param.name = name.encode("ascii")+ if table:+ param.flags = 1 << 4+ if replacement is not None:+ payload = replacement.encode("ascii") + b"\0"+ buf[param.data_start:param.data_start + len(payload)] = payload+ if uuid:+ param.flags |= 1 << 14+ if command == 14:+ buf[param.data_start:param.data_start + 14] = struct.pack("Q", 0) + b"probe\0"+ request = (direction << 30) | (encoded_size << 16) | (0xfd << 8) | command+ fcntl.ioctl(fd, request, buf, True)+ return bytes(buf)+++def mapped_device(path):+ st = os.stat(path)+ dev = f"{os.major(st.st_dev)}:{os.minor(st.st_dev)}"+ name = pathlib.Path(f"/sys/dev/block/{dev}/dm/name").read_text().strip()+ return name, dev+++def dm_guards(fd, name):+ before = dm_request(fd, 12, name, table=True)+ status = DmIoctl.from_buffer_copy(dm_request(fd, 7, name))+ identity = (bytes(status.name), bytes(status.uuid))+ for command, label in ((9, "table load"), (10, "table clear"),+ (4, "active device removal"), (6, "resume"),+ (14, "target message")):+ try:+ dm_request(fd, command, name)+ except OSError as exc:+ assert exc.errno in DENIED, (name, label, exc.errno)+ else:+ raise AssertionError((name, label, "mutation was allowed"))+ assert dm_request(fd, 12, name, table=True) == before, (name, label)+ for uuid, label in ((False, "device rename"), (True, "device UUID replacement")):+ replacement = f"shirudo-denied-{os.getpid()}-{'uuid' if uuid else 'name'}"+ try:+ dm_request(fd, 5, name, replacement=replacement, uuid=uuid)+ except OSError as exc:+ assert exc.errno in DENIED, (name, label, exc.errno)+ else:+ raise AssertionError((name, label, "mutation was allowed"))+ after = DmIoctl.from_buffer_copy(dm_request(fd, 7, name))+ assert (bytes(after.name), bytes(after.uuid)) == identity, (name, label)+ assert dm_request(fd, 12, name, table=True) == before, (name, label)+ assert dm_request(fd, 7, name), (name, "read-only status denied")+ for direction, encoded_size in ((0, 0), (1, 1), (2, 0x3fff)):+ assert dm_request(fd, 7, name, direction=direction, encoded_size=encoded_size)+ try:+ dm_request(fd, 10, name, direction=direction, encoded_size=encoded_size)+ except OSError as exc:+ assert exc.errno in DENIED, (name, "noncanonical table clear",+ direction, encoded_size, exc.errno)+ else:+ raise AssertionError((name, "noncanonical table clear was allowed",+ direction, encoded_size))+ assert dm_request(fd, 12, name, table=True) == before, \+ (name, "noncanonical table clear", direction, encoded_size)+++def in_namespace(fn):+ read_fd, write_fd = os.pipe()+ pid = os.fork()+ if not pid:+ os.close(read_fd)+ try:+ assert libc.unshare(0x20000) == 0, ("unshare", ctypes.get_errno())+ assert libc.mount(None, b"/", None, (1 << 18) | (1 << 14), None) == 0, \+ ("recursive private propagation", ctypes.get_errno())+ for line in open("/proc/self/mountinfo", encoding="ascii"):+ fields = line.split()+ optional = fields[6:fields.index("-")]+ assert not any(item.startswith(("shared:", "master:")) for item in optional), \+ ("namespace propagation is not isolated", line)+ fn()+ except BaseException as exc:+ os.write(write_fd, repr(exc).encode())+ os._exit(1)+ os._exit(0)+ os.close(write_fd)+ message = os.read(read_fd, 8192)+ os.close(read_fd)+ _, status = os.waitpid(pid, 0)+ assert os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0, message.decode()+++def mount_attempt(path, operation, destination):+ encoded = os.fsencode(path)+ if operation == "unmount":+ result = libc.umount2(encoded, 0)+ elif operation == "lazy unmount":+ result = libc.umount2(encoded, 2)+ elif operation == "remount":+ result = libc.mount(None, encoded, None, 1 << 5, None)+ elif operation == "overmount":+ result = libc.mount(b"none", encoded, b"tmpfs", 0, None)+ elif operation == "move_mount":+ syscall = {"x86_64": 429, "aarch64": 429, "riscv64": 429}[platform.machine()]+ result = libc.syscall(syscall, -100, encoded, -100,+ os.fsencode(destination), 0)+ elif operation == "recursive shared":+ result = libc.mount(None, encoded, None, (1 << 20) | (1 << 14), None)+ else:+ raise AssertionError(operation)+ assert result == -1 and ctypes.get_errno() in DENIED, \+ (path, operation, result, ctypes.get_errno())+++mode = sys.argv[1]+if mode == "devices":+ control = os.open("/dev/mapper/control", os.O_RDWR | os.O_CLOEXEC)+ try:+ for root in ROOTS:+ name, dev = mapped_device(root)+ dm_guards(control, name)+ pid = os.fork()+ if not pid:+ try:+ dm_guards(control, name)+ except BaseException as exc:+ print(f"inherited control FD: {exc}", file=sys.stderr)+ os._exit(1)+ os._exit(0)+ _, status = os.waitpid(pid, 0)+ assert os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0+ assert mapped_device(root) == (name, dev)+ finally:+ os.close(control)+ with tempfile.TemporaryDirectory(prefix="shirudo-dm-alias-", dir="/dev") as directory:+ alias = pathlib.Path(directory) / "control"+ os.mknod(alias, stat.S_IFCHR | 0o600, os.stat("/dev/mapper/control").st_rdev)+ control = os.open(alias, os.O_RDWR | os.O_CLOEXEC)+ try:+ for root in ROOTS:+ name, dev = mapped_device(root)+ dm_guards(control, name)+ assert mapped_device(root) == (name, dev)+ finally:+ os.close(control)+elif mode == "mounts":+ with tempfile.TemporaryDirectory() as destination:+ for root in ROOTS:+ for operation in ("unmount", "lazy unmount", "remount", "overmount", "move_mount"):+ in_namespace(lambda: mount_attempt(root, operation, destination))+else:+ raise AssertionError(mode)+print(f"verity {mode} guards passed")diff --git a/testing/tamperproof/t1150-verity-devices.sh b/testing/tamperproof/t1150-verity-devices.shnew file mode 100755index 00000000..ef632c59--- /dev/null+++ b/testing/tamperproof/t1150-verity-devices.sh@@ -0,0 +1,36 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++cd "$(dirname "$0")/.."+. ./integration-lib.sh+verity_required() {+ printf 'Bail out! %s\n' "$*" >&2+ exit 1+}+target_guard++mountpoint -q /run/shirudo/runtime && mountpoint -q /run/shirudo/config ||+ verity_required "dm-verity image mode is not active"+command -v python3 >/dev/null 2>&1 || verity_required "no python3"++test_expect_success 'runtime and config filesystems enforce their mount flags' '+ python3 - <<"PY"+import os+for path in ("/run/shirudo/runtime", "/run/shirudo/config"):+ flags = os.statvfs(path).f_flag+ assert flags & os.ST_RDONLY and flags & os.ST_NOSUID and flags & os.ST_NODEV, (path, flags)+ if path.endswith("/config"):+ assert flags & os.ST_NOEXEC, (path, flags)+PY+'++test_expect_success 'active DM tables reject mutations through inherited FDs, device aliases and alternate ioctl encodings' '+ python3 tamperproof/t1150-verity-devices.py devices+'++test_expect_success 'direct image mount changes and move_mount are denied in private namespaces' '+ python3 tamperproof/t1150-verity-devices.py mounts+'++test_donediff --git a/testing/tamperproof/t1151-verity-process.py b/testing/tamperproof/t1151-verity-process.pynew file mode 100644index 00000000..fc67efc8--- /dev/null+++ b/testing/tamperproof/t1151-verity-process.py@@ -0,0 +1,153 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++import ctypes+import errno+import os+import platform+import struct+import signal+import subprocess+import sys+import tempfile+import time++libc = ctypes.CDLL(None, use_errno=True)+libc.ptrace.argtypes = (ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p)+libc.ptrace.restype = ctypes.c_long+libc.syscall.restype = ctypes.c_long+++class Iovec(ctypes.Structure):+ _fields_ = [("base", ctypes.c_void_p), ("length", ctypes.c_size_t)]+++libc.process_vm_writev.argtypes = (ctypes.c_int, ctypes.POINTER(Iovec), ctypes.c_ulong,+ ctypes.POINTER(Iovec), ctypes.c_ulong, ctypes.c_ulong)+libc.process_vm_writev.restype = ctypes.c_ssize_t++class SockFilter(ctypes.Structure):+ _fields_ = [("code", ctypes.c_ushort), ("jt", ctypes.c_ubyte),+ ("jf", ctypes.c_ubyte), ("k", ctypes.c_uint32)]+++class SockFprog(ctypes.Structure):+ _fields_ = [("length", ctypes.c_ushort),+ ("filter", ctypes.POINTER(SockFilter))]+++def allow_all_seccomp():+ instruction = SockFilter(6, 0, 0, 0x7fff0000)+ program = SockFprog(1, ctypes.pointer(instruction))+ assert libc.prctl(38, 1, 0, 0, 0) == 0, ("NO_NEW_PRIVS", ctypes.get_errno())+ assert libc.prctl(22, 2, ctypes.byref(program), 0, 0) == 0, \+ ("seccomp allow-all prerequisite", ctypes.get_errno())+++def outside_exec_with_seccomp():+ allow_all_seccomp()+ os.execv(sys.executable, [sys.executable, "-c", "pass"])+++def forbidden_exec_with_seccomp():+ allow_all_seccomp()+ try:+ os.execv(sys.argv[1], [sys.argv[1], "unexpected-exec"])+ except OSError as exc:+ assert exc.errno in (errno.EPERM, errno.EACCES), exc+ else:+ raise AssertionError("runtime exec succeeded under caller-controlled seccomp")+++def forbidden_exec_while_traced():+ assert libc.ptrace(0, 0, None, None) == 0, ("TRACEME prerequisite", ctypes.get_errno())+ try:+ os.execv(sys.argv[1], [sys.argv[1], "unexpected-exec"])+ except OSError as exc:+ assert exc.errno in (errno.EPERM, errno.EACCES), exc+ else:+ raise AssertionError("runtime exec succeeded with a pre-existing tracer")+++def child_check(fn):+ pid = os.fork()+ if not pid:+ try:+ fn()+ except BaseException as exc:+ print(f"pre-existing observer: {exc}", file=sys.stderr)+ os._exit(1)+ os._exit(0)+ _, status = os.waitpid(pid, 0)+ if os.WIFSTOPPED(status):+ libc.ptrace(17, pid, None, None)+ os.kill(pid, signal.SIGKILL)+ os.waitpid(pid, 0)+ raise AssertionError("trusted exec reached a ptrace stop")+ assert os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0, (fn.__name__, status)+++child_check(outside_exec_with_seccomp)+child_check(forbidden_exec_with_seccomp)+child_check(forbidden_exec_while_traced)+++with tempfile.TemporaryDirectory() as work:+ ready = os.path.join(work, "ready")+ target = subprocess.Popen([sys.argv[1], "wait", ready])+ try:+ for _ in range(100):+ if os.path.isfile(ready):+ fields = open(ready, encoding="ascii").read().split()+ if len(fields) == 2:+ break+ assert target.poll() is None, "trusted process exited early"+ time.sleep(0.05)+ else:+ raise AssertionError("trusted process did not become ready")+ pid, address = int(fields[0]), int(fields[1], 16)+ assert pid == target.pid+ ctypes.set_errno(0)+ result = libc.ptrace(16, pid, None, None)+ err = ctypes.get_errno()+ if result == 0:+ os.waitpid(pid, 0)+ libc.ptrace(17, pid, None, None)+ assert result == -1 and err in (errno.EPERM, errno.EACCES), ("ptrace", result, err)+ try:+ fd = os.open(f"/proc/{pid}/mem", os.O_WRONLY | os.O_CLOEXEC)+ except OSError as exc:+ assert exc.errno in (errno.EPERM, errno.EACCES), exc+ else:+ os.close(fd)+ raise AssertionError("writable /proc/pid/mem was opened")+ perf_syscall = {"x86_64": 298, "aarch64": 241, "riscv64": 241}[platform.machine()]+ attributes = ctypes.create_string_buffer(64)+ struct.pack_into("IIQQQQQ", attributes, 0, 1, 64, 0, 0, 0, 0, 1)+ for perf_pid, cpu in ((pid, -1),):+ ctypes.set_errno(0)+ event_fd = libc.syscall(perf_syscall, ctypes.byref(attributes),+ perf_pid, cpu, -1, 0)+ err = ctypes.get_errno()+ if event_fd >= 0:+ os.close(event_fd)+ assert event_fd == -1 and err in (errno.EPERM, errno.EACCES), \+ ("perf_event_open", perf_pid, cpu, event_fd, err)+ value = ctypes.c_ulong(0)+ source = Iovec(ctypes.addressof(value), ctypes.sizeof(value))+ destination = Iovec(address, ctypes.sizeof(value))+ ctypes.set_errno(0)+ result = libc.process_vm_writev(pid, ctypes.byref(source), 1,+ ctypes.byref(destination), 1, 0)+ err = ctypes.get_errno()+ assert result == -1 and err in (errno.EPERM, errno.EACCES), \+ ("process_vm_writev", result, err)+ finally:+ if target.poll() is None:+ target.send_signal(signal.SIGTERM)+ try:+ target.wait(timeout=3)+ except subprocess.TimeoutExpired:+ target.kill()+ target.wait(timeout=3)+print("trusted process memory guards passed")diff --git a/testing/tamperproof/t1151-verity-process.sh b/testing/tamperproof/t1151-verity-process.shnew file mode 100755index 00000000..3cde850e--- /dev/null+++ b/testing/tamperproof/t1151-verity-process.sh@@ -0,0 +1,22 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++cd "$(dirname "$0")/.."+. ./integration-lib.sh+verity_required() {+ printf 'Bail out! %s\n' "$*" >&2+ exit 1+}+target_guard++: "${SHIRUDO_TEST_RUNTIME_PROBE:=/run/shirudo/runtime/usr/bin/shirudo-policy-probe}"+[ -x "$SHIRUDO_TEST_RUNTIME_PROBE" ] ||+ verity_required "runtime image has no authority test fixture"+command -v python3 >/dev/null 2>&1 || verity_required "no python3"++test_expect_success 'root cannot attach or write memory of an image-authorized task' '+ python3 tamperproof/t1151-verity-process.py "$SHIRUDO_TEST_RUNTIME_PROBE"+'++test_donediff --git a/testing/tamperproof/t1153-verity-hidden.py b/testing/tamperproof/t1153-verity-hidden.pynew file mode 100644index 00000000..ada547c3--- /dev/null+++ b/testing/tamperproof/t1153-verity-hidden.py@@ -0,0 +1,132 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++import ctypes+import hashlib+import os+import pathlib+import platform+import subprocess+import sys+import tempfile++libc = ctypes.CDLL(None, use_errno=True)+libc.mount.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p,+ ctypes.c_ulong, ctypes.c_char_p)+libc.unshare.argtypes = (ctypes.c_int,)+libc.syscall.restype = ctypes.c_long+RUNTIME = "/run/shirudo/runtime"+MODE_QUERY = 0x53520001+IMAGE_MODE_ERRNO = 1002+++def keyring_contents():+ syscall = {"x86_64": 250, "aarch64": 219, "riscv64": 219}[platform.machine()]+ size = libc.syscall(syscall, 11, -9, None, 0, 0)+ assert size >= 4, ("BPF keyring read prerequisite", ctypes.get_errno())+ data = ctypes.create_string_buffer(size)+ count = libc.syscall(syscall, 11, -9, data, size, 0)+ assert count == size, ("BPF keyring read", count, size, ctypes.get_errno())+ return data.raw+++def snapshot():+ files = {}+ for directory in ("/var/lib/shirudo/config-update",):+ root = pathlib.Path(directory)+ if not root.exists():+ continue+ for path in sorted(root.rglob("*")):+ if path.is_file():+ files[str(path)] = hashlib.sha256(path.read_bytes()).digest()+ mappings = {}+ for device in pathlib.Path("/sys/block").glob("dm-*"):+ mappings[device.name] = tuple((device / name).read_text().strip()+ for name in ("dm/name", "dm/uuid", "dev", "diskseq"))+ return files, mappings, keyring_contents()+++def runtime_command(binary):+ interpreter = {+ "x86_64": "lib64/ld-linux-x86-64.so.2",+ "aarch64": "lib/ld-linux-aarch64.so.1",+ "riscv64": "lib/ld-linux-riscv64-lp64d.so.1",+ }[platform.machine()]+ loader = pathlib.Path(RUNTIME) / interpreter+ assert os.access(loader, os.X_OK), ("runtime interpreter prerequisite", loader)+ libraries = [pathlib.Path(RUNTIME) / name+ for name in ("lib", "lib64", "usr/lib", "usr/lib64")]+ for pattern in ("lib/*-linux-gnu", "usr/lib/*-linux-gnu"):+ libraries.extend(sorted(path for path in pathlib.Path(RUNTIME).glob(pattern)+ if path.is_dir()))+ return [str(loader), "--inhibit-cache", "--library-path",+ ":".join(map(str, libraries)), binary]+++def chroot_run(root, command, arguments):+ def enter():+ os.chroot(root)+ os.chdir("/")+ ctypes.set_errno(0)+ mode = libc.prctl(MODE_QUERY, 0, 0, 0, 0)+ if mode != -1 or ctypes.get_errno() != IMAGE_MODE_ERRNO:+ raise RuntimeError(("mode query became hidden", mode, ctypes.get_errno()))++ return subprocess.run([*command, *arguments], preexec_fn=enter,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ timeout=30, check=False)+++def isolated(root, command):+ assert libc.unshare(0x00020000) == 0, ("mount namespace prerequisite", ctypes.get_errno())+ assert libc.mount(None, b"/", None, (1 << 18) | (1 << 14), None) == 0, \+ ("recursive private namespace prerequisite", ctypes.get_errno())+ for line in open("/proc/self/mountinfo", encoding="ascii"):+ fields = line.split()+ optional = fields[6:fields.index("-")]+ assert not any(item.startswith(("shared:", "master:")) for item in optional), \+ ("namespace propagation is not isolated", line)+ destination = pathlib.Path(root + RUNTIME)+ destination.mkdir(parents=True)+ assert libc.mount(RUNTIME.encode(), str(destination).encode(), None, 4096, None) == 0, \+ ("verified runtime bind prerequisite", ctypes.get_errno())+ assert not pathlib.Path(root + "/run/shirudo/bpffs").exists()+ for arguments, expected in ((["init"], b"authenticated image settings"),+ (["status"], b"image state"),+ (["image", "status"], b"image state")):+ result = chroot_run(root, command, arguments)+ assert result.returncode > 0, (arguments, result.returncode, result.stderr)+ assert expected in result.stderr, (arguments, result.stderr)+ assert b"pre-flight" not in result.stderr, (arguments, result.stderr)+ assert b"error while loading shared libraries" not in result.stderr, result.stderr+++def main():+ binary = os.path.abspath(sys.argv[1])+ assert binary.startswith(RUNTIME + "/"), ("runtime executable required", binary)+ command = runtime_command(binary)+ healthy = subprocess.run([*command, "image", "status"], capture_output=True,+ timeout=30, check=False)+ assert healthy.returncode == 0, ("healthy image prerequisite", healthy.stderr)+ ctypes.set_errno(0)+ mode = libc.prctl(MODE_QUERY, 0, 0, 0, 0)+ assert mode == -1 and ctypes.get_errno() == IMAGE_MODE_ERRNO, \+ ("image mode query prerequisite", mode, ctypes.get_errno())+ before = snapshot()+ with tempfile.TemporaryDirectory(prefix="shirudo-hidden-") as root:+ child = os.fork()+ if not child:+ try:+ isolated(root, command)+ except BaseException:+ import traceback+ traceback.print_exc()+ os._exit(1)+ os._exit(0)+ _, status = os.waitpid(child, 0)+ assert os.waitstatus_to_exitcode(status) == 0, status+ assert snapshot() == before, "hidden-bpffs attempts altered journal, keyring or mappings"+++if __name__ == "__main__":+ main()diff --git a/testing/tamperproof/t1153-verity-hidden.sh b/testing/tamperproof/t1153-verity-hidden.shnew file mode 100755index 00000000..6bd4b0d8--- /dev/null+++ b/testing/tamperproof/t1153-verity-hidden.sh@@ -0,0 +1,22 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++cd "$(dirname "$0")/.."+. ./integration-lib.sh+verity_required() {+ printf 'Bail out! %s\n' "$*" >&2+ exit 1+}+target_guard++: "${SHIRUDO_TEST_RUNTIME_BIN:=/run/shirudo/runtime/usr/bin/shirudo}"+mountpoint -q /run/shirudo/runtime && [ -x "$SHIRUDO_TEST_RUNTIME_BIN" ] ||+ verity_required "requires the executable from the runtime image"+command -v python3 >/dev/null 2>&1 || verity_required "no python3"++test_expect_success 'hidden bpffs cannot make an image executable initialize legacy state' '+ python3 tamperproof/t1153-verity-hidden.py "$SHIRUDO_TEST_RUNTIME_BIN"+'++test_done