eBPF-based security platform
testing: cover kernel-obs socket families
John Fastabend9b37b34300da
diff --git a/testing/run-target-obs-tests.sh b/testing/run-target-obs-tests.shindex 31593fad..851d5bfa 100755--- a/testing/run-target-obs-tests.sh+++ b/testing/run-target-obs-tests.sh@@ -10,6 +10,7 @@ fail=0: "${SHIRUDO_TEST_SUITE_FAILURES_FILE:=}"for test_script in \upatch/kernel-obs/network/t1210-kernel-obs.sh \+ upatch/kernel-obs/network/kernel-obs-net.sh \upatch/kernel-obs/priv/kernel-obs-priv.sh \upatch/kernel-obs/dns/t1211-kernel-obs-dns-matrix.shdodiff --git a/testing/upatch/kernel-obs/network/kernel-obs-net.sh b/testing/upatch/kernel-obs/network/kernel-obs-net.shnew file mode 100755index 00000000..30ee4352--- /dev/null+++ b/testing/upatch/kernel-obs/network/kernel-obs-net.sh@@ -0,0 +1,114 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++cd "$(dirname "$0")/../../.."+. ./integration-lib.sh+target_guard+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"++FIXTURES=${SHIRUDO_TEST_FIXTURES_DIR:?target fixture directory is not set}+NAME=kernel-obs+LOAD="$FIXTURES/$NAME.upatch"+UNLOAD="$FIXTURES/$NAME.unload.upatch"+PIN="/run/shirudo/bpffs/upatches/$NAME/link_0"+WORK=$(mktemp -d)++cleanup()+{+ if [ -e "$PIN" ] || [ -e "/run/shirudo/bpffs/upatches/$NAME/link" ]; then+ "$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck \+ >/dev/null 2>&1 || true+ fi+ rm -f "/var/lib/shirudo/upatches/$NAME.upatch"+ rm -rf "$WORK"+}+trap cleanup EXIT++[ -s "$LOAD" ] || test_skip_all "missing kernel-obs fixture"+[ -s "$UNLOAD" ] || test_skip_all "missing kernel-obs unload fixture"++export_net_maps()+{+ for map in net socket; do+ "$SHIRUDO_BIN" upatch map "$NAME" "$map" \+ --json="$WORK/events.ndjson" >/dev/null+ done+}++cat >"$WORK/check.py" <<'PYTHON'+import json+import sys++expected = json.load(open(sys.argv[1], encoding="utf-8"))+documents = [json.loads(line) for line in+ open(sys.argv[2], encoding="utf-8")]+tables = {record["map"]: record["records"] for record in documents+ if isinstance(record, dict)}+assert set(tables) == {"net", "socket"}, documents+net = tables["net"]+sockets = tables["socket"]+assert any(r["address"] == "127.0.0.1" and r["proto"] == "tcp" and+ r["role"] == "initiator" and int(r["tx_packets"]) >= 1 and+ int(r["rx_packets"]) >= 1 for r in net), net+assert any(r["address"] == "127.0.0.1" and r["proto"] == "udp" and+ int(r["count"]) >= 1 for r in net), net+for item in expected["creations"]:+ assert any(r["operation"] == "create" and+ r["family"] == item["family"] and+ r["type"] == item["type"] and+ r["protocol"] == item["protocol"]+ for r in sockets), (item, sockets)+for family, operation in ((2, "sendmsg"), (1, "bind"),+ (16, "sendmsg")):+ assert any(r["family"] == family and r["operation"] == operation+ for r in sockets), (family, operation, sockets)+for operation in ("bind", "connect", "listen", "accept", "sendmsg",+ "recvmsg", "setsockopt", "shutdown", "socketpair"):+ assert any(r["family"] == 1 and r["operation"] == operation+ for r in sockets), (1, operation, sockets)+if expected["raw_created"]:+ assert any(r["family"] == 2 and r["type"] == 3 and+ r["protocol"] == 1 and r["operation"] == "sendmsg"+ for r in sockets), sockets+if any(r["family"] == 17 for r in sockets):+ assert any(r["family"] == 17 and+ r["operation"] in ("setsockopt", "sendmsg")+ for r in sockets), sockets+if any(r["family"] == 44 for r in sockets):+ assert any(r["family"] == 44 and+ r["operation"] in ("bind", "sendmsg")+ for r in sockets), sockets+if any(r["family"] == 40 for r in sockets):+ assert any(r["family"] == 40 and r["operation"] in+ ("bind", "connect", "sendmsg") for r in sockets), sockets+pass_ids = expected["fd_pass"]+assert any(r["operation"] == "sendmsg" and+ r["owner"]["known"] and+ r["owner"]["pid"] == pass_ids["owner_pid"] and+ r["actor"]["pid"] == pass_ids["actor_pid"]+ for r in sockets), (pass_ids, sockets)+for record in documents:+ if isinstance(record, dict):+ assert record["interval"]["overflow"] == 0, record+ assert record["interval"]["lost"] == 0, record+ for item in record["records"]:+ assert "path" not in item and "payload" not in item, item+PYTHON++test_expect_success 'socket map loads with the network serializers' '+ "$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck >/dev/null 2>&1 &&+ test -e "/run/shirudo/bpffs/upatches/$NAME/serializers/net" &&+ test -e "/run/shirudo/bpffs/upatches/$NAME/serializers/socket"+'++test_expect_success 'TCP, UDP and additional socket families are recorded' '+ python3 upatch/kernel-obs/network/kernel_obs_events.py tcp &&+ python3 upatch/kernel-obs/network/kernel_obs_events.py udp &&+ python3 upatch/kernel-obs/network/kernel_obs_events.py sockets \+ >"$WORK/expected.json" &&+ export_net_maps &&+ python3 "$WORK/check.py" "$WORK/expected.json" "$WORK/events.ndjson"+'++test_donediff --git a/testing/upatch/kernel-obs/network/kernel_obs_events.py b/testing/upatch/kernel-obs/network/kernel_obs_events.pyindex 1a449f92..da85db69 100755--- a/testing/upatch/kernel-obs/network/kernel_obs_events.py+++ b/testing/upatch/kernel-obs/network/kernel_obs_events.py@@ -4,7 +4,9 @@"""Generate activity that exercises every table of the kernel-obs upatch."""import argparse+import ctypesimport errno+import jsonimport osimport randomimport shutil@@ -41,6 +43,7 @@ def exec_event():dropped_uid_executable = os.path.join(directory, "true-drop-euid")shutil.copyfile("/bin/true", dropped_uid_executable)os.chmod(dropped_uid_executable, 0o755)+ os.chmod(directory, 0o755)subprocess.run(["./upatch/kernel-obs/exec/exec-paths","--drop-euid", dropped_uid_executable], check=True)subprocess.run(["./upatch/kernel-obs/exec/exec-paths", "--replace", executable],@@ -117,6 +120,187 @@ def watch_event():sender.close()+def socket_events():+ expected = {"creations": [], "fd_pass": {}}++ def create(family, kind, protocol=0, required=False):+ try:+ sock = socket.socket(family, kind, protocol)+ except OSError:+ if required:+ raise+ return None+ expected["creations"].append({+ "family": family,+ "type": kind & 0xf,+ "protocol": protocol,+ })+ return sock++ raw = create(socket.AF_INET, socket.SOCK_RAW,+ socket.IPPROTO_ICMP)+ expected["raw_created"] = raw is not None+ if raw:+ try:+ raw.sendto(b"\x08\x00\x00\x00\x12\x34\x00\x01",+ ("127.0.0.1", 0))+ except OSError:+ pass+ raw.close()++ def family_module_loaded(*modules):+ return any(os.path.isdir(os.path.join("/sys/module", module))+ for module in modules)++ packet_family = getattr(socket, "AF_PACKET", 17)+ sol_packet = getattr(socket, "SOL_PACKET", 263)+ eth_p_all = 0x0003+ packet_kinds = ((socket.SOCK_RAW, socket.SOCK_DGRAM)+ if family_module_loaded("af_packet") else ())+ for kind in packet_kinds:+ packet = create(packet_family, kind, socket.htons(eth_p_all))+ if not packet:+ continue+ try:+ packet.bind(("lo", socket.htons(eth_p_all)))+ except OSError:+ pass+ try:+ packet.setsockopt(sol_packet, 10, 2)+ packet.setsockopt(sol_packet, 5,+ struct.pack("=7I", 4096, 1, 2048, 2,+ 100, 0, 0))+ packet.setsockopt(sol_packet, 13,+ struct.pack("=4I", 4096, 1, 2048, 2))+ except OSError:+ pass+ try:+ packet.send(b"")+ except OSError:+ pass+ packet.close()++ xdp_family = getattr(socket, "AF_XDP", 44)+ xdp = (create(xdp_family, socket.SOCK_RAW)+ if family_module_loaded("xsk", "xdp_sock", "xdp") else None)+ if xdp:+ class SockaddrXDP(ctypes.Structure):+ _fields_ = [("family", ctypes.c_ushort),+ ("flags", ctypes.c_ushort),+ ("ifindex", ctypes.c_uint),+ ("queue_id", ctypes.c_uint),+ ("shared_umem_fd", ctypes.c_uint)]++ address = SockaddrXDP()+ address.family = xdp_family+ try:+ address.ifindex = socket.if_nametoindex("lo")+ except OSError:+ address.ifindex = 0+ libc = ctypes.CDLL(None, use_errno=True)+ libc.bind.argtypes = [ctypes.c_int, ctypes.c_void_p,+ ctypes.c_uint]+ libc.sendto.argtypes = [ctypes.c_int, ctypes.c_void_p,+ ctypes.c_size_t, ctypes.c_int,+ ctypes.c_void_p, ctypes.c_uint]+ libc.bind(xdp.fileno(), ctypes.byref(address),+ ctypes.sizeof(address))+ libc.sendto(xdp.fileno(), None, 0, 0, ctypes.byref(address),+ ctypes.sizeof(address))+ xdp.close()++ unix_types = (socket.SOCK_STREAM, socket.SOCK_DGRAM,+ socket.SOCK_SEQPACKET)+ with tempfile.TemporaryDirectory() as directory:+ for index, kind in enumerate(unix_types):+ server = create(socket.AF_UNIX, kind, required=True)+ server.setsockopt(socket.SOL_SOCKET, socket.SO_PASSCRED, 0)+ path = os.path.join(directory, f"unix-{index}")+ server.bind(path)+ if kind == socket.SOCK_DGRAM:+ sender = create(socket.AF_UNIX, kind, required=True)+ sender.sendto(b"u", path)+ server.recvfrom(1)+ sender.close()+ else:+ server.listen(1)+ client = create(socket.AF_UNIX, kind, required=True)+ client.connect(path)+ accepted, _ = server.accept()+ client.send(b"u")+ client.shutdown(socket.SHUT_WR)+ accepted.recv(1)+ accepted.close()+ client.close()+ server.close()++ for kind in unix_types:+ try:+ left, right = socket.socketpair(socket.AF_UNIX, kind)+ except OSError:+ continue+ left.send(b"p")+ right.recv(1)+ left.close()+ right.close()++ netlink_family = getattr(socket, "AF_NETLINK", 16)+ netlink_protocol = getattr(socket, "NETLINK_ROUTE", 0)+ netlink = create(netlink_family, socket.SOCK_RAW, netlink_protocol,+ required=True)+ netlink.bind((0, 0))+ sequence = os.getpid() & 0xffffffff+ request = struct.pack("=IHHII", 32, 18, 0x301, sequence, 0)+ request += struct.pack("=BBHiII", 0, 0, 0, 0, 0, 0)+ netlink.settimeout(2)+ netlink.send(request)+ netlink.recv(4096)+ netlink.close()++ vsock_family = getattr(socket, "AF_VSOCK", 40)+ vsock_types = (unix_types if family_module_loaded("vsock") else ())+ for kind in vsock_types:+ vsock = create(vsock_family, kind)+ if not vsock:+ continue+ try:+ vsock.bind((0xffffffff, 0))+ except OSError:+ pass+ try:+ if kind == socket.SOCK_DGRAM:+ vsock.sendto(b"", (2, 1))+ else:+ vsock.setblocking(False)+ vsock.connect_ex((2, 1))+ except OSError:+ pass+ vsock.close()++ flagged = getattr(socket, "SOCK_NONBLOCK", 0) | \+ getattr(socket, "SOCK_CLOEXEC", 0)+ if flagged:+ sock = create(socket.AF_INET, socket.SOCK_DGRAM | flagged)+ if sock:+ sock.close()++ inherited = create(socket.AF_INET, socket.SOCK_DGRAM, required=True)+ inherited.bind(("127.0.0.1", 0))+ owner_pid = os.getpid()+ child_pid = os.fork()+ if child_pid == 0:+ try:+ inherited.sendto(b"i", ("127.0.0.1", 9))+ finally:+ os._exit(0)+ _, status = os.waitpid(child_pid, 0)+ inherited.close()+ if os.waitstatus_to_exitcode(status) != 0:+ raise RuntimeError("inherited socket send failed")+ expected["fd_pass"] = {"owner_pid": owner_pid, "actor_pid": child_pid}+ print(json.dumps(expected))++def dns_name(name):labels = [label.encode() for label in name.split(".")]if not labels or any(not label or len(label) > 63 for label in labels):@@ -218,6 +402,7 @@ EVENTS = {"exec": exec_event,"tcp": tcp_event,"udp": udp_event,+ "sockets": socket_events,"dns": dns_event,"listen": listen_event,"file": file_event,