Skip to content

eBPF-based security platform

bpf: deny pin, map and link descriptors to tasks without authority

Daniel Borkmann4d9bf32c4adb
diff --git a/bpf/admission.h b/bpf/admission.h
index a50d10d6..99f0eb1c 100644
--- a/bpf/admission.h
+++ b/bpf/admission.h
@@ -78,16 +78,25 @@ int BPF_PROG(shirudo_lsm_bpf, int cmd, union bpf_attr *attr,
return shirudo_self_or_deny(SHIRUDO_TAMPER_OBJ_PIN);
/*
- * Read-only / observability cmds, so `bpftool prog show`,
- * `shirudo status`, and `shirudo upatch get/map` keep working.
- * BPF_OBJ_UNPIN does not exist as a bpf() cmd; VFS unlink removes
- * pins and shirudo's lsm/inode_unlink hook blocks `rm` on the
- * private bpffs.
+ * A descriptor keeps its object alive: a link held open stays
+ * attached after shirudo unpins it for an unload, a revocation or
+ * the undo of a refused load, and no LSM hook sees a link descriptor
+ * being handed out. A map descriptor reads the state the serializers
+ * own. Neither is root's to take, by pin or by id.
+ */
+ case BPF_OBJ_GET:
+ case BPF_MAP_GET_FD_BY_ID:
+ case BPF_LINK_GET_FD_BY_ID:
+ return shirudo_self_or_deny(SHIRUDO_TAMPER_OBJ_GET);
+
+ /*
+ * Read-only / observability cmds. BPF_OBJ_UNPIN does not exist as a
+ * bpf() cmd; VFS unlink removes pins and shirudo's lsm/inode_unlink
+ * hook blocks `rm` on the private bpffs.
*/
case BPF_MAP_LOOKUP_ELEM:
case BPF_MAP_GET_NEXT_KEY:
case BPF_MAP_LOOKUP_BATCH:
- case BPF_OBJ_GET:
case BPF_OBJ_GET_INFO_BY_FD:
case BPF_PROG_QUERY:
case BPF_PROG_GET_NEXT_ID:
@@ -95,9 +104,7 @@ int BPF_PROG(shirudo_lsm_bpf, int cmd, union bpf_attr *attr,
case BPF_BTF_GET_NEXT_ID:
case BPF_LINK_GET_NEXT_ID:
case BPF_PROG_GET_FD_BY_ID:
- case BPF_MAP_GET_FD_BY_ID:
case BPF_BTF_GET_FD_BY_ID:
- case BPF_LINK_GET_FD_BY_ID:
case BPF_TASK_FD_QUERY:
return 0;
@@ -122,25 +129,19 @@ 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.
+ * mmap lets it alter arena pages without another bpf() command; a
+ * read-only one reads what the serializers own. Every route to a map
+ * descriptor ends here, so every one is shirudo's.
*/
SEC("lsm/bpf_map")
int BPF_PROG(shirudo_lsm_bpf_map, struct bpf_map *map, fmode_t fmode,
int ret)
{
- struct shirudo_sb_id *id = shirudo_policy();
-
if (ret)
return ret;
if (fmode & FMODE_WRITE)
return shirudo_self_or_deny(SHIRUDO_TAMPER_MAP_FD);
- if (!shirudo_private_map(map))
- return 0;
- if (!id || !shirudo_task_is_self(id))
- return -EACCES;
- return 0;
+ return shirudo_self_or_deny(SHIRUDO_TAMPER_OBJ_GET);
}
/*
diff --git a/bpf/bpf2.c b/bpf/bpf2.c
index 8d6242ce..b3151005 100644
--- a/bpf/bpf2.c
+++ b/bpf/bpf2.c
@@ -144,10 +144,11 @@ deny:
}
/*
- * The bpffs mount of init's namespace, recorded once when the bootstrap
- * task opens its root with the mount guards live: the one the unmount
- * guard keeps, where a copy in another namespace is any process's to
- * drop.
+ * A pin opened as a file reads a map's contents through bpffs, so pins
+ * open for shirudo alone; directories stay listable. The bpffs mount of
+ * init's namespace is recorded once when the bootstrap task opens its
+ * root with the mount guards live: the one the unmount guard keeps,
+ * where a copy in another namespace is any process's to drop.
*/
SEC("lsm/file_open")
int BPF_PROG(shirudo_lsm_file_open, struct file *file, int ret)
@@ -157,11 +158,15 @@ int BPF_PROG(shirudo_lsm_file_open, struct file *file, int ret)
struct vfsmount *mnt;
__u32 zero = 0;
- if (ret || !id || !shirudo_bootstrap_task())
+ if (ret || !id)
return ret;
mnt = BPF_CORE_READ(file, f_path.mnt);
if (!mnt || BPF_CORE_READ(mnt, mnt_sb, s_dev) != id->sb_dev)
return 0;
+ if ((BPF_CORE_READ(file, f_inode, i_mode) & S_IFMT) != S_IFDIR)
+ return shirudo_self_or_deny(SHIRUDO_TAMPER_OBJ_GET);
+ if (!shirudo_bootstrap_task())
+ return 0;
rec = bpf_map_lookup_elem(&shirudo_mnt_rec, &zero);
if (rec && !rec->mount)
rec->mount = (__u64)shirudo_mount_of(mnt);
diff --git a/bpf/lib/shirudo_tamper.h b/bpf/lib/shirudo_tamper.h
index 242bf116..cbc09adf 100644
--- a/bpf/lib/shirudo_tamper.h
+++ b/bpf/lib/shirudo_tamper.h
@@ -46,6 +46,7 @@ enum shirudo_tamper_point {
SHIRUDO_TAMPER_SEAL_COPY_UP,
SHIRUDO_TAMPER_KEXEC,
SHIRUDO_TAMPER_TPM_EXTEND,
+ SHIRUDO_TAMPER_OBJ_GET,
SHIRUDO_TAMPER_MAX
};
diff --git a/bpf/lsm.h b/bpf/lsm.h
index 59f7e558..21ecfab1 100644
--- a/bpf/lsm.h
+++ b/bpf/lsm.h
@@ -24,6 +24,12 @@
#ifndef FMODE_WRITE
#define FMODE_WRITE 0x2
#endif
+#ifndef S_IFMT
+#define S_IFMT 00170000
+#endif
+#ifndef S_IFDIR
+#define S_IFDIR 0040000
+#endif
#define LSM_UNSAFE_PTRACE 2
#define PR_SET_MM 35
#define PR_SET_MM_EXE_FILE 13
diff --git a/bpf/seal.h b/bpf/seal.h
index 4269e07e..ebbe8038 100644
--- a/bpf/seal.h
+++ b/bpf/seal.h
@@ -22,12 +22,6 @@
#ifndef FMODE_WRITE
#define FMODE_WRITE 0x2
#endif
-#ifndef S_IFMT
-#define S_IFMT 00170000
-#endif
-#ifndef S_IFDIR
-#define S_IFDIR 0040000
-#endif
#define SHIRUDO_XATTR "security.bpf.shirudo"
/* The label is a SHA-256 hex string (util/seal.h) -- always 64 bytes. */
diff --git a/bpf/verity_policy.h b/bpf/verity_policy.h
index 5b77d47c..87230f81 100644
--- a/bpf/verity_policy.h
+++ b/bpf/verity_policy.h
@@ -59,16 +59,6 @@ shirudo_protected_filesystem(const struct shirudo_sb_id *id, __u32 dev)
return dev == id->sb_dev || (id->run_dev && dev == id->run_dev);
}
-/* Device records expose pointers and belong only to trusted image tasks. */
-static __always_inline bool shirudo_private_map(struct bpf_map *map)
-{
- char name[16] = {};
-
- bpf_probe_read_kernel_str(name, sizeof(name), map->name);
- return !__builtin_memcmp(name, "shirudo_devices", sizeof(name)) ||
- !__builtin_memcmp(name, "shirudo_mnt_rec", sizeof(name));
-}
-
/* Device pointers can be reused even when the free hook did not run. */
static __always_inline struct shirudo_device *
shirudo_bdev_device(struct block_device *bdev)
diff --git a/testing/functional/tamperproof/t6005-mode-objects.sh b/testing/functional/tamperproof/t6005-mode-objects.sh
index c470e6d1..db203f1b 100755
--- a/testing/functional/tamperproof/t6005-mode-objects.sh
+++ b/testing/functional/tamperproof/t6005-mode-objects.sh
@@ -33,45 +33,4 @@ assert "bpf_real_data_inode" in inventory["seal"]["extern"]
PYTEST
'
-test_expect_success 'the PR_SET_MM fixture matches the native identity map ABI' '
- python3 - <<"PYTEST"
-import ast
-import ctypes
-import os
-from pathlib import Path
-import shlex
-import subprocess
-import tempfile
-
-root = Path.cwd().parent
-path = root / "testing/functional/tamperproof/t6110-pr-set-mm-identity.py"
-definition = next(node for node in ast.parse(path.read_text()).body
- if isinstance(node, ast.ClassDef) and node.name == "ShirudoIdentity")
-namespace = {"ctypes": ctypes}
-exec(compile(ast.Module(body=[definition], type_ignores=[]), str(path), "exec"), namespace)
-identity = namespace["ShirudoIdentity"]
-fields = [name for name, field_type in identity._fields_]
-source = "\n".join([
- "#include <stddef.h>",
- "#include <stdio.h>",
- "#include \"util/identity.h\"",
- "int main(void)",
- "{",
- "\tprintf(\"%zu\\n\", sizeof(struct shirudo_identity));",
- *[f"\tprintf(\"%zu\\n\", offsetof(struct shirudo_identity, {name}));" for name in fields],
- "\treturn 0;",
- "}",
-])
-with tempfile.TemporaryDirectory(prefix="shirudo-identity-abi-") as directory:
- binary = Path(directory) / "identity-layout"
- command = shlex.split(os.environ.get("CC", "cc"))
- command += ["-std=gnu11", "-I" + str(root), "-I" + str(root / "include"),
- "-x", "c", "-", "-o", str(binary)]
- subprocess.run(command, input=source, text=True, check=True)
- actual = [int(value) for value in subprocess.check_output([binary], text=True).split()]
-expected = [ctypes.sizeof(identity)] + [getattr(identity, name).offset for name in fields]
-assert actual == expected, (actual, expected)
-PYTEST
-'
-
test_done
diff --git a/testing/functional/tamperproof/t6107-bpf-cmd-deny.sh b/testing/functional/tamperproof/t6107-bpf-cmd-deny.sh
index b8f189ed..2add27fb 100755
--- a/testing/functional/tamperproof/t6107-bpf-cmd-deny.sh
+++ b/testing/functional/tamperproof/t6107-bpf-cmd-deny.sh
@@ -6,9 +6,11 @@
# or denies outright. A root process that is not shirudo gets EACCES for
# link creation, raw tracepoint opens and pins (a vetted program must
# not be re-attached where its signer never meant it to run, and the
-# private bpffs takes no entries shirudo did not make), for the
-# tear-down and mutation commands the policy default-denies, and for an
-# unclassified command; a read-only command is answered by the kernel.
+# private bpffs takes no entries shirudo did not make), for opening a
+# pin or a map or link by id (a held link stays attached after shirudo
+# unpins it), for the tear-down and mutation commands the policy
+# default-denies, and for an unclassified command; a read-only command
+# is answered by the kernel.
# The hook decides before the kernel reads the attr, so every attr here
# is empty. Non-destructive: nothing is created.
@@ -32,6 +34,10 @@ test_expect_success 'link creation, raw tracepoint open and pin are shirudo-only
denied LINK_CREATE RAW_TRACEPOINT_OPEN OBJ_PIN
'
+test_expect_success 'opening a pin or a map or link by id is shirudo-only' '
+ denied OBJ_GET MAP_GET_FD_BY_ID LINK_GET_FD_BY_ID
+'
+
test_expect_success 'map creation, update, freeze and test run are shirudo-only' '
denied MAP_CREATE MAP_UPDATE_ELEM MAP_FREEZE PROG_TEST_RUN
'
diff --git a/testing/functional/tamperproof/t6108-tamper-counters.sh b/testing/functional/tamperproof/t6108-tamper-counters.sh
index dec9802f..30fdb27f 100755
--- a/testing/functional/tamperproof/t6108-tamper-counters.sh
+++ b/testing/functional/tamperproof/t6108-tamper-counters.sh
@@ -53,7 +53,7 @@ d = json.load(sys.stdin)[\"tamper_attempts\"]
assert isinstance(d[\"total\"], int)
assert all(isinstance(v, int) for v in d[\"counters\"].values())
assert \"PinRename\" in d[\"counters\"] and \"ProgAttach\" in d[\"counters\"]
-assert \"LoadNotLoader\" in d[\"counters\"]
+assert \"LoadNotLoader\" in d[\"counters\"] and \"ObjGet\" in d[\"counters\"]
"
'
@@ -91,6 +91,15 @@ test_expect_success 'a link creation moves ProgAttach and a pin moves ObjPin' '
grew ProgAttach "$ProgAttach" && grew ObjPin "$pin"
'
+test_expect_success 'opening a pin, by pin or as a file, moves ObjGet' '
+ before=$(counter ObjGet) &&
+ [ "$(./$C OBJ_GET)" = "errno=13" ] &&
+ grew ObjGet "$before" &&
+ before=$(counter ObjGet) &&
+ ! cat "$B/tamper" >/dev/null 2>&1 &&
+ grew ObjGet "$before"
+'
+
test_expect_success 'a denied tear-down command moves BpfCommand' '
before=$(counter BpfCommand) &&
[ "$(./$C LINK_DETACH)" = "errno=13" ] &&
diff --git a/testing/functional/tamperproof/t6109-map-lockdown.sh b/testing/functional/tamperproof/t6109-map-lockdown.sh
index cef466fc..8cea0221 100644
--- a/testing/functional/tamperproof/t6109-map-lockdown.sh
+++ b/testing/functional/tamperproof/t6109-map-lockdown.sh
@@ -2,8 +2,10 @@
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c) 2026 Authors of shirudo
#
-# t6109 -- direct BPF syscalls from a root process with a different
-# executable cannot acquire writable map fds or mutate Shirudo's maps.
+# t6109 -- a root process with a different executable cannot take hold
+# of shirudo's maps: no descriptor by pin or by id, read-only or
+# writable, and no read of a pin as a file. A serializer program it
+# reaches by id cannot be test-run to drain what the map export reads.
# PR_SET_MM executable spoofing is covered separately by t6110.
cd "$(dirname "$0")/../.."
@@ -42,18 +44,14 @@ import platform
import subprocess
import sys
-BPF_MAP_UPDATE_ELEM = 2
+BPF_OBJ_GET = 7
BPF_PROG_TEST_RUN = 10
-BPF_MAP_FREEZE = 22
+BPF_PROG_GET_NEXT_ID = 11
+BPF_MAP_GET_NEXT_ID = 12
+BPF_PROG_GET_FD_BY_ID = 13
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:
@@ -64,8 +62,6 @@ except KeyError as 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):
@@ -74,33 +70,31 @@ class ObjGetAttr(ctypes.Structure):
("file_flags", ctypes.c_uint32)]
+class IdAttr(ctypes.Structure):
+ _fields_ = [("id", ctypes.c_uint32),
+ ("next_id", ctypes.c_uint32),
+ ("open_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):
+class ProgInfoPrefix(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)]
+ ("tag", ctypes.c_uint8 * 8),
+ ("jited_prog_len", ctypes.c_uint32),
+ ("xlated_prog_len", ctypes.c_uint32),
+ ("jited_prog_insns", ctypes.c_uint64),
+ ("xlated_prog_insns", ctypes.c_uint64),
+ ("load_time", ctypes.c_uint64),
+ ("created_by_uid", ctypes.c_uint32),
+ ("nr_map_ids", ctypes.c_uint32),
+ ("map_ids", ctypes.c_uint64),
+ ("name", ctypes.c_char * 16)]
class SerializerCtx(ctypes.Structure):
@@ -139,88 +133,73 @@ def bpf(cmd, 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")
+ if error != errno.EACCES:
+ raise AssertionError(f"{label}: errno={error}, expected EACCES")
-for map_name in ("shirudo_ser",):
- path = os.path.join(sys.argv[1], map_name)
- assert_denied(obj_get(path, 0), f"writable fd for {map_name}")
+def obj_get(path, flags):
+ name = ctypes.create_string_buffer(os.fsencode(path) + b"\0")
+ return bpf(BPF_OBJ_GET, ObjGetAttr(ctypes.addressof(name), 0, flags))
+
+
+def ids(cmd):
+ current = 0
+ while True:
+ attr = IdAttr(current, 0, 0)
+ result, _ = bpf(cmd, attr)
+ if result < 0:
+ return
+ current = attr.next_id
+ yield current
- readonly_fd, error = obj_get(path, BPF_F_RDONLY)
- if readonly_fd < 0:
- raise AssertionError(f"read-only fd for {map_name}: errno={error}")
+
+def open_file(path):
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)
-
-serializer_path = os.path.join(os.path.dirname(sys.argv[1]),
- "serializers/exec")
-serializer_fd, error = obj_get(serializer_path, 0)
+ fd = os.open(path, os.O_RDONLY)
+ except OSError as exc:
+ return -1, exc.errno
+ return fd, 0
+
+
+pins = [os.path.join(sys.argv[1], name) for name in os.listdir(sys.argv[1])
+ if not os.path.isdir(os.path.join(sys.argv[1], name))]
+if not pins:
+ raise AssertionError(f"no map pins under {sys.argv[1]}")
+pins.append(os.path.join(os.path.dirname(sys.argv[1]), "serializers/exec"))
+for pin in pins:
+ assert_denied(obj_get(pin, 0), f"writable fd for {pin}")
+ assert_denied(obj_get(pin, BPF_F_RDONLY), f"read-only fd for {pin}")
+ assert_denied(open_file(pin), f"open of {pin}")
+
+maps = 0
+for map_id in ids(BPF_MAP_GET_NEXT_ID):
+ assert_denied(bpf(BPF_MAP_GET_FD_BY_ID, IdAttr(map_id, 0, 0)),
+ f"writable fd for map {map_id}")
+ assert_denied(bpf(BPF_MAP_GET_FD_BY_ID, IdAttr(map_id, 0, BPF_F_RDONLY)),
+ f"read-only fd for map {map_id}")
+ maps += 1
+if not maps:
+ raise AssertionError("no map ids to try")
+
+serializer_fd = -1
+for prog_id in ids(BPF_PROG_GET_NEXT_ID):
+ fd, error = bpf(BPF_PROG_GET_FD_BY_ID, IdAttr(prog_id, 0, 0))
+ if fd < 0:
+ continue
+ info = ProgInfoPrefix()
+ attr = ObjInfoAttr(fd, ctypes.sizeof(info), ctypes.addressof(info))
+ result, error = bpf(BPF_OBJ_GET_INFO_BY_FD, attr)
+ if result == 0 and info.name.startswith(b"shirudo_seriali"):
+ serializer_fd = fd
+ break
+ os.close(fd)
if serializer_fd < 0:
- raise AssertionError(f"exec serializer fd: errno={error}")
+ raise AssertionError("no serializer program found by id")
try:
ctx = SerializerCtx(0x5A4C5253, 3, 0, 1, 4032, 0, 0, 1)
attr = ProgTestRunAttr(serializer_fd, 0, 0, 0, 0, 0, 1, 0,
@@ -246,10 +225,11 @@ if not any(record.get("path") == python_exe for record in records):
raise AssertionError(
f"Python exec record was lost after denied serializer run: {records!r}")
-print("root BPF map mutation and serializer test-run denied; export preserved")
+print("root cannot open maps by pin, file or id; test-run denied; "
+ "export preserved")
PYTHON
-test_expect_success 'root map mutation and serializer test-run are denied' '
+test_expect_success 'root cannot open maps or test-run a serializer' '
"$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck >/dev/null 2>&1 &&
python3 "$WORK/check.py" "$MAPS" "$SHIRUDO_BIN" "$WORK"
'
diff --git a/testing/functional/tamperproof/t6110-pr-set-mm-identity.py b/testing/functional/tamperproof/t6110-pr-set-mm-identity.py
index cb5213f3..02357df1 100644
--- a/testing/functional/tamperproof/t6110-pr-set-mm-identity.py
+++ b/testing/functional/tamperproof/t6110-pr-set-mm-identity.py
@@ -5,6 +5,7 @@ import ctypes
import errno
import os
import platform
+import subprocess
import sys
PR_SET_MM = 35
@@ -12,6 +13,8 @@ PR_SET_MM_EXE_FILE = 13
PR_SET_MM_MAP = 14
SHIRUDO_COMMAND = os.path.abspath(sys.argv[1])
RUNTIME = "/run/shirudo/runtime"
+PROBE = os.environ.get("SHIRUDO_TEST_RUNTIME_PROBE",
+ RUNTIME + "/usr/bin/shirudo-policy-probe")
libc = ctypes.CDLL(None, use_errno=True)
libc.prctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong,
@@ -33,9 +36,8 @@ OTHER = next(os.path.realpath(path) for path in
BPF_SYSCALL = {"x86_64": 321, "aarch64": 280,
"riscv64": 280}[platform.machine()]
BPF_OBJ_GET = 7
-BPF_OBJ_GET_INFO_BY_FD = 15
-BPF_MAP_LOOKUP_ELEM = 1
BPF_F_RDONLY = 1 << 3
+IDENTITY = "/run/shirudo/bpffs/identity"
class ObjGetAttr(ctypes.Structure):
@@ -44,77 +46,24 @@ class ObjGetAttr(ctypes.Structure):
("file_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)]
-
-
-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 ShirudoIdentity(ctypes.Structure):
- _fields_ = [("sb_dev", ctypes.c_uint32),
- ("run_dev", ctypes.c_uint32),
- ("keyring_serial", ctypes.c_int32),
- ("keyring_type", ctypes.c_uint32),
- ("n_keys", ctypes.c_uint32),
- ("key_serials", ctypes.c_int32 * 16),
- ("runtime_root", ctypes.c_uint8 * 32),
- ("nv_writer_seed", ctypes.c_uint8 * 32),
- ("nv_writer_public", ctypes.c_uint8 * 384),
- ("ak_name", ctypes.c_uint8 * 34),
- ("ak_name_len", ctypes.c_uint32),
- ("dm_verity_ring", ctypes.c_int32),
- ("dm_verity_key", ctypes.c_int32),
- ("nv_index", ctypes.c_uint32)]
+def probe_identity(field):
+ return subprocess.run([PROBE, "identity", IDENTITY, field], check=True,
+ capture_output=True, text=True).stdout.strip()
def assert_frozen_runtime():
- path = b"/run/shirudo/bpffs/identity\0"
- name = ctypes.create_string_buffer(path)
+ name = ctypes.create_string_buffer(os.fsencode(IDENTITY) + b"\0")
get_attr = ObjGetAttr(ctypes.addressof(name), 0, BPF_F_RDONLY)
+ ctypes.set_errno(0)
fd = libc.syscall(BPF_SYSCALL, BPF_OBJ_GET, ctypes.byref(get_attr),
ctypes.sizeof(get_attr))
- assert fd >= 0, ("open identity map", ctypes.get_errno())
- try:
- info = MapInfoPrefix()
- info_attr = ObjInfoAttr(fd, ctypes.sizeof(info), ctypes.addressof(info))
- result = libc.syscall(BPF_SYSCALL, BPF_OBJ_GET_INFO_BY_FD,
- ctypes.byref(info_attr), ctypes.sizeof(info_attr))
- assert result == 0, ("identity map metadata", ctypes.get_errno())
- assert info.type == 2 and info.key_size == 4 and info.max_entries == 1, \
- ("identity map shape", info.type, info.key_size, info.max_entries)
- assert ctypes.sizeof(ShirudoIdentity) <= info.value_size <= 1024 * 1024, \
- ("identity map value size", info.value_size)
- key = ctypes.c_uint32(0)
- buffer = ctypes.create_string_buffer(info.value_size)
- lookup_attr = MapElemAttr(fd, 0, ctypes.addressof(key),
- ctypes.addressof(buffer), 0)
- result = libc.syscall(BPF_SYSCALL, BPF_MAP_LOOKUP_ELEM,
- ctypes.byref(lookup_attr),
- ctypes.sizeof(lookup_attr))
- assert result == 0, ("read identity map", ctypes.get_errno())
- finally:
+ error = ctypes.get_errno()
+ if fd >= 0:
os.close(fd)
- value = ShirudoIdentity.from_buffer_copy(buffer.raw)
- assert info.value_size == ctypes.sizeof(ShirudoIdentity), info.value_size
- assert any(value.runtime_root), "runtime hash missing"
- assert value.nv_index, "NV index missing"
+ assert fd < 0 and error == errno.EACCES, \
+ ("identity map opened by a non-Shirudo caller", fd, error)
+ assert probe_identity("runtime_root").strip("0"), "runtime hash missing"
+ assert int(probe_identity("nv_index")), "NV index missing"
executable = os.path.realpath(SHIRUDO)
runtime = os.path.realpath(RUNTIME)
assert os.path.commonpath((executable, runtime)) == runtime, executable
diff --git a/testing/functional/tamperproof/t6138-upatch-integrity.sh b/testing/functional/tamperproof/t6138-upatch-integrity.sh
index 5c3fa4a5..c649025b 100755
--- a/testing/functional/tamperproof/t6138-upatch-integrity.sh
+++ b/testing/functional/tamperproof/t6138-upatch-integrity.sh
@@ -6,7 +6,8 @@
# loader with one bit flipped and its userspace digest recomputed passes
# every userspace check and is refused by the kernel's signature check,
# leaving no pin or archive, and root can neither change the pin's
-# payload binding nor detach or update its link. The mutated loader keeps
+# payload binding nor take hold of its link, by pin or by id, to keep it
+# attached, detach it or update it. The mutated loader keeps
# its signed name, which is covered by the signature; it is the lifecycle
# fixture's, which is not loaded.
@@ -59,7 +60,7 @@ test_expect_success 'root cannot change the live payload binding xattr' '
after=$(python3 -c "import os,sys; print(os.getxattr(sys.argv[1], \"security.bpf.shirudo.payload\").hex())" "$PINDIR") &&
[ "$before" = "$after" ]
'
-test_expect_success 'root cannot detach or update a live upatch link' '
+test_expect_success 'root cannot open a live upatch link by pin or id' '
"$HELPER" "$PIN" &&
[ -e "$PIN" ]
'
diff --git a/testing/functional/tpm/t4103-nv-writer.sh b/testing/functional/tpm/t4103-nv-writer.sh
index 504777d6..e13c1559 100644
--- a/testing/functional/tpm/t4103-nv-writer.sh
+++ b/testing/functional/tpm/t4103-nv-writer.sh
@@ -15,6 +15,9 @@ target_guard
test_skip_all "test-nv-cphash not built"
[ -n "${SHIRUDO_TEST_FIXTURES_DIR:-}" ] ||
test_skip_all "target fixture directory is not set"
+: "${SHIRUDO_TEST_RUNTIME_PROBE:=/run/shirudo/runtime/usr/bin/shirudo-policy-probe}"
+[ -x "$SHIRUDO_TEST_RUNTIME_PROBE" ] ||
+ test_skip_all "runtime policy probe is not installed"
NAME=shirudo-test-lifecycle
LOAD="$SHIRUDO_TEST_FIXTURES_DIR/$NAME.upatch"
@@ -58,7 +61,9 @@ PY
}
test_expect_success 'the TPM writer public key matches the init record' '
- ./helper/test-nv-writer public
+ public=$("$SHIRUDO_TEST_RUNTIME_PROBE" identity \
+ /run/shirudo/bpffs/identity nv_writer_public) &&
+ ./helper/test-nv-writer public "$public"
'
test_expect_success 'unrelated TPM signing works on both device nodes' '
diff --git a/testing/helper/policy-probe.c b/testing/helper/policy-probe.c
index 1fdc3565..eb9a6587 100644
--- a/testing/helper/policy-probe.c
+++ b/testing/helper/policy-probe.c
@@ -35,8 +35,10 @@ static int check_mark(const char *pin, int expected)
attr.file_flags = BPF_F_RDONLY;
fd = syscall(SYS_bpf, BPF_OBJ_GET, &attr, sizeof(attr));
if (fd < 0) {
+ /* Only a task with authority may open the pin at all. */
+ rc = errno == EACCES && !expected ? 0 : 1;
close(pidfd);
- return 1;
+ return rc;
}
memset(&attr, 0, sizeof(attr));
attr.map_fd = fd;
@@ -52,6 +54,46 @@ static int check_mark(const char *pin, int expected)
return rc;
}
+static void print_hex(const __u8 *bytes, size_t n)
+{
+ size_t i;
+
+ for (i = 0; i < n; i++)
+ printf("%02x", bytes[i]);
+ printf("\n");
+}
+
+static int print_identity(const char *pin, const char *field)
+{
+ struct shirudo_identity id = {};
+ union bpf_attr attr = {};
+ __u32 zero = 0;
+ int fd, rc;
+
+ attr.pathname = (uintptr_t)pin;
+ attr.file_flags = BPF_F_RDONLY;
+ fd = syscall(SYS_bpf, BPF_OBJ_GET, &attr, sizeof(attr));
+ if (fd < 0)
+ return 1;
+ memset(&attr, 0, sizeof(attr));
+ attr.map_fd = fd;
+ attr.key = (uintptr_t)&zero;
+ attr.value = (uintptr_t)&id;
+ rc = syscall(SYS_bpf, BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
+ close(fd);
+ if (rc)
+ return 1;
+ if (!strcmp(field, "runtime_root"))
+ print_hex(id.runtime_root, sizeof(id.runtime_root));
+ else if (!strcmp(field, "nv_writer_public"))
+ print_hex(id.nv_writer_public, sizeof(id.nv_writer_public));
+ else if (!strcmp(field, "nv_index"))
+ printf("%u\n", id.nv_index);
+ else
+ return 2;
+ return 0;
+}
+
static int check_mappings(const char *trusted, const char *outside)
{
long length = sysconf(_SC_PAGESIZE);
@@ -146,6 +188,8 @@ int main(int argc, char **argv)
for (;;)
pause();
}
+ if (!strcmp(argv[1], "identity") && argc == 4)
+ return print_identity(argv[2], argv[3]);
if (!strcmp(argv[1], "mark") && argc == 4)
return check_mark(argv[2], atoi(argv[3]));
if (!strcmp(argv[1], "failed-exec")) {
diff --git a/testing/helper/test-bpf-cmd.c b/testing/helper/test-bpf-cmd.c
index ad0d5aad..10b463a5 100644
--- a/testing/helper/test-bpf-cmd.c
+++ b/testing/helper/test-bpf-cmd.c
@@ -34,6 +34,8 @@ static const struct {
{ "PROG_DETACH", BPF_PROG_DETACH },
{ "PROG_TEST_RUN", BPF_PROG_TEST_RUN },
{ "MAP_GET_NEXT_ID", BPF_MAP_GET_NEXT_ID },
+ { "MAP_GET_FD_BY_ID", BPF_MAP_GET_FD_BY_ID },
+ { "LINK_GET_FD_BY_ID", BPF_LINK_GET_FD_BY_ID },
{ "RAW_TRACEPOINT_OPEN", BPF_RAW_TRACEPOINT_OPEN },
{ "BTF_LOAD", BPF_BTF_LOAD },
{ "MAP_LOOKUP_AND_DELETE_ELEM", BPF_MAP_LOOKUP_AND_DELETE_ELEM },
diff --git a/testing/helper/test-nv-writer.c b/testing/helper/test-nv-writer.c
index 81961a7e..ba33212e 100644
--- a/testing/helper/test-nv-writer.c
+++ b/testing/helper/test-nv-writer.c
@@ -8,34 +8,25 @@
#include <sys/wait.h>
#include <unistd.h>
-#include <bpf/bpf.h>
-
#include "tpm_internal.h"
#include "eventlog.h"
-#include "identity.h"
+#include "hex.h"
#include "paths.h"
-static int public_matches_init(void)
+/* The writer modulus as the identity map holds it, from a trusted reader. */
+static int public_matches_init(const char *hex)
{
- struct bpf_obj_get_opts opts = {
- .sz = sizeof(opts),
- .file_flags = BPF_F_RDONLY,
- };
+ __u8 expected[SHIRUDO_TPM_NV_RSA_BYTES];
struct shirudo_eventlog_init rec;
- struct shirudo_identity id = {};
- __u32 zero = 0;
- int fd, rc;
- fd = bpf_obj_get_opts(SHIRUDO_IDENTITY_PIN, &opts);
- if (fd < 0) {
- perror("open read-only identity");
+ if (strlen(hex) != 2 * sizeof(expected) ||
+ hex_decode(hex, expected, sizeof(expected))) {
+ fprintf(stderr, "writer modulus must be %zu hex digits\n",
+ 2 * sizeof(expected));
return 1;
}
- rc = bpf_map_lookup_elem(fd, &zero, &id);
- close(fd);
- if (rc || eventlog_boot_init(&rec) ||
- memcmp(id.nv_writer_public, rec.writer_public,
- sizeof(id.nv_writer_public))) {
+ if (eventlog_boot_init(&rec) ||
+ memcmp(expected, rec.writer_public, sizeof(expected))) {
fprintf(stderr, "writer modulus differs between identity and init record\n");
return 1;
}
@@ -215,8 +206,8 @@ static int raw_extend_check(const char *device, enum extend_probe probe,
int main(int argc, char **argv)
{
- if (argc == 2 && !strcmp(argv[1], "public"))
- return public_matches_init();
+ if (argc == 3 && !strcmp(argv[1], "public"))
+ return public_matches_init(argv[2]);
if (argc != 3)
return 2;
if (!strcmp(argv[1], "sign-allowed"))
diff --git a/testing/helper/test-upatch-link-lockdown.c b/testing/helper/test-upatch-link-lockdown.c
index 278cfd8a..26483ada 100644
--- a/testing/helper/test-upatch-link-lockdown.c
+++ b/testing/helper/test-upatch-link-lockdown.c
@@ -2,7 +2,8 @@
/*
* Copyright (c) 2026 Authors of shirudo
*
- * Check that an untrusted caller cannot detach or update a pinned upatch link.
+ * Check that an untrusted caller cannot take hold of a pinned upatch link,
+ * by its pin or by its id, to keep it attached or to detach or update it.
*/
#include <errno.h>
@@ -21,32 +22,47 @@ static long sys_bpf(int cmd, union bpf_attr *attr)
int main(int argc, char **argv)
{
+ int pin_errno = 0, id_errno = 0, links = 0;
union bpf_attr attr = {};
- int link_fd;
- int detach_errno, update_errno;
+ __u32 id = 0;
+ long fd;
if (argc != 2) {
- fprintf(stderr, "usage: %s <pinned-link>\\n", argv[0]);
+ fprintf(stderr, "usage: %s <pinned-link>\n", argv[0]);
return 2;
}
attr.pathname = (__u64)(uintptr_t)argv[1];
- link_fd = (int)sys_bpf(BPF_OBJ_GET, &attr);
- if (link_fd < 0) {
- fprintf(stderr, "BPF_OBJ_GET: %s\\n", strerror(errno));
+ fd = sys_bpf(BPF_OBJ_GET, &attr);
+ if (fd >= 0) {
+ close((int)fd);
+ fprintf(stderr, "BPF_OBJ_GET of %s was allowed\n", argv[1]);
return 1;
}
- memset(&attr, 0, sizeof(attr));
- attr.link_detach.link_fd = link_fd;
- if (sys_bpf(BPF_LINK_DETACH, &attr) == 0)
- return 1;
- detach_errno = errno;
- memset(&attr, 0, sizeof(attr));
- attr.link_update.link_fd = link_fd;
- attr.link_update.new_prog_fd = 0x7fffffff;
- if (sys_bpf(BPF_LINK_UPDATE, &attr) == 0)
- return 1;
- update_errno = errno;
- close(link_fd);
- printf("detach_errno=%d update_errno=%d\\n", detach_errno, update_errno);
- return detach_errno == EACCES && update_errno == EACCES ? 0 : 1;
+ pin_errno = errno;
+ for (;;) {
+ memset(&attr, 0, sizeof(attr));
+ attr.start_id = id;
+ if (sys_bpf(BPF_LINK_GET_NEXT_ID, &attr))
+ break;
+ id = attr.next_id;
+ memset(&attr, 0, sizeof(attr));
+ attr.link_id = id;
+ fd = sys_bpf(BPF_LINK_GET_FD_BY_ID, &attr);
+ if (fd >= 0) {
+ close((int)fd);
+ fprintf(stderr, "BPF_LINK_GET_FD_BY_ID %u was allowed\n",
+ id);
+ return 1;
+ }
+ if (id_errno && errno != id_errno) {
+ fprintf(stderr, "link %u: errno=%d after errno=%d\n",
+ id, errno, id_errno);
+ return 1;
+ }
+ id_errno = errno;
+ links++;
+ }
+ printf("pin_errno=%d id_errno=%d links=%d\n", pin_errno, id_errno,
+ links);
+ return pin_errno == EACCES && id_errno == EACCES && links ? 0 : 1;
}
diff --git a/util/tamper.c b/util/tamper.c
index a8e51f96..245c9b3c 100644
--- a/util/tamper.c
+++ b/util/tamper.c
@@ -90,6 +90,8 @@ static const struct {
"kexec image or initramfs load" },
[SHIRUDO_TAMPER_TPM_EXTEND] = { "TpmExtend",
"extension of Shirudo's TPM NV index by another executable" },
+ [SHIRUDO_TAMPER_OBJ_GET] = { "ObjGet",
+ "pin, map or link opened by another executable" },
};
const char *tamper_name(enum shirudo_tamper_point point)