eBPF-based security platform
bpf: restrict test run to shirudo
John Fastabendd811f21ac696
diff --git a/Documentation/architecture.rst b/Documentation/architecture.rstindex 14b53a22..8a63ce45 100644--- a/Documentation/architecture.rst+++ b/Documentation/architecture.rst@@ -217,8 +217,11 @@ bpf() admission. ``lsm/bpf`` sees every ``bpf()`` command with akernel context and false for userspace. Kernel-context calls areallowed; they come from a loader the kernel has already verified.Userspace ``BPF_PROG_LOAD`` is allowed only for ``BPF_PROG_TYPE_SYSCALL``-with a non-zero ``signature_size``, so the only program userspace can-load is a signed loader. Allowed without a signature are the commands+with a non-zero ``signature_size``. Userspace ``BPF_PROG_TEST_RUN`` is+restricted to the executable recorded at ``init``; kernel-context calls+from verified loaders remain allowed. This lets shirudo run loaders and+serializers while preventing root from invoking a serializer to drain+its maps. 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 kernelcontext and is already allowed), map update and freeze only from@@ -227,7 +230,7 @@ shirudo's executable, object pin, link create and raw tracepoint openalready-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+``PROG_QUERY``, ``TASK_FD_QUERY``) that keep``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, includingdiff --git a/Documentation/features.rst b/Documentation/features.rstindex 4198d5f5..43455727 100644--- a/Documentation/features.rst+++ b/Documentation/features.rst@@ -207,9 +207,12 @@ Serializers``shirudo_serialize__<map>`` renders ``<map>`` into the upatch's``shirudo_ser`` output map as a stream of ``structshirudo_serial_chunk`` records, which is how a map of structs or a- per-CPU map becomes a flat record the exporter can ship. ``shirudo+ per-CPU map becomes a flat record the exporter can ship. ``shirudoupatch map`` and the map-export timer run it on the target instead- of reading the map directly. The builder refuses a serializer+ of reading the map directly. The LSM permits userspace+ ``BPF_PROG_TEST_RUN`` only to shirudo's recorded executable,+ preventing root from invoking a pinned serializer directly. The+ builder refuses a serializerwithout the output map, one for a reserved or missing map, and twofor the same map.diff --git a/Documentation/threat-model.rst b/Documentation/threat-model.rstindex fcbe2cb0..6b7c9906 100644--- a/Documentation/threat-model.rst+++ b/Documentation/threat-model.rst@@ -130,9 +130,12 @@ T2 Detaching or replacing enforcementfrozen at creation, so even with the LSM gone userspace could notrewrite the identity map. ``lsm/bpf_map`` denies writable map fdsto 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 records+ same executable gate. Userspace ``BPF_PROG_TEST_RUN`` is restricted+ to shirudo's recorded executable; kernel-context loader calls remain+ allowed. Root therefore cannot invoke a signed+ serializer to drain or clear map state. 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 afterdiff --git a/Makefile.shirudo b/Makefile.shirudoindex e471af5a..54fa8073 100644--- a/Makefile.shirudo+++ b/Makefile.shirudo@@ -499,7 +499,6 @@ TEST_HELPERS := testing/helper/test-json-parser \testing/helper/test-kernel-release \testing/helper/test-kernel-build-id \testing/helper/test-bpf-load \- testing/helper/test-dns-prog-run \testing/helper/test-kernel-abi \testing/helper/test-otel-map \testing/helper/test-upatch-map-types \@@ -573,10 +572,6 @@ testing/helper/test-bpf-load: testing/helper/test-bpf-load.c@printf ' CC $@\n'$(Q)$(CC) $(CFLAGS) -o $@ $^-testing/helper/test-dns-prog-run: testing/helper/test-dns-prog-run.c- @printf ' CC $@\n'- $(Q)$(CC) $(CFLAGS) -o $@ $^-# Needs the vendored uapi bpf.h (excl_prog_hash / fd_array_cnt / keyring_id# are newer than a stock system header) and libcrypto for SHA-256.testing/helper/test-signed-load: testing/helper/test-signed-load.cdiff --git a/bpf/bpf2.c b/bpf/bpf2.cindex 24e80d39..7041ca8f 100644--- a/bpf/bpf2.c+++ b/bpf/bpf2.c@@ -209,6 +209,12 @@ int BPF_PROG(shirudo_lsm_bpf, int cmd, union bpf_attr *attr,return -EACCES;return 0;+ case BPF_PROG_TEST_RUN:+ 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:@@ -216,8 +222,6 @@ int BPF_PROG(shirudo_lsm_bpf, int cmd, union bpf_attr *attr,/** Read-only / observability cmds, so `bpftool prog show`,* `shirudo status`, and `shirudo upatch get/map` keep working.- * BPF_PROG_TEST_RUN is included so shirudo can invoke its own- * signed loaders -- a TEST_RUN cannot introduce unsigned code.* 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.@@ -227,7 +231,6 @@ int BPF_PROG(shirudo_lsm_bpf, int cmd, union bpf_attr *attr,case BPF_MAP_LOOKUP_BATCH:case BPF_OBJ_GET:case BPF_OBJ_GET_INFO_BY_FD:- case BPF_PROG_TEST_RUN:case BPF_PROG_QUERY:case BPF_PROG_GET_NEXT_ID:case BPF_MAP_GET_NEXT_ID:diff --git a/contrib/build-test-vm-bundle.sh b/contrib/build-test-vm-bundle.shindex 49340294..67104c6a 100755--- a/contrib/build-test-vm-bundle.sh+++ b/contrib/build-test-vm-bundle.sh@@ -303,7 +303,6 @@ testing/helper/test-json-parsertesting/helper/test-chaintesting/helper/test-configtesting/helper/test-bpf-load-testing/helper/test-dns-prog-runtesting/helper/test-kernel-abitesting/helper/test-otel-maptesting/helper/test-upatch-map-typesdiff --git a/contrib/test-vm.sh b/contrib/test-vm.shindex 2ade8e35..ff8ebb29 100755--- a/contrib/test-vm.sh+++ b/contrib/test-vm.sh@@ -64,9 +64,6 @@ VM_INITRD="${TEST_VM_INITRD:-0}"VM_INITRD_MODULES="${TEST_VM_INITRD_MODULES:-base systemd systemd-initrd dracut-systemd rootfs-block fs-lib udev-rules terminfo shirudo}"INITRD=""VM_VERBOSE="${VM_VERBOSE:-0}"-DNS_FUZZ="${TEST_VM_DNS_FUZZ:-0}"-DNS_FUZZ_SEED="${TEST_VM_DNS_FUZZ_SEED:-0x53484952}"-DNS_FUZZ_CASES="${TEST_VM_DNS_FUZZ_CASES:-5000}"VM_NAME_REQUEST="${VM_NAME:-}"VM_TENANT="${VM_TENANT:-}"VM_SSH_COMMAND="${VM_SSH_COMMAND:-}"@@ -163,10 +160,6 @@ validate_mode();;*) die "TEST_VM_SUITE must be 'all', 'obs', or 'tree'" ;;esac- case "$DNS_FUZZ" in- 0|1) ;;- *) die "TEST_VM_DNS_FUZZ must be '0' or '1'" ;;- esaccase "$SKIP_SEAL" in0|1) ;;*) die "TEST_VM_SKIP_SEAL must be '0' or '1'" ;;@@ -175,12 +168,6 @@ validate_mode()0|1) ;;*) die "TEST_VM_INITRD must be '0' or '1'" ;;esac- [[ "$DNS_FUZZ_SEED" =~ ^(0[xX][0-9a-fA-F]+|[0-9]+)$ ]] ||- die "TEST_VM_DNS_FUZZ_SEED must be a decimal or hexadecimal integer"- [[ "$DNS_FUZZ_CASES" =~ ^[1-9][0-9]*$ ]] ||- die "TEST_VM_DNS_FUZZ_CASES must be a positive integer"- (( DNS_FUZZ_CASES <= 100000 )) ||- die "TEST_VM_DNS_FUZZ_CASES must be between 1 and 100000"}validate_map_export()@@ -1315,9 +1302,6 @@ printf ' export VM_MODE=%q\n' "$VM_MODE" >>"$USER_DATA"printf ' export TEST_VM_SUITE=%q\n' "$VM_SUITE" >>"$USER_DATA"printf ' export TEST_VM_SKIP_SEAL=%q\n' "$SKIP_SEAL" >>"$USER_DATA"printf ' export TEST_VM_INITRD=%q\n' "$VM_INITRD" >>"$USER_DATA"-printf ' export TEST_VM_DNS_FUZZ=%q\n' "$DNS_FUZZ" >>"$USER_DATA"-printf ' export TEST_VM_DNS_FUZZ_SEED=%q\n' "$DNS_FUZZ_SEED" >>"$USER_DATA"-printf ' export TEST_VM_DNS_FUZZ_CASES=%q\n' "$DNS_FUZZ_CASES" >>"$USER_DATA"printf ' export TEST_VM_SSH_PUBLIC_KEY=%q\n' "$SSH_PUBLIC_KEY" >>"$USER_DATA"if [[ -n "$OCI_CA_DIR" ]]; thenprintf ' export TEST_VM_OCI_CA=/mnt/shirudo-oci/ca.crt\n' >>"$USER_DATA"diff --git a/testing/Makefile b/testing/Makefileindex 0863eae2..37c99a37 100644--- a/testing/Makefile+++ b/testing/Makefile@@ -17,7 +17,7 @@ root-path = $(if $(filter /%,$(1)),$(1),$(ROOT)/$(1)).DEFAULT_GOAL := help.PHONY: help clean test-helpers test-op test test-installer bundle test-vm-bundle kernel \bpf-next vm vm-console vm-ssh vm-stop vm-clean test-tgt test-tgt-obs \- test-tgt-obs-fuzz test-vm test-vm-clean+ test-vm test-vm-cleanKERNEL_PATCHES ?= $(if $(wildcard $(ROOT)/kernel/*.patch),$(ROOT)/kernel/,)override KERNEL_PATCHES := $(if $(strip $(KERNEL_PATCHES)),$(call root-path,$(KERNEL_PATCHES)),)@@ -44,8 +44,6 @@ TEST_VM_MEMORY ?= 4GTEST_VM_DISK_SIZE ?= 30GTEST_VM_UBUNTU_CODENAME ?= resoluteTEST_VM_VERBOSE ?= 0-DNS_OBS_FUZZ_SEED ?= 0x53484952-DNS_OBS_FUZZ_CASES ?= 5000# `make -C testing vm` keeps bpf-next as its default, but can select a stable kernel# built from an upstream Linux tag. The stable list is intentionally explicit# so a typo cannot silently create a new VM kernel artifact directory.@@ -214,7 +212,7 @@ test-tgt: $(VM_KERNEL_DEP) test-vm-bundle$(ROOT)/contrib/test-vm.shtest-tgt-obs: $(VM_KERNEL_DEP) test-vm-bundle- $(Q)VM_MODE=test TEST_VM_SUITE=obs TEST_VM_DNS_FUZZ=0 VM_VERBOSE="$(TEST_VM_VERBOSE)" VM_NAME="$(VM_NAME)" VM_TENANT="$(VM_TENANT)" \+ $(Q)VM_MODE=test TEST_VM_SUITE=obs VM_VERBOSE="$(TEST_VM_VERBOSE)" VM_NAME="$(VM_NAME)" VM_TENANT="$(VM_TENANT)" \TEST_VM_KERNEL="$(abspath $(VM_KERNEL_IMAGE))" \TEST_VM_KERNEL_ARTIFACT_DIR="$(abspath $(VM_KERNEL_ARTIFACT_DIR))" \TEST_VM_WORK_DIR="$(TEST_VM_WORK_DIR)" \@@ -229,26 +227,6 @@ test-tgt-obs: $(VM_KERNEL_DEP) test-vm-bundleTEST_VM_HOST_BUNDLE="$(abspath $(TEST_VM_BUNDLE_DIR))" \$(ROOT)/contrib/test-vm.sh-test-tgt-obs-fuzz: $(VM_KERNEL_DEP) test-vm-bundle- $(Q)VM_MODE=test TEST_VM_SUITE=obs TEST_VM_DNS_FUZZ=1 \- TEST_VM_DNS_FUZZ_SEED="$(DNS_OBS_FUZZ_SEED)" \- TEST_VM_DNS_FUZZ_CASES="$(DNS_OBS_FUZZ_CASES)" \- VM_VERBOSE="$(TEST_VM_VERBOSE)" VM_NAME="$(VM_NAME)" VM_TENANT="$(VM_TENANT)" \- TEST_VM_KERNEL="$(abspath $(VM_KERNEL_IMAGE))" \- TEST_VM_KERNEL_ARTIFACT_DIR="$(abspath $(VM_KERNEL_ARTIFACT_DIR))" \- TEST_VM_WORK_DIR="$(TEST_VM_WORK_DIR)" \- TEST_VM_RUNTIME_CACHE_DIR="$(TEST_VM_RUNTIME_CACHE_DIR)" \- TEST_VM_MAP_EXPORT_ENDPOINT="$(TEST_VM_MAP_EXPORT_ENDPOINT)" \- TEST_VM_MAP_EXPORT_TENANT_ID="$(TEST_VM_MAP_EXPORT_TENANT_ID)" \- TEST_VM_MAP_EXPORT_INSECURE="$(TEST_VM_MAP_EXPORT_INSECURE)" \- TEST_VM_MAP_EXPORT_CA="$(TEST_VM_MAP_EXPORT_CA)" \- TEST_VM_OCI_CA="$(TEST_VM_OCI_CA)" \- TEST_VM_PACKAGE_CERT="$(TEST_VM_PACKAGE_CERT)" \- TEST_VM_BPM_OCI_REPOSITORY="$(TEST_VM_BPM_OCI_REPOSITORY)" \- TEST_VM_BPM_OCI_INDEX_CERT="$(TEST_VM_BPM_OCI_INDEX_CERT)" \- TEST_VM_HOST_BUNDLE="$(abspath $(TEST_VM_BUNDLE_DIR))" \- $(ROOT)/contrib/test-vm.sh-vm-stop:$(Q)VM_NAME="$(VM_NAME)" \TEST_VM_WORK_DIR="$(TEST_VM_WORK_DIR)" $(ROOT)/contrib/test-vm.sh --stop@@ -291,7 +269,7 @@ help:' make -C testing test-op' \' make -C testing test-helpers' \' make -C testing test-tgt [TEST_VM_INITRD=1]' \- ' make -C testing test-tgt-obs or test-tgt-obs-fuzz' \+ ' make -C testing test-tgt-obs' \' make -C testing test-installer' \' make -C testing vm, vm-console, vm-ssh, vm-stop, or vm-clean' \' make -C testing vm KERNEL=6.18' \diff --git a/testing/helper/test-dns-prog-run.c b/testing/helper/test-dns-prog-run.cdeleted file mode 100644index 64dae3f1..00000000--- a/testing/helper/test-dns-prog-run.c+++ /dev/null@@ -1,492 +0,0 @@-// SPDX-License-Identifier: BSD-2-Clause-/*- * Run exact DNS packets through an already-loaded Linux-observability- * cgroup/skb program. The helper intentionally uses only the raw bpf()- * syscall: target VMs do not need libbpf or bpftool at runtime.- *- * Input is a little-endian batch stream:- *- * batch header: u32 magic, u16 version, u16 reserved, u32 records- * each record: u16 frame_len, u8 direction (0=query, 1=response),- * u8 flags, u16 transaction_id, u16 reserved, frame bytes- *- * The frame includes an Ethernet header. BPF_PROG_TEST_RUN strips it before- * invoking a cgroup/skb program, matching the L3 view used on a real cgroup.- * One JSON object is written for every record.- */--#include <errno.h>-#include <inttypes.h>-#include <linux/bpf.h>-#include <stdbool.h>-#include <stdint.h>-#include <stdio.h>-#include <stdlib.h>-#include <string.h>-#include <sys/socket.h>-#include <sys/syscall.h>-#include <unistd.h>--#define DNS_BATCH_MAGIC 0x31534e44u /* "DNS1" little-endian */-#define DNS_BATCH_VERSION 1u-#define DNS_BATCH_MAX_RECORDS 100000u-#define DNS_BATCH_MAX_FRAME 65535u-#define DNS_DEBUG_COUNTERS 41u-#define DNS_NAME_BYTES 256u-#define DNS_ETH_HEADER_BYTES 14u-#define DNS_ETH_P_IP 0x0800u-#define DNS_ETH_P_IPV6 0x86ddu-#define DNS_IPPROTO_UDP 17u--#ifndef SO_NETNS_COOKIE-#define SO_NETNS_COOKIE 71-#endif--enum dns_direction {- DNS_DIRECTION_QUERY = 0,- DNS_DIRECTION_RESPONSE = 1,-};--struct dns_batch_header {- uint32_t magic;- uint16_t version;- uint16_t reserved;- uint32_t records;-} __attribute__((packed));--struct dns_batch_record {- uint16_t frame_len;- uint8_t direction;- uint8_t flags;- uint16_t transaction_id;- uint16_t reserved;-} __attribute__((packed));--struct dns_exec_uid {- uint64_t ino;- uint32_t dev;- uint32_t pad;-};--struct dns_request {- struct dns_exec_uid uid;- uint64_t cgroup;- char name[DNS_NAME_BYTES];- uint16_t qtype;- uint16_t pad;- uint32_t pad2;-};--struct dns_request_key {- uint64_t netns_cookie;- uint32_t client_addr[4];- uint32_t resolver_addr[4];- uint16_t id;- uint16_t client_port;- uint16_t resolver_port;- uint8_t family;- uint8_t pad;-};--_Static_assert(sizeof(struct dns_request_key) == 48,- "DNS request key layout must match the BPF program");--static int sys_bpf(enum bpf_cmd cmd, union bpf_attr *attr)-{- return (int)syscall(__NR_bpf, cmd, attr, sizeof(*attr));-}--static int read_full(void *buffer, size_t size)-{- unsigned char *p = buffer;-- while (size) {- size_t got = fread(p, 1, size, stdin);-- if (got == 0) {- if (ferror(stdin))- return -EIO;- return -ENODATA;- }- p += got;- size -= got;- }- return 0;-}--static bool object_name_equal(const char actual[BPF_OBJ_NAME_LEN],- const char *wanted)-{- char expected[BPF_OBJ_NAME_LEN] = {};-- strncpy(expected, wanted, sizeof(expected) - 1);- return memcmp(actual, expected, sizeof(expected)) == 0;-}--static int find_prog_fd(const char *name)-{- uint32_t id = 0;-- for (;;) {- union bpf_attr next = {};- union bpf_attr get = {};- union bpf_attr info_attr = {};- struct bpf_prog_info info = {};- uint32_t info_len = sizeof(info);- int fd;-- next.start_id = id;- if (sys_bpf(BPF_PROG_GET_NEXT_ID, &next) < 0) {- if (errno == ENOENT)- break;- return -errno;- }- id = next.next_id;- get.prog_id = id;- fd = sys_bpf(BPF_PROG_GET_FD_BY_ID, &get);- if (fd < 0) {- if (errno == ENOENT)- continue;- return -errno;- }- info_attr.info.bpf_fd = fd;- info_attr.info.info_len = info_len;- info_attr.info.info = (uint64_t)(uintptr_t)&info;- if (sys_bpf(BPF_OBJ_GET_INFO_BY_FD, &info_attr) < 0) {- int saved = errno;-- close(fd);- return -saved;- }- if (object_name_equal(info.name, name))- return fd;- close(fd);- }- return -ENOENT;-}--static int find_map_fd(const char *name)-{- uint32_t id = 0;-- for (;;) {- union bpf_attr next = {};- union bpf_attr get = {};- union bpf_attr info_attr = {};- struct bpf_map_info info = {};- uint32_t info_len = sizeof(info);- int fd;-- next.start_id = id;- if (sys_bpf(BPF_MAP_GET_NEXT_ID, &next) < 0) {- if (errno == ENOENT)- break;- return -errno;- }- id = next.next_id;- get.map_id = id;- fd = sys_bpf(BPF_MAP_GET_FD_BY_ID, &get);- if (fd < 0) {- if (errno == ENOENT)- continue;- return -errno;- }- info_attr.info.bpf_fd = fd;- info_attr.info.info_len = info_len;- info_attr.info.info = (uint64_t)(uintptr_t)&info;- if (sys_bpf(BPF_OBJ_GET_INFO_BY_FD, &info_attr) < 0) {- int saved = errno;-- close(fd);- return -saved;- }- if (object_name_equal(info.name, name))- return fd;- close(fd);- }- return -ENOENT;-}--static int map_lookup(int fd, const void *key, void *value)-{- union bpf_attr attr = {};-- attr.map_fd = fd;- attr.key = (uint64_t)(uintptr_t)key;- attr.value = (uint64_t)(uintptr_t)value;- if (sys_bpf(BPF_MAP_LOOKUP_ELEM, &attr) < 0)- return -errno;- return 0;-}--static int validate_request_map(int fd)-{- union bpf_attr attr = {};- struct bpf_map_info info = {};- uint32_t info_len = sizeof(info);-- attr.info.bpf_fd = fd;- attr.info.info_len = info_len;- attr.info.info = (uint64_t)(uintptr_t)&info;- if (sys_bpf(BPF_OBJ_GET_INFO_BY_FD, &attr) < 0)- return -errno;- if (info.key_size != sizeof(struct dns_request_key) ||- info.value_size != sizeof(struct dns_request))- return -EINVAL;- return 0;-}--static uint16_t read_be16(const unsigned char *p)-{- return ((uint16_t)p[0] << 8) | (uint16_t)p[1];-}--static int current_netns_cookie(uint64_t *cookie)-{- socklen_t size = sizeof(*cookie);- int fd, rc = 0;-- fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);- if (fd < 0)- return -errno;- if (getsockopt(fd, SOL_SOCKET, SO_NETNS_COOKIE, cookie, &size) < 0)- rc = -errno;- else if (size != sizeof(*cookie))- rc = -EINVAL;- close(fd);- return rc;-}--static bool request_key_from_frame(const unsigned char *frame, size_t frame_len,- uint8_t direction, uint16_t id,- uint64_t netns_cookie,- struct dns_request_key *key)-{- const unsigned char *ip, *udp;- size_t ip_len;- uint16_t ethertype;-- memset(key, 0, sizeof(*key));- if (frame_len < DNS_ETH_HEADER_BYTES)- return false;- ethertype = read_be16(frame + 12);- ip = frame + DNS_ETH_HEADER_BYTES;- ip_len = frame_len - DNS_ETH_HEADER_BYTES;-- if (ethertype == DNS_ETH_P_IP) {- size_t ihl;-- if (ip_len < 20 || ip[9] != DNS_IPPROTO_UDP)- return false;- ihl = (size_t)(ip[0] & 0x0f) * 4;- if (ihl < 20 || ihl > 60 || ip_len < ihl + 8)- return false;- key->family = AF_INET;- if (direction == DNS_DIRECTION_QUERY) {- memcpy(&key->client_addr[0], ip + 12, 4);- memcpy(&key->resolver_addr[0], ip + 16, 4);- } else {- memcpy(&key->client_addr[0], ip + 16, 4);- memcpy(&key->resolver_addr[0], ip + 12, 4);- }- udp = ip + ihl;- } else if (ethertype == DNS_ETH_P_IPV6) {- if (ip_len < 48 || ip[6] != DNS_IPPROTO_UDP)- return false;- key->family = AF_INET6;- if (direction == DNS_DIRECTION_QUERY) {- memcpy(key->client_addr, ip + 8, 16);- memcpy(key->resolver_addr, ip + 24, 16);- } else {- memcpy(key->client_addr, ip + 24, 16);- memcpy(key->resolver_addr, ip + 8, 16);- }- udp = ip + 40;- } else {- return false;- }-- if (direction == DNS_DIRECTION_QUERY) {- memcpy(&key->client_port, udp, sizeof(key->client_port));- memcpy(&key->resolver_port, udp + 2,- sizeof(key->resolver_port));- } else {- memcpy(&key->client_port, udp + 2,- sizeof(key->client_port));- memcpy(&key->resolver_port, udp,- sizeof(key->resolver_port));- }- key->netns_cookie = netns_cookie;- key->id = id;- return true;-}--static int read_counters(int map_fd, uint64_t values[DNS_DEBUG_COUNTERS])-{- uint32_t i;-- for (i = 0; i < DNS_DEBUG_COUNTERS; i++) {- uint32_t key = i;- int rc;-- rc = map_lookup(map_fd, &key, &values[i]);- if (rc)- return rc;- }- return 0;-}--static int run_packet(int prog_fd, const void *frame, uint32_t frame_len,- uint32_t *retval)-{- union bpf_attr attr = {};-- attr.test.prog_fd = prog_fd;- attr.test.data_size_in = frame_len;- attr.test.data_in = (uint64_t)(uintptr_t)frame;- attr.test.repeat = 1;- if (sys_bpf(BPF_PROG_TEST_RUN, &attr) < 0)- return -errno;- *retval = attr.test.retval;- return 0;-}--static void print_name_hex(const char name[DNS_NAME_BYTES])-{- uint32_t i;-- for (i = 0; i < DNS_NAME_BYTES && name[i]; i++)- printf("%02x", (unsigned char)name[i]);-}--static void print_result(uint32_t index, int rc, uint32_t retval,- int request_rc, const struct dns_request *request,- const uint64_t before[DNS_DEBUG_COUNTERS],- const uint64_t after[DNS_DEBUG_COUNTERS])-{- uint32_t i;-- printf("{\"index\":%u,\"rc\":%d,\"retval\":%u,", index, rc,- retval);- if (request_rc == 0) {- printf("\"request\":true,\"request_qtype\":%u,"- "\"request_name_hex\":\"", request->qtype);- print_name_hex(request->name);- printf("\",");- } else {- printf("\"request\":false,\"request_qtype\":0,"- "\"request_name_hex\":\"\",");- }- printf("\"counter_delta\":[");- for (i = 0; i < DNS_DEBUG_COUNTERS; i++) {- if (i)- putchar(',');- printf("%" PRIu64, after[i] - before[i]);- }- printf("]}\n");-}--int main(void)-{- struct dns_batch_header header;- uint64_t before[DNS_DEBUG_COUNTERS], after[DNS_DEBUG_COUNTERS];- int query_fd = -1, response_fd = -1, debug_fd = -1, request_fd = -1;- unsigned char *frame = NULL;- uint64_t netns_cookie;- uint32_t i;- int rc = 1;-- if (read_full(&header, sizeof(header))) {- fprintf(stderr, "dns batch: short header\n");- return 1;- }- if (header.magic != DNS_BATCH_MAGIC ||- header.version != DNS_BATCH_VERSION || header.reserved != 0 ||- header.records > DNS_BATCH_MAX_RECORDS) {- fprintf(stderr, "dns batch: invalid header\n");- return 1;- }-- query_fd = find_prog_fd("track_dns_query");- response_fd = find_prog_fd("track_dns_respo");- debug_fd = find_map_fd("obs_i_dns_dbg");- request_fd = find_map_fd("obs_i_dns_req");- if (query_fd < 0 || response_fd < 0 || debug_fd < 0 || request_fd < 0) {- fprintf(stderr,- "dns batch: required objects unavailable: query=%d response=%d debug=%d request=%d\n",- query_fd, response_fd, debug_fd, request_fd);- goto out;- }- if (validate_request_map(request_fd)) {- fprintf(stderr, "dns batch: request map layout does not match helper\n");- goto out;- }- if (current_netns_cookie(&netns_cookie)) {- fprintf(stderr, "dns batch: cannot read network namespace cookie\n");- goto out;- }-- frame = malloc(DNS_BATCH_MAX_FRAME);- if (!frame) {- fprintf(stderr, "dns batch: out of memory\n");- goto out;- }-- for (i = 0; i < header.records; i++) {- struct dns_batch_record record;- struct dns_request_key key;- struct dns_request request = {};- uint32_t retval = 0;- int run_rc, request_rc;-- if (read_full(&record, sizeof(record)) ||- record.direction > DNS_DIRECTION_RESPONSE || record.flags != 0 ||- record.reserved != 0 ||- read_full(frame, record.frame_len)) {- fprintf(stderr, "dns batch: invalid record %u\n", i);- goto out;- }- if (read_counters(debug_fd, before)) {- fprintf(stderr, "dns batch: cannot read counters before record %u\n", i);- goto out;- }- run_rc = run_packet(record.direction == DNS_DIRECTION_QUERY ?- query_fd : response_fd,- frame, record.frame_len, &retval);- if (read_counters(debug_fd, after)) {- fprintf(stderr, "dns batch: cannot read counters after record %u\n", i);- goto out;- }- if (request_key_from_frame(frame, record.frame_len,- record.direction,- record.transaction_id,- netns_cookie, &key))- request_rc = map_lookup(request_fd, &key, &request);- else- request_rc = -ENOENT;- if (request_rc != 0 && request_rc != -ENOENT) {- fprintf(stderr, "dns batch: request lookup failed for record %u: %d\n",- i, request_rc);- goto out;- }- print_result(i, run_rc, retval, request_rc, &request,- before, after);- }-- if (fgetc(stdin) != EOF) {- fprintf(stderr, "dns batch: trailing input\n");- goto out;- }- rc = 0;-out:- free(frame);- if (query_fd >= 0)- close(query_fd);- if (response_fd >= 0)- close(response_fd);- if (debug_fd >= 0)- close(debug_fd);- if (request_fd >= 0)- close(request_fd);- return rc;-}diff --git a/testing/kernel-obs/dns_obs_matrix.py b/testing/kernel-obs/dns_obs_matrix.pyindex a298491a..f5ab82ca 100755--- a/testing/kernel-obs/dns_obs_matrix.py+++ b/testing/kernel-obs/dns_obs_matrix.py@@ -1,18 +1,14 @@#!/usr/bin/env python3# SPDX-License-Identifier: BSD-2-Clause-"""Exercise the loaded Linux-observability DNS programs with exact frames."""+"""Validate the DNS packet-case builders and batch encoding."""from __future__ import annotationsimport argparseimport ipaddress-import json-import randomimport struct-import subprocessimport sysfrom dataclasses import dataclass, field-from pathlib import Pathfrom typing import Callable@@ -91,8 +87,6 @@ class Case:request: bool | None = Falserequest_name: str | None = Nonerequest_qtype: int | None = None- run_rc: int = 0- retval: int = 1def wire_name(name: str | list[bytes]) -> bytes:@@ -299,12 +293,12 @@ def add_transport_cases(matrix: Matrix) -> None:txid = matrix.txid()matrix.add(Case("transport: truncated IPv4 header", QUERY, txid,ethernet(b"\x45" + b"\x00" * 18),- {}, False, run_rc=-22, retval=0))+ {}, False))txid = matrix.txid()matrix.add(Case("transport: truncated IPv6 header", RESPONSE, txid,ethernet(b"\x60" + b"\x00" * 38, 0x86DD),- {}, False, run_rc=-22, retval=0))+ {}, False))txid = matrix.txid()payload = query_payload(txid, wire_name("options.example"))@@ -722,126 +716,6 @@ def encode_batch(cases: list[Case]) -> bytes:return bytes(output)-def invoke_runner(runner: Path, cases: list[Case], artifact: Path | None = None) -> list[dict]:- batch = encode_batch(cases)- if artifact is not None:- artifact.write_bytes(batch)- process = subprocess.run([str(runner)], input=batch, stdout=subprocess.PIPE,- stderr=subprocess.PIPE, check=False)- if process.returncode:- raise RuntimeError(- f"runner exited {process.returncode}: " +- process.stderr.decode("utf-8", "replace").strip())- try:- results = [json.loads(line) for line in process.stdout.splitlines()]- except json.JSONDecodeError as error:- raise RuntimeError(f"invalid runner JSON: {error}") from error- if len(results) != len(cases):- raise RuntimeError(f"runner returned {len(results)} results for {len(cases)} cases")- return results---def assert_results(cases: list[Case], results: list[dict]) -> set[str]:- hit: set[str] = set()- failures: list[str] = []- for index, (case, result) in enumerate(zip(cases, results)):- prefix = f"case {index} ({case.name})"- if result.get("index") != index:- failures.append(f"{prefix}: result index is {result.get('index')!r}")- if (result.get("rc") != case.run_rc or- result.get("retval") != case.retval):- failures.append(- f"{prefix}: BPF_PROG_TEST_RUN rc={result.get('rc')} "- f"retval={result.get('retval')}, expected rc={case.run_rc} "- f"retval={case.retval}")- delta = result.get("counter_delta")- if not isinstance(delta, list) or len(delta) != len(COUNTERS):- failures.append(f"{prefix}: malformed counter delta")- continue- hit.update(COUNTERS[i] for i, value in enumerate(delta) if value)- for name, expected in case.counters.items():- actual = delta[COUNTER[name]]- if actual != expected:- failures.append(f"{prefix}: {name}={actual}, expected {expected}")- if case.request is not None and result.get("request") is not case.request:- failures.append(- f"{prefix}: request={result.get('request')!r}, expected {case.request}")- if case.request_name is not None:- actual_name = bytes.fromhex(result.get("request_name_hex", "")).decode(- "ascii", "backslashreplace")- if actual_name != case.request_name:- failures.append(- f"{prefix}: request name {actual_name!r}, expected {case.request_name!r}")- if case.request_qtype is not None and result.get("request_qtype") != case.request_qtype:- failures.append(- f"{prefix}: qtype={result.get('request_qtype')}, expected {case.request_qtype}")- if failures:- raise AssertionError("\n".join(failures))- return hit---def export_dns(shirudo: Path, upatch: str, output: Path) -> dict:- process = subprocess.run(- [str(shirudo), "upatch", "map", upatch, "dns",- f"--json={output}"], stdout=subprocess.PIPE, stderr=subprocess.PIPE,- check=False, text=True)- if process.returncode:- raise RuntimeError(- f"DNS export exited {process.returncode}: {process.stderr.strip()}")- records = [json.loads(line) for line in output.read_text(encoding="utf-8").splitlines()]- if len(records) != 1 or records[0].get("map") != "dns":- raise AssertionError(f"unexpected DNS export: {records!r}")- return records[0]---def names_by_address(export: dict) -> dict[str, dict[str, int]]:- output: dict[str, dict[str, int]] = {}- for record in export.get("records", []):- output.setdefault(record["address"], {}).update(- {item["name"]: int(item["seen_count"]) for item in record["names"]})- return output---def assert_export(export: dict) -> None:- addresses = names_by_address(export)- required = {- "192.0.2.10": {"basic.example": 1},- "2001:0db8:0000:0000:0000:0000:0000:0010": {"v6.example": 1},- "192.0.2.11": {".".join(["a"] * 127): 1},- "192.0.2.20": {"duplicate.example": 2},- "192.0.2.21": {f"name{i}.example": 1 for i in range(2, 6)},- "192.0.2.30": {"multi-address.example": 1},- "192.0.2.31": {"multi-address.example": 1},- "203.0.113.75": {"slot75.example": 1},- "198.51.100.200": {"flow-port-first.example": 1},- "198.51.100.201": {"flow-port-second.example": 1},- "198.51.100.202": {"flow-address-first.example": 1},- "198.51.100.203": {"flow-address-second.example": 1},- "198.51.100.204": {"flow-family-v4.example": 1},- "198.51.100.205": {"flow-family-v6.example": 1},- "198.51.100.207": {"flow-wrong-tuple.example": 1},- }- failures: list[str] = []- for address, expected_names in required.items():- actual_names = addresses.get(address)- if actual_names is None:- failures.append(f"missing exported address {address}")- continue- for name, seen_count in expected_names.items():- if actual_names.get(name) != seen_count:- failures.append(- f"{address} name {name!r}: seen_count={actual_names.get(name)}, "- f"expected {seen_count}")- if "name1.example" in addresses.get("192.0.2.21", {}):- failures.append("oldest fifth-name slot was not evicted")- if "203.0.113.76" in addresses:- failures.append("answer 76 was parsed despite the 75-answer cap")- if "198.51.100.254" in addresses:- failures.append("wrong-tuple response unexpectedly produced an event")- if failures:- raise AssertionError("\n".join(failures))--def build_known_gap_matrix() -> tuple[list[Case], list[tuple[str, Callable[[dict], bool]]]]:matrix = Matrix(0x7000)probes: list[tuple[str, Callable[[dict], bool]]] = []@@ -956,151 +830,19 @@ def validate_matrix(cases: list[Case]) -> None:raise AssertionError("batch has trailing bytes")-def run_deterministic(args: argparse.Namespace, work: Path) -> None:- matrix = build_deterministic_matrix()- validate_matrix(matrix.cases)- results = invoke_runner(args.runner, matrix.cases, work / "dns-matrix.batch")- hit = assert_results(matrix.cases, results)- (work / "dns-matrix-results.ndjson").write_text(- "".join(json.dumps(item, sort_keys=True) + "\n" for item in results),- encoding="utf-8")-- required = set(COUNTERS) - NON_PACKET_COUNTERS- missing = sorted(required - hit)- if missing:- raise AssertionError("packet-controlled debug counters not covered: " +- ", ".join(missing))-- first_export = export_dns(args.shirudo, args.upatch,- work / "dns-matrix-export.ndjson")- assert_export(first_export)- second_export = export_dns(args.shirudo, args.upatch,- work / "dns-matrix-export-empty.ndjson")- if second_export.get("records"):- raise AssertionError("DNS serializer did not clear pending records")-- print(f"PASS deterministic: {len(matrix.cases)} exact packets, "- f"{len(hit)} debug branches, serializer output and clear-on-export")-- if args.known_gaps:- known_cases, probes = build_known_gap_matrix()- known_results = invoke_runner(args.runner, known_cases,- work / "dns-known-gaps.batch")- # Known gaps do not carry semantic assertions, but syscall execution- # and the runner protocol remain gating.- assert_results(known_cases, known_results)- report: list[str] = []- for label, predicate in probes:- status = "XFAIL known-gap" if predicate(known_results) else "RESOLVED"- report.append(f"{status}: {label}")- report.extend([- "LIMITATION: IPv6 extension headers are not walked",- "LIMITATION: response question class is read but not compared",- "LIMITATION: answer type is not constrained by the requested type",- "LIMITATION: IP/UDP checksums are not validated",- ])- text = "\n".join(report) + "\n"- (work / "dns-known-gaps.log").write_text(text, encoding="utf-8")- print(text, end="")---def mutate_packet(rng: random.Random, corpus: list[bytes]) -> bytes:- packet = bytearray(rng.choice(corpus))- operation = rng.randrange(6)- if operation == 0 and packet:- del packet[rng.randrange(len(packet)):]- elif operation == 1 and packet:- for _ in range(rng.randint(1, min(16, len(packet)))):- index = rng.randrange(len(packet))- packet[index] ^= 1 << rng.randrange(8)- elif operation == 2:- at = rng.randrange(len(packet) + 1)- packet[at:at] = rng.randbytes(rng.randint(1, 32))- elif operation == 3 and len(packet) > 14:- start = rng.randrange(14, len(packet))- end = min(len(packet), start + rng.randint(1, 32))- del packet[start:end]- elif operation == 4:- packet.extend(rng.randbytes(rng.randint(0, 512)))- elif len(packet) >= 14:- packet[12:14] = rng.choice((b"\x08\x00", b"\x86\xdd", b"\x88\xb5"))- return bytes(packet[:65535])---def assert_fuzz_results(cases: list[Case], results: list[dict]) -> None:- failures: list[str] = []- for index, (case, result) in enumerate(zip(cases, results)):- if result.get("index") != index:- failures.append(- f"case {index}: result index is {result.get('index')!r}")- outcome = (result.get("rc"), result.get("retval"))- # The skb test harness rejects frames that no longer satisfy its- # minimum L2/L3 shape before invoking BPF. That is a valid fuzz- # outcome; anything besides success or EINVAL is not.- if outcome not in ((0, 1), (-22, 0)):- failures.append(- f"case {index} ({case.name}): unexpected rc/retval {outcome}")- delta = result.get("counter_delta")- if not isinstance(delta, list) or len(delta) != len(COUNTERS):- failures.append(f"case {index} ({case.name}): malformed counter delta")- if len(failures) >= 20:- break- if failures:- raise AssertionError("\n".join(failures))---def run_fuzz(args: argparse.Namespace, work: Path) -> None:- rng = random.Random(args.seed)- deterministic = build_deterministic_matrix().cases- corpus = [case.frame for case in deterministic]- cases: list[Case] = []- for index in range(args.cases):- direction = rng.randrange(2)- cases.append(Case(f"fuzz-{index}", direction, rng.randrange(0x10000),- mutate_packet(rng, corpus), request=None))- validate_matrix(cases)- results = invoke_runner(args.runner, cases, work / "dns-fuzz.batch")- assert_fuzz_results(cases, results)- (work / "dns-fuzz-results.ndjson").write_text(- "".join(json.dumps(item, sort_keys=True) + "\n" for item in results),- encoding="utf-8")- print(f"PASS fuzz: seed={args.seed:#x}, cases={args.cases}")---def parse_int(value: str) -> int:- return int(value, 0)--def main() -> int:parser = argparse.ArgumentParser()- parser.add_argument("--runner", type=Path, default=Path("helper/test-dns-prog-run"))- parser.add_argument("--shirudo", type=Path, default=Path("/usr/local/bin/shirudo"))- parser.add_argument("--upatch", default="kernel-obs")- parser.add_argument("--work", type=Path, default=Path("."))parser.add_argument("--self-test", action="store_true")- parser.add_argument("--deterministic", action="store_true")- parser.add_argument("--known-gaps", action="store_true")- parser.add_argument("--fuzz", action="store_true")- parser.add_argument("--seed", type=parse_int, default=0x53484952)- parser.add_argument("--cases", type=int, default=5000)args = parser.parse_args()+ if not args.self_test:+ parser.error("select --self-test")- if args.cases < 1 or args.cases > 100000:- parser.error("--cases must be between 1 and 100000")- args.work.mkdir(parents=True, exist_ok=True)matrix = build_deterministic_matrix()validate_matrix(matrix.cases)- if args.self_test:- known_cases, _ = build_known_gap_matrix()- validate_matrix(known_cases)- print(f"PASS matrix self-test: {len(matrix.cases)} deterministic packets, "- f"{len(known_cases)} known-gap packets")- if args.deterministic:- run_deterministic(args, args.work)- if args.fuzz:- run_fuzz(args, args.work)- if not (args.self_test or args.deterministic or args.fuzz):- parser.error("select --self-test, --deterministic, or --fuzz")+ known_cases, _ = build_known_gap_matrix()+ validate_matrix(known_cases)+ print(f"PASS matrix self-test: {len(matrix.cases)} deterministic packets, "+ f"{len(known_cases)} known-gap packets")return 0diff --git a/testing/kernel-obs/t0019-dns-observability-matrix.sh b/testing/kernel-obs/t0019-dns-observability-matrix.shindex aef27577..863ebd0e 100755--- a/testing/kernel-obs/t0019-dns-observability-matrix.sh+++ b/testing/kernel-obs/t0019-dns-observability-matrix.sh@@ -7,7 +7,7 @@ cd "$(dirname "$0")/.."command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"-test_expect_success 'DNS observability packet matrix and batch ABI are valid' '+test_expect_success 'DNS packet-case builders and batch encoding are valid' 'python3 kernel-obs/dns_obs_matrix.py --self-test'diff --git a/testing/kernel-obs/t1211-kernel-obs-dns-matrix.sh b/testing/kernel-obs/t1211-kernel-obs-dns-matrix.shindex 28db5f03..21783b43 100755--- a/testing/kernel-obs/t1211-kernel-obs-dns-matrix.sh+++ b/testing/kernel-obs/t1211-kernel-obs-dns-matrix.sh@@ -12,7 +12,6 @@ NAME=kernel-obsLOAD="$FIXTURES/$NAME.upatch"UNLOAD="$FIXTURES/$NAME.unload.upatch"PIN="/run/shirudo/bpffs/upatches/$NAME/link_0"-RUNNER=./helper/test-dns-prog-runWORK=$(mktemp -d)cleanup()@@ -26,63 +25,42 @@ cleanup()}trap cleanup EXIT-save_failure()-{- cat "$WORK/matrix.log" >&2 2>/dev/null || true- if [ -d /mnt/shirudo-out ]; then- mkdir -p /mnt/shirudo-out/dns-matrix- cp -a "$WORK/." /mnt/shirudo-out/dns-matrix/- fi- return 1-}--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/dns-matrix-load.log- fi- return 1-}-[ -s "$LOAD" ] || test_skip_all "missing kernel-obs fixture"[ -s "$UNLOAD" ] || test_skip_all "missing kernel-obs unload fixture"-test_expect_success 'DNS matrix helper and generator are available' '- [ -x "$RUNNER" ] &&- python3 kernel-obs/dns_obs_matrix.py --self-test >"$WORK/self-test.log" 2>&1-'+cat >"$WORK/check.py" <<'PYTHON'+import json+import sys-test_expect_success 'kernel-obs DNS programs load for packet tests' '- load_observability &&- [ -e "/run/shirudo/bpffs/upatches/$NAME/serializers/dns" ]-'+records = [json.loads(line) for line in open(sys.argv[1], encoding="utf-8")]+assert len(records) == 1 and records[0].get("map") == "dns", records+addresses = {item["address"]: item for item in records[0].get("records", [])}+for address, name in (("203.0.113.10", ".".join(["a"] * 127)),+ ("203.0.113.75", "many.example")):+ record = addresses.get(address)+ assert record is not None, records+ assert any(item["name"] == name for item in record["names"]), record+assert records[0]["interval"]["overflow"] == 0, records+assert records[0]["interval"]["lost"] == 0, records+PYTHON-test_expect_success 'DNS UDP deterministic packet matrix passes' '- python3 kernel-obs/dns_obs_matrix.py --deterministic --known-gaps \- --runner "$RUNNER" --shirudo "$SHIRUDO_BIN" --upatch "$NAME" \- --work "$WORK" >"$WORK/matrix.log" 2>&1 || save_failure-'+cat >"$WORK/check-empty.py" <<'PYTHON'+import json+import sys-if [ -s "$WORK/matrix.log" ]; then- sed 's/^/# dns-matrix: /' "$WORK/matrix.log"-fi+records = [json.loads(line) for line in open(sys.argv[1], encoding="utf-8")]+assert len(records) == 1 and records[0].get("map") == "dns", records+assert records[0].get("records") == [], records+PYTHON-if [ "${TEST_VM_DNS_FUZZ:-0}" = 1 ]; then- test_expect_success 'DNS UDP seeded mutation fuzz run passes' '- python3 kernel-obs/dns_obs_matrix.py --fuzz \- --runner "$RUNNER" --work "$WORK" \- --seed "${TEST_VM_DNS_FUZZ_SEED:-0x53484952}" \- --cases "${TEST_VM_DNS_FUZZ_CASES:-5000}" \- >"$WORK/fuzz.log" 2>&1 || save_failure- '- if [ -s "$WORK/fuzz.log" ]; then- sed 's/^/# dns-fuzz: /' "$WORK/fuzz.log"- fi-fi+test_expect_success 'DNS observations use real loopback UDP traffic' '+ "$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck >/dev/null 2>&1 &&+ python3 kernel-obs/kernel_obs_events.py dns-long &&+ python3 kernel-obs/kernel_obs_events.py dns-many &&+ "$SHIRUDO_BIN" upatch map "$NAME" dns --json="$WORK/dns.ndjson" >/dev/null &&+ python3 "$WORK/check.py" "$WORK/dns.ndjson" &&+ "$SHIRUDO_BIN" upatch map "$NAME" dns --json="$WORK/dns-empty.ndjson" >/dev/null &&+ python3 "$WORK/check-empty.py" "$WORK/dns-empty.ndjson"+'test_donediff --git a/testing/tamperproof/t1130-map-lockdown.sh b/testing/tamperproof/t1130-map-lockdown.shindex 69bd7ec5..270303ee 100644--- a/testing/tamperproof/t1130-map-lockdown.sh+++ b/testing/tamperproof/t1130-map-lockdown.sh@@ -36,11 +36,14 @@ trap cleanup EXIT HUP INT TERMcat >"$WORK/check.py" <<'PYTHON'import ctypesimport errno+import jsonimport osimport platform+import subprocessimport sysBPF_MAP_UPDATE_ELEM = 2+BPF_PROG_TEST_RUN = 10BPF_MAP_FREEZE = 22BPF_MAP_GET_FD_BY_ID = 14BPF_OBJ_GET = 7@@ -100,6 +103,35 @@ class MapElemAttr(ctypes.Structure):("flags", ctypes.c_uint64)]+class SerializerCtx(ctypes.Structure):+ _fields_ = [("magic", ctypes.c_uint32),+ ("version", ctypes.c_uint32),+ ("flags", ctypes.c_uint32),+ ("max_chunks", ctypes.c_uint32),+ ("chunk_payload_size", ctypes.c_uint32),+ ("page_index", ctypes.c_uint32),+ ("cursor", ctypes.c_uint64),+ ("invocation_id", ctypes.c_uint64)]+++class ProgTestRunAttr(ctypes.Structure):+ _fields_ = [("prog_fd", ctypes.c_uint32),+ ("retval", ctypes.c_uint32),+ ("data_size_in", ctypes.c_uint32),+ ("data_size_out", ctypes.c_uint32),+ ("data_in", ctypes.c_uint64),+ ("data_out", ctypes.c_uint64),+ ("repeat", ctypes.c_uint32),+ ("duration", ctypes.c_uint32),+ ("ctx_size_in", ctypes.c_uint32),+ ("ctx_size_out", ctypes.c_uint32),+ ("ctx_in", ctypes.c_uint64),+ ("ctx_out", ctypes.c_uint64),+ ("flags", ctypes.c_uint32),+ ("cpu", ctypes.c_uint32),+ ("batch_size", ctypes.c_uint32)]++def bpf(cmd, attr):ctypes.set_errno(0)result = libc.syscall(BPF_SYSCALL, cmd, ctypes.byref(attr),@@ -184,12 +216,42 @@ for map_name in ("shirudo_ser", "obs_i_arena"):finally:os.close(readonly_fd)-print("direct root BPF map mutation denied")+serializer_path = os.path.join(os.path.dirname(sys.argv[1]),+ "serializers/exec")+serializer_fd, error = obj_get(serializer_path, 0)+if serializer_fd < 0:+ raise AssertionError(f"exec serializer fd: errno={error}")+try:+ ctx = SerializerCtx(0x5A4C5253, 3, 0, 1, 4032, 0, 0, 1)+ attr = ProgTestRunAttr(serializer_fd, 0, 0, 0, 0, 0, 1, 0,+ ctypes.sizeof(ctx), 0,+ ctypes.addressof(ctx), 0, 0, 0, 0)+ result, error = bpf(BPF_PROG_TEST_RUN, attr)+ if result == 0 or error != errno.EACCES:+ raise AssertionError(+ f"serializer BPF_PROG_TEST_RUN: result={result}, errno={error}; "+ "expected LSM EACCES")+finally:+ os.close(serializer_fd)++output = os.path.join(sys.argv[3], "exec-after-test-run.ndjson")+subprocess.run([sys.argv[2], "upatch", "map", "kernel-obs", "exec",+ f"--json={output}"], check=True, stdout=subprocess.DEVNULL)+documents = [json.loads(line) for line in open(output, encoding="utf-8")]+records = [record for document in documents+ if isinstance(document, dict) and document.get("map") == "exec"+ for record in document.get("records", [])]+python_exe = os.path.realpath(sys.executable)+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")PYTHON-test_expect_success 'root direct BPF map mutation is denied' '+test_expect_success 'root map mutation and serializer test-run are denied' '"$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck >/dev/null 2>&1 &&- python3 "$WORK/check.py" "$MAPS"+ python3 "$WORK/check.py" "$MAPS" "$SHIRUDO_BIN" "$WORK"'test_donediff --git a/testing/tamperproof/test.plan.md b/testing/tamperproof/test.plan.mdindex 49e2013b..643e2fcb 100644--- a/testing/tamperproof/test.plan.md+++ b/testing/tamperproof/test.plan.md@@ -7,20 +7,14 @@ this review.## Priority finding-**Open bypass: a root caller can invoke a pinned serializer with-`BPF_PROG_TEST_RUN`.** The Shirudo BPF LSM allows `BPF_PROG_TEST_RUN`,-`BPF_OBJ_GET`, and `BPF_PROG_GET_FD_BY_ID` to all callers. Kernel-obs-serializers are pinned signed syscall programs. A non-PEEK serializer context-can flip the arena buffers and clear drained state, so a root caller can cause-observation records to be drained or cleared without acquiring a writable map-FD. This is a state-integrity/availability bypass through signed code, not-unsigned code loading or arbitrary map writes.--Restrict `BPF_PROG_TEST_RUN` to Shirudo's recorded executable, then add a-negative root test that attempts a destructive serializer run and confirms-the records remain. Keep a positive control proving Shirudo's own export still-works. Relevant implementation: `bpf/bpf2.c`,-`upatches/kernel-obs/obs_table.h`, and `util/upatch_maps.c`.+**Resolved bypass: root could invoke a pinned serializer with+`BPF_PROG_TEST_RUN`.** Kernel-obs serializers are pinned signed syscall+programs. A non-PEEK serializer context can flip arena buffers and clear+drained state, allowing a root caller to drain observations without a+writable map FD. The LSM now restricts userspace `BPF_PROG_TEST_RUN` to+Shirudo's recorded executable; verified kernel-context loader calls remain+allowed. `t1130-map-lockdown.sh` asserts the denial and then+checks that Shirudo can still export the pre-existing Python exec record.## Coverage matrix@@ -39,7 +33,7 @@ works. Relevant implementation: `bpf/bpf2.c`,| TP-11 | Read-only map FD access as a positive control | Covered | `t1130-map-lockdown.sh` | Preserve both path and map-ID read-only checks. || TP-12 | Update serializer map or freeze serializer/arena map directly | Covered | `t1130-map-lockdown.sh` | Current test attempts update on serializer array and freeze on both. || TP-13 | Writable mmap of arena | Covered | `t1130-map-lockdown.sh` | Preserve denial check. |-| TP-14 | Invoke pinned serializer with destructive `BPF_PROG_TEST_RUN` context | **Open bypass** | None | After policy fix, root invocation must be denied and accumulated records must remain; Shirudo export must still succeed. |+| TP-14 | Invoke pinned serializer with destructive `BPF_PROG_TEST_RUN` context | Covered | `t1130-map-lockdown.sh` | Root receives `EACCES`; Shirudo export still succeeds and contains the Python exec record created before the attempt. || TP-15 | Delete map element; update/delete batch; lookup-and-delete variants | Not covered | None | Add raw-syscall denial cases for each applicable command. Policy default-denies them, but that behavior is not asserted. || TP-16 | Create a BPF map from a non-Shirudo executable | Not covered | None in tamperproof | Add direct negative test for `BPF_MAP_CREATE`; cover authorized Shirudo loader creation as positive control. || TP-17 | Create links or pin existing objects from root | Not covered | None | `BPF_LINK_CREATE` and `BPF_OBJ_PIN` are allowed. Test whether root can create an unwanted attachment or pin and whether the resulting object affects enforcement/state. |diff --git a/upatches/kernel-obs/dns.todo b/upatches/kernel-obs/dns.todoindex 8d1509c2..e2ea9552 100644--- a/upatches/kernel-obs/dns.todo+++ b/upatches/kernel-obs/dns.todo@@ -4,9 +4,12 @@ The UDP DNS parser correlates requests with a canonical key made fromthe network-namespace cookie, address family, client/resolver addressesand ports, and transaction ID, and attributes the answer to the queryingsocket's owner. The items below are the remaining parser and-correlation gaps. Each behavior change should promote its corresponding-case in `testing/kernel-obs/dns_obs_matrix.py` from a known-gap probe to a gating-test.+correlation gaps. `testing/kernel-obs/dns_obs_matrix.py` now validates+case construction and batch encoding only. Its former target runner used+`BPF_PROG_TEST_RUN`, which is restricted to Shirudo. The target suite uses+live loopback UDP exchanges for representative query and response+coverage. Exact malformed-packet and mutation-fuzz coverage needs a live+packet harness before it can gate target changes.## Matching and response integrity@@ -38,8 +41,9 @@ test.- [ ] Walk supported IPv6 extension headers or reject packets containing anyextension header with a dedicated debug counter.- [ ] Validate the IP version against the Ethernet protocol.-- [ ] Decide whether checksum validation belongs in this program. The packet- matrix currently demonstrates that invalid IP/UDP checksums are accepted.+- [ ] Decide whether checksum validation belongs in this program. The case+ builder includes invalid-checksum inputs, but target tests do not currently+ inject those malformed packets over a live network path.## Name and answer parsing