eBPF-based security platform
testing: share end-to-end setup and snapshot checks
John Fastabend13793e16a5e6
diff --git a/Documentation/contribute/testing/testing.rst b/Documentation/contribute/testing/testing.rstindex 1b89854a..1da86dd7 100644--- a/Documentation/contribute/testing/testing.rst+++ b/Documentation/contribute/testing/testing.rst@@ -575,6 +575,12 @@ hold the same data. The comparison uses event times relative to eachmap's interval start and ignores the metric export time, which the twodecoder calls sample independently.+The kernel observability scenarios share fixture setup, load reports and+unload operations through ``testing/end2end/kernel-obs-lib.sh``. Their+Python assertions use ``snapshots.py`` to read and validate map snapshots;+``kernel_obs_checks.py`` holds the scenario checks called by the shell+tests.+.. code-block:: console# make -C testing end2enddiff --git a/testing/end2end/check-otlp.py b/testing/end2end/check-otlp.pyindex d37b07eb..c90308cb 100644--- a/testing/end2end/check-otlp.py+++ b/testing/end2end/check-otlp.py@@ -10,6 +10,8 @@ import sysimport timeimport urllib.request+from snapshots import read_documents+def value(item):if "stringValue" in item:@@ -60,7 +62,8 @@ def metric_body(metric):return without_export_time(metric)-def collected(path):+def collected(path, require_delivery=False):+ delivery_seen = Falselogs = collections.Counter()metrics = collections.Counter()with open(path, encoding="utf-8") as stream:@@ -73,12 +76,17 @@ def collected(path):for entry in record.get("attributes", [])}if attrs.get("shirudo.upatch.name") != "kernel-obs":continue- logs[key((attrs.get("shirudo.map.name"),- log_body(value(record["body"]))))] += 1+ body = value(record["body"])+ if attrs.get("shirudo.map.name") == "exec":+ delivery_seen |= any("end2end/exec-paths" in entry.get("path", "")+ for entry in body["records"])+ logs[key((attrs.get("shirudo.map.name"), log_body(body)))] += 1for resource in document.get("resourceMetrics", []):for scope in resource.get("scopeMetrics", []):for metric in scope.get("metrics", []):metrics[key(metric_body(metric))] += 1+ if require_delivery:+ assert delivery_seen, "no exec record of the test program in the collector"return logs, metrics@@ -89,15 +97,12 @@ def expected(directory):logs = collections.Counter()metrics = collections.Counter()for path in paths:- with open(path, encoding="utf-8") as stream:- for line in stream:- document = json.loads(line)- if isinstance(document, list):- for metric in document:- metrics[key(metric_body(metric))] += 1- else:- assert document["upatch"] == "kernel-obs", path- logs[key((document["map"], log_body(document)))] += 1+ for document in read_documents(path):+ if isinstance(document, list):+ for metric in document:+ metrics[key(metric_body(metric))] += 1+ else:+ logs[key((document["map"], log_body(document)))] += 1return logs, metrics@@ -184,7 +189,7 @@ def check_clickhouse(endpoint, want_logs, want_metrics, got_logs, got_metrics):def main():want_logs, want_metrics = expected(sys.argv[1])- got_logs, got_metrics = collected(sys.argv[2])+ got_logs, got_metrics = collected(sys.argv[2], require_delivery=True)check(want_logs, got_logs, "log")check(want_metrics, got_metrics, "metric")print(f"verified {sum(want_logs.values())} map logs and "diff --git a/testing/end2end/host.sh b/testing/end2end/host.shindex f7661ac9..7404a307 100755--- a/testing/end2end/host.sh+++ b/testing/end2end/host.sh@@ -194,20 +194,5 @@ python3 "$REPO/testing/end2end/check-otlp.py" \"$REPO/build/test-vm/vms/$VM_NAME-end2end/result/end2end/otel" \"$W/out/otlp.json" "http://$CLICKHOUSE/" || \die "the collector or ClickHouse snapshots differ from the map exports"-python3 - "$W/out/otlp.json" <<'PY' || die "the collector did not get the export"-import json, sys--upatches, text = set(), ""-with open(sys.argv[1]) as f:- for line in f:- text += line- for rl in json.loads(line).get("resourceLogs", []):- for sl in rl.get("scopeLogs", []):- for record in sl.get("logRecords", []):- for kv in record.get("attributes", []):- if kv["key"] == "shirudo.upatch.name":- upatches.add(kv["value"].get("stringValue"))-assert "kernel-obs" in upatches, upatches-assert "end2end/exec-paths" in text, "no exec record of the test's program"-PY+say "ok"diff --git a/testing/end2end/kernel-obs-lib.sh b/testing/end2end/kernel-obs-lib.shnew file mode 100644index 00000000..7eb12b9d--- /dev/null+++ b/testing/end2end/kernel-obs-lib.sh@@ -0,0 +1,40 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++. ./end2end/otel-export.sh++kernel_obs_setup()+{+ 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"+ [ -s "$LOAD" ] || test_skip_all "missing kernel-obs fixture"+ [ -s "$UNLOAD" ] || test_skip_all "missing kernel-obs unload fixture"+ otel_setup+ WORK=$(mktemp -d)+}++kernel_obs_unload()+{+ if [ -e "/run/shirudo/bpffs/upatches/$1/link_0" ] ||+ [ -e "/run/shirudo/bpffs/upatches/$1/link" ]; then+ "$SHIRUDO_BIN" upatch unload "$2" --no-precheck \+ >/dev/null 2>&1 || true+ fi+}++kernel_obs_load()+{+ if "$SHIRUDO_BIN" upatch load "$1" --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/$2"+ fi+ return 1+}diff --git a/testing/end2end/kernel_obs_checks.py b/testing/end2end/kernel_obs_checks.pynew file mode 100644index 00000000..e0e8f985--- /dev/null+++ b/testing/end2end/kernel_obs_checks.py@@ -0,0 +1,250 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++import json+import sys++from snapshots import read_documents, tables_from+++def t9101_check(argv):+ documents = read_documents(argv[1])+ records = [document for document in documents+ if isinstance(document, dict) and "map" in document]+ metrics = [document for document in documents if isinstance(document, list)]+ expected = {"exec", "net", "socket", "listen", "watch", "dns", "priv", "file"}+ assert {record["map"] for record in records} == expected, documents+ assert len(metrics) == 1, documents+ assert metrics[0][0]["name"] == "kernel_obs.watch_attempts", metrics+ for record in records:+ for item in record["records"]:+ assert isinstance(item["first_seen_unix_nano"], str), item+ assert isinstance(item["last_seen_unix_nano"], str), item+ assert int(item["first_seen_unix_nano"]) > 0, item+++def t9101_check_events(argv):+ documents = read_documents(argv[1])+ tables = tables_from(documents)+ exec_ids = {(r["executable"]["dev"], r["executable"]["ino"])+ for r in tables["exec"]}+ assert any(r["name"] == "true" and r["path"].endswith("/true")+ for r in tables["exec"]), tables["exec"]+ assert any("caller" in r for r in tables["exec"]), tables["exec"]+ assert any(r["caller_inferred"] and "caller" in r+ for r in tables["exec"]), tables["exec"]+ helper_records = [r for r in tables["exec"]+ if r["path"].endswith("/end2end/exec-paths")]+ helper = next(r for r in helper_records+ if (r.get("caller", {}).get("dev"),+ r.get("caller", {}).get("ino")) !=+ (r["executable"]["dev"], r["executable"]["ino"]))+ helper_id = (helper["executable"]["dev"], helper["executable"]["ino"])+ self_exec = [r for r in tables["exec"]+ if (r["executable"]["dev"], r["executable"]["ino"]) == helper_id+ and (r.get("caller", {}).get("dev"),+ r.get("caller", {}).get("ino")) == helper_id]+ assert sum(int(r["exec_count"]) for r in self_exec) == 5, self_exec+ assert all(not r["caller_inferred"] and "caller" in r+ for r in self_exec), self_exec+ assert any(r["uid"] == 0 and r["euid"] == 0 and+ int(r["cap_effective"]) > 0 for r in self_exec), self_exec+ replace_exec = [r for r in tables["exec"]+ if r["path"].endswith("/true") and+ (r.get("caller", {}).get("dev"),+ r.get("caller", {}).get("ino")) == helper_id]+ assert replace_exec and any(r["pid"] == helper["pid"]+ for r in replace_exec), (helper, replace_exec)+ for method in ("execveat-empty", "fexecve"):+ fd_exec = [r for r in tables["exec"]+ if r["path"].endswith(f"/true-{method}") and+ (r.get("caller", {}).get("dev"),+ r.get("caller", {}).get("ino")) == helper_id]+ assert len(fd_exec) == 1 and int(fd_exec[0]["exec_count"]) == 1, fd_exec+ dirfd_exec = [r for r in tables["exec"]+ if r["path"].endswith("/true-execveat-dirfd") and+ (r.get("caller", {}).get("dev"),+ r.get("caller", {}).get("ino")) == helper_id]+ assert len(dirfd_exec) == 1 and int(dirfd_exec[0]["exec_count"]) == 1, dirfd_exec+ drop_euid_exec = [r for r in tables["exec"]+ if r["path"].endswith("/true-drop-euid") and+ (r.get("caller", {}).get("dev"),+ r.get("caller", {}).get("ino")) == helper_id]+ assert len(drop_euid_exec) == 1, drop_euid_exec+ assert (drop_euid_exec[0]["uid"] == 65534 and+ drop_euid_exec[0]["euid"] == 65534 and+ int(drop_euid_exec[0]["cap_effective"]) == 0), drop_euid_exec+ for name in ("exec-script", "exec-script-fd"):+ scripts = [r for r in tables["exec"]+ if r["path"].endswith("/" + name) and+ (r.get("caller", {}).get("dev"),+ r.get("caller", {}).get("ino")) == helper_id]+ assert len(scripts) == 1 and not scripts[0]["interpreter"], scripts+ assert int(scripts[0]["exec_count"]) == 1, scripts+ script_id = (scripts[0]["executable"]["dev"],+ scripts[0]["executable"]["ino"])+ interpreters = [r for r in tables["exec"]+ if r["interpreter"] and+ (r.get("caller", {}).get("dev"),+ r.get("caller", {}).get("ino")) == script_id and+ r["pid"] == scripts[0]["pid"]]+ assert len(interpreters) == 1, (scripts, interpreters)+ for name in ("net", "dns"):+ assert any((r["executable"]["dev"], r["executable"]["ino"]) in exec_ids+ for r in tables[name]), (name, tables[name])+ assert any(r["address"] == "127.0.0.1" and r["proto"] == "tcp" and+ r["role"] == "initiator" and int(r["count"]) >= 1 and+ int(r["tx_packets"]) >= 1 and int(r["rx_packets"]) >= 1+ for r in tables["net"]), tables["net"]+ assert any(r["address"] == "127.0.0.1" and r["proto"] == "tcp" and+ r.get("role") == "acceptor" for r in tables["net"]), tables["net"]+ assert any(r["address"] == "127.0.0.1" and r["proto"] == "udp" and+ int(r["count"]) >= 1 for r in tables["net"]), tables["net"]+ assert any(r["kind"] == "listen" and r["proto"] == "tcp" and+ r["address"] == "127.0.0.1" and r["port"] > 0+ for r in tables["listen"]), tables["listen"]+ assert any(r["kind"] == "bind" and r["proto"] == "udp" and+ r["port"] == 35353 for r in tables["listen"]), tables["listen"]+ assert any(n["name"] == "example.com"+ for r in tables["dns"] for n in r["names"]), tables["dns"]+ long_name = ".".join(["a"] * 127)+ assert any(n["name"] == long_name+ for r in tables["dns"] for n in r["names"]), tables["dns"]+ assert any(r["address"] == "203.0.113.75" and+ any(n["name"] == "many.example" for n in r["names"])+ for r in tables["dns"]), tables["dns"]+ assert any(r["path"] == "/etc/shadow" and r["mode"] == "r"+ for r in tables["file"]), tables["file"]+ assert any(r["path"].endswith("/environ")+ for r in tables["file"]), tables["file"]+++def t9101_check_watch(argv):+ documents = read_documents(argv[1])+ tables = tables_from(documents)+ metrics = [document for document in documents if isinstance(document, list)]+ assert any(r["address"] == "203.0.113.10" and r["proto"] == "tcp" and+ r["port"] == 80 and int(r["attempts"]) >= 1+ for r in tables["watch"]), tables["watch"]+ assert any(r["address"] == "2001:0db8:0000:0000:0000:0000:0000:0010" and+ r["proto"] == "udp" for r in tables["watch"]), tables["watch"]+ assert any(r["address"] == "203.0.113.10" and+ r.get("role") == "initiator" for r in tables["net"]), tables["net"]+ metric = metrics[0][0]+ assert metric["name"] == "kernel_obs.watch_attempts", metric+ values = {point["attributes"][0]["value"]["stringValue"]: int(point["asInt"])+ for point in metric["sum"]["dataPoints"]}+ assert values["matched"] >= 2, values+ assert values["checked"] >= values["matched"], values+++def t9101_check_drained(argv):+ documents = read_documents(argv[1])+ tables = tables_from(documents)+ for name in ("listen", "watch", "file"):+ assert not tables[name], (name, tables[name])+ # The guest's own resolver traffic may land in the window; the test's+ # names must be gone.+ test_names = {"example.com", "many.example", ".".join(["a"] * 127)}+ assert not any(n["name"] in test_names+ for r in tables["dns"] for n in r["names"]), tables["dns"]+++def t9101_check_exec_only(argv):+ documents = read_documents(argv[1])+ tables = tables_from(documents)+ assert tables["exec"], tables+ for name in ("listen", "watch", "file"):+ assert not tables[name], (name, tables)+ test_names = {"example.com", "many.example", ".".join(["a"] * 127)}+ assert not any(n["name"] in test_names+ for r in tables["dns"] for n in r["names"]), tables["dns"]+ assert not any(r["kind"] in ("userns_create", "mount")+ for r in tables["priv"]), tables["priv"]+++def t9102_check(argv):+ expected = json.load(open(argv[1], encoding="utf-8"))+ documents = read_documents(argv[2])+ tables = tables_from(documents)+ 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):+ for item in record["records"]:+ assert "path" not in item and "payload" not in item, item+++def t9104_check(argv):+ records = read_documents(argv[1])+ 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+++def t9104_check_empty(argv):+ records = read_documents(argv[1])+ assert len(records) == 1 and records[0].get("map") == "dns", records+ assert records[0].get("records") == [], records+++CHECKS = {+ "t9101_check": t9101_check,+ "t9101_check_events": t9101_check_events,+ "t9101_check_watch": t9101_check_watch,+ "t9101_check_drained": t9101_check_drained,+ "t9101_check_exec_only": t9101_check_exec_only,+ "t9102_check": t9102_check,+ "t9104_check": t9104_check,+ "t9104_check_empty": t9104_check_empty,+}+++if __name__ == "__main__":+ CHECKS[sys.argv[1]]([sys.argv[0]] + sys.argv[2:])diff --git a/testing/end2end/priv_events.py b/testing/end2end/priv_events.pyindex e5c38d5c..10d42cb3 100644--- a/testing/end2end/priv_events.py+++ b/testing/end2end/priv_events.py@@ -13,6 +13,8 @@ import socketimport structimport sys+from snapshots import read_documents+PAGE_SIZE = os.sysconf("SC_PAGE_SIZE")PROT_READ = 1PROT_WRITE = 2@@ -370,13 +372,8 @@ def generate(expected_path):def records_from(path):- with open(path, encoding="utf-8") as stream:- documents = [json.loads(line) for line in stream]+ documents = read_documents(path)document = next(doc for doc in documents if doc.get("map") == "priv")- assert document["schema"] == 1, document- assert document["upatch"] == "kernel-obs", document- assert document["interval"]["overflow"] == 0, document- assert document["interval"]["lost"] == 0, documentreturn document["records"]@@ -441,8 +438,7 @@ def anomaly_event(expected_path):def check_exec_unknown(path):- with open(path, encoding="utf-8") as source:- documents = [json.loads(line) for line in source]+ documents = read_documents(path)document = next(doc for doc in documents if doc.get("map") == "exec")records = document["records"]unknown = [record for record in recordsdiff --git a/testing/end2end/snapshots.py b/testing/end2end/snapshots.pynew file mode 100644index 00000000..d1f3eac2--- /dev/null+++ b/testing/end2end/snapshots.py@@ -0,0 +1,24 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++import json+++def read_documents(path):+ with open(path, encoding="utf-8") as stream:+ documents = [json.loads(line) for line in stream]+ for document in documents:+ if isinstance(document, dict):+ assert document["schema"] == 1, document+ assert document["upatch"] == "kernel-obs", document+ assert isinstance(document["records"], list), document+ for name in ("used", "overflow", "lost"):+ assert isinstance(document["interval"][name], int), document+ assert document["interval"]["overflow"] == 0, document+ assert document["interval"]["lost"] == 0, document+ return documents+++def tables_from(documents):+ return {document["map"]: document["records"] for document in documents+ if isinstance(document, dict)}diff --git a/testing/end2end/t9101-kernel-obs.sh b/testing/end2end/t9101-kernel-obs.shindex 6dc69017..9e832cc5 100755--- a/testing/end2end/t9101-kernel-obs.sh+++ b/testing/end2end/t9101-kernel-obs.sh@@ -7,29 +7,17 @@ cd "$(dirname "$0")/.."target_guardcommand -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"+. ./end2end/kernel-obs-lib.sh+kernel_obs_setupTABLES="exec net socket listen watch dns priv file"-WORK=$(mktemp -d)-. ./end2end/otel-export.sh-otel_setupcleanup(){- if [ -e "$PIN" ] || [ -e "/run/shirudo/bpffs/upatches/$NAME/link" ]; then- "$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck \- >/dev/null 2>&1 || true- fi+ kernel_obs_unload "$NAME" "$UNLOAD"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_maps(){output="$1"@@ -38,205 +26,8 @@ export_maps()done}-load_observability()-{- if "$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck --report=- \- >"$WORK/load.log" 2>&1; then- return 0- fi- cat "$WORK/load.log" >&2- if [ -d /mnt/shirudo-out ]; then- cp "$WORK/load.log" /mnt/shirudo-out/kernel-obs-load.log- fi- return 1-}--cat >"$WORK/check.py" <<'PY'-import json-import sys--documents = [json.loads(line) for line in open(sys.argv[1], encoding="utf-8")]-records = [document for document in documents- if isinstance(document, dict) and "map" in document]-metrics = [document for document in documents if isinstance(document, list)]-expected = {"exec", "net", "socket", "listen", "watch", "dns", "priv", "file"}-assert {record["map"] for record in records} == expected, documents-assert len(metrics) == 1, documents-assert metrics[0][0]["name"] == "kernel_obs.watch_attempts", metrics-for record in records:- assert record["schema"] == 1, record- assert record["upatch"] == "kernel-obs", record- assert isinstance(record["records"], list), record- interval = record["interval"]- assert isinstance(interval, dict), record- for key in ("used", "overflow", "lost"):- assert isinstance(interval[key], int), record- assert interval["overflow"] == 0, record- assert interval["lost"] == 0, record- for item in record["records"]:- assert isinstance(item["first_seen_unix_nano"], str), item- assert isinstance(item["last_seen_unix_nano"], str), item- assert int(item["first_seen_unix_nano"]) > 0, item-PY--cat >"$WORK/check_events.py" <<'PY'-import json-import sys--documents = [json.loads(line) for line in open(sys.argv[1], encoding="utf-8")]-tables = {record["map"]: record["records"] for record in documents- if isinstance(record, dict)}-exec_ids = {(r["executable"]["dev"], r["executable"]["ino"])- for r in tables["exec"]}-assert any(r["name"] == "true" and r["path"].endswith("/true")- for r in tables["exec"]), tables["exec"]-assert any("caller" in r for r in tables["exec"]), tables["exec"]-assert any(r["caller_inferred"] and "caller" in r- for r in tables["exec"]), tables["exec"]-helper_records = [r for r in tables["exec"]- if r["path"].endswith("/end2end/exec-paths")]-helper = next(r for r in helper_records- if (r.get("caller", {}).get("dev"),- r.get("caller", {}).get("ino")) !=- (r["executable"]["dev"], r["executable"]["ino"]))-helper_id = (helper["executable"]["dev"], helper["executable"]["ino"])-self_exec = [r for r in tables["exec"]- if (r["executable"]["dev"], r["executable"]["ino"]) == helper_id- and (r.get("caller", {}).get("dev"),- r.get("caller", {}).get("ino")) == helper_id]-assert sum(int(r["exec_count"]) for r in self_exec) == 5, self_exec-assert all(not r["caller_inferred"] and "caller" in r- for r in self_exec), self_exec-assert any(r["uid"] == 0 and r["euid"] == 0 and- int(r["cap_effective"]) > 0 for r in self_exec), self_exec-replace_exec = [r for r in tables["exec"]- if r["path"].endswith("/true") and- (r.get("caller", {}).get("dev"),- r.get("caller", {}).get("ino")) == helper_id]-assert replace_exec and any(r["pid"] == helper["pid"]- for r in replace_exec), (helper, replace_exec)-for method in ("execveat-empty", "fexecve"):- fd_exec = [r for r in tables["exec"]- if r["path"].endswith(f"/true-{method}") and- (r.get("caller", {}).get("dev"),- r.get("caller", {}).get("ino")) == helper_id]- assert len(fd_exec) == 1 and int(fd_exec[0]["exec_count"]) == 1, fd_exec-dirfd_exec = [r for r in tables["exec"]- if r["path"].endswith("/true-execveat-dirfd") and- (r.get("caller", {}).get("dev"),- r.get("caller", {}).get("ino")) == helper_id]-assert len(dirfd_exec) == 1 and int(dirfd_exec[0]["exec_count"]) == 1, dirfd_exec-drop_euid_exec = [r for r in tables["exec"]- if r["path"].endswith("/true-drop-euid") and- (r.get("caller", {}).get("dev"),- r.get("caller", {}).get("ino")) == helper_id]-assert len(drop_euid_exec) == 1, drop_euid_exec-assert (drop_euid_exec[0]["uid"] == 65534 and- drop_euid_exec[0]["euid"] == 65534 and- int(drop_euid_exec[0]["cap_effective"]) == 0), drop_euid_exec-for name in ("exec-script", "exec-script-fd"):- scripts = [r for r in tables["exec"]- if r["path"].endswith("/" + name) and- (r.get("caller", {}).get("dev"),- r.get("caller", {}).get("ino")) == helper_id]- assert len(scripts) == 1 and not scripts[0]["interpreter"], scripts- assert int(scripts[0]["exec_count"]) == 1, scripts- script_id = (scripts[0]["executable"]["dev"],- scripts[0]["executable"]["ino"])- interpreters = [r for r in tables["exec"]- if r["interpreter"] and- (r.get("caller", {}).get("dev"),- r.get("caller", {}).get("ino")) == script_id and- r["pid"] == scripts[0]["pid"]]- assert len(interpreters) == 1, (scripts, interpreters)-for name in ("net", "dns"):- assert any((r["executable"]["dev"], r["executable"]["ino"]) in exec_ids- for r in tables[name]), (name, tables[name])-assert any(r["address"] == "127.0.0.1" and r["proto"] == "tcp" and- r["role"] == "initiator" and int(r["count"]) >= 1 and- int(r["tx_packets"]) >= 1 and int(r["rx_packets"]) >= 1- for r in tables["net"]), tables["net"]-assert any(r["address"] == "127.0.0.1" and r["proto"] == "tcp" and- r.get("role") == "acceptor" for r in tables["net"]), tables["net"]-assert any(r["address"] == "127.0.0.1" and r["proto"] == "udp" and- int(r["count"]) >= 1 for r in tables["net"]), tables["net"]-assert any(r["kind"] == "listen" and r["proto"] == "tcp" and- r["address"] == "127.0.0.1" and r["port"] > 0- for r in tables["listen"]), tables["listen"]-assert any(r["kind"] == "bind" and r["proto"] == "udp" and- r["port"] == 35353 for r in tables["listen"]), tables["listen"]-assert any(n["name"] == "example.com"- for r in tables["dns"] for n in r["names"]), tables["dns"]-long_name = ".".join(["a"] * 127)-assert any(n["name"] == long_name- for r in tables["dns"] for n in r["names"]), tables["dns"]-assert any(r["address"] == "203.0.113.75" and- any(n["name"] == "many.example" for n in r["names"])- for r in tables["dns"]), tables["dns"]-assert any(r["path"] == "/etc/shadow" and r["mode"] == "r"- for r in tables["file"]), tables["file"]-assert any(r["path"].endswith("/environ")- for r in tables["file"]), tables["file"]-PY--cat >"$WORK/check_watch.py" <<'PY'-import json-import sys--documents = [json.loads(line) for line in open(sys.argv[1], encoding="utf-8")]-tables = {record["map"]: record["records"] for record in documents- if isinstance(record, dict)}-metrics = [document for document in documents if isinstance(document, list)]-assert any(r["address"] == "203.0.113.10" and r["proto"] == "tcp" and- r["port"] == 80 and int(r["attempts"]) >= 1- for r in tables["watch"]), tables["watch"]-assert any(r["address"] == "2001:0db8:0000:0000:0000:0000:0000:0010" and- r["proto"] == "udp" for r in tables["watch"]), tables["watch"]-assert any(r["address"] == "203.0.113.10" and- r.get("role") == "initiator" for r in tables["net"]), tables["net"]-metric = metrics[0][0]-assert metric["name"] == "kernel_obs.watch_attempts", metric-values = {point["attributes"][0]["value"]["stringValue"]: int(point["asInt"])- for point in metric["sum"]["dataPoints"]}-assert values["matched"] >= 2, values-assert values["checked"] >= values["matched"], values-PY--cat >"$WORK/check_drained.py" <<'PY'-import json-import sys--documents = [json.loads(line) for line in open(sys.argv[1], encoding="utf-8")]-tables = {record["map"]: record["records"] for record in documents- if isinstance(record, dict)}-for name in ("listen", "watch", "file"):- assert not tables[name], (name, tables[name])-# The guest's own resolver traffic may land in the window; the test's-# names must be gone.-test_names = {"example.com", "many.example", ".".join(["a"] * 127)}-assert not any(n["name"] in test_names- for r in tables["dns"] for n in r["names"]), tables["dns"]-PY--cat >"$WORK/check_exec_only.py" <<'PY'-import json-import sys--documents = [json.loads(line) for line in open(sys.argv[1], encoding="utf-8")]-tables = {record["map"]: record["records"] for record in documents- if isinstance(record, dict)}-assert tables["exec"], tables-for name in ("listen", "watch", "file"):- assert not tables[name], (name, tables)-test_names = {"example.com", "many.example", ".".join(["a"] * 127)}-assert not any(n["name"] in test_names- for r in tables["dns"] for n in r["names"]), tables["dns"]-assert not any(r["kind"] in ("userns_create", "mount")- for r in tables["priv"]), tables["priv"]-PY-test_expect_success 'kernel-obs upatch loads with eight serializers' '- load_observability &&+ kernel_obs_load "$LOAD" kernel-obs-load.log &&for map in $TABLES; do[ -e "/run/shirudo/bpffs/upatches/$NAME/serializers/$map" ] ||exit 1@@ -248,25 +39,25 @@ test_expect_success 'exec, net, listen, DNS, privilege and file events produce rpython3 end2end/kernel_obs_events.py dns-long &&python3 end2end/kernel_obs_events.py dns-many &&export_maps "$OTEL_OUT/t9101-events.ndjson" &&- python3 "$WORK/check.py" "$OTEL_OUT/t9101-events.ndjson" &&- python3 "$WORK/check_events.py" "$OTEL_OUT/t9101-events.ndjson"+ python3 end2end/kernel_obs_checks.py t9101_check "$OTEL_OUT/t9101-events.ndjson" &&+ python3 end2end/kernel_obs_checks.py t9101_check_events "$OTEL_OUT/t9101-events.ndjson"'test_expect_success 'watched destinations are recorded with the metric' 'python3 end2end/kernel_obs_events.py watch &&export_maps "$OTEL_OUT/t9101-watch.ndjson" &&- python3 "$WORK/check_watch.py" "$OTEL_OUT/t9101-watch.ndjson"+ python3 end2end/kernel_obs_checks.py t9101_check_watch "$OTEL_OUT/t9101-watch.ndjson"'test_expect_success 'an export drains the tables' 'export_maps "$OTEL_OUT/t9101-drained.ndjson" &&- python3 "$WORK/check_drained.py" "$OTEL_OUT/t9101-drained.ndjson"+ python3 end2end/kernel_obs_checks.py t9101_check_drained "$OTEL_OUT/t9101-drained.ndjson"'test_expect_success 'only the touched tables carry records' 'python3 end2end/kernel_obs_events.py exec &&export_maps "$OTEL_OUT/t9101-exec-only.ndjson" &&- python3 "$WORK/check_exec_only.py" "$OTEL_OUT/t9101-exec-only.ndjson"+ python3 end2end/kernel_obs_checks.py t9101_check_exec_only "$OTEL_OUT/t9101-exec-only.ndjson"'test_donediff --git a/testing/end2end/t9102-kernel-obs-net.sh b/testing/end2end/t9102-kernel-obs-net.shindex 32eef472..d202bd32 100755--- a/testing/end2end/t9102-kernel-obs-net.sh+++ b/testing/end2end/t9102-kernel-obs-net.sh@@ -7,29 +7,17 @@ cd "$(dirname "$0")/.."target_guardcommand -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)-. ./end2end/otel-export.sh-otel_setup+. ./end2end/kernel-obs-lib.sh+kernel_obs_setupcleanup(){- if [ -e "$PIN" ] || [ -e "/run/shirudo/bpffs/upatches/$NAME/link" ]; then- "$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck \- >/dev/null 2>&1 || true- fi+ kernel_obs_unload "$NAME" "$UNLOAD"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@@ -37,68 +25,8 @@ export_net_maps()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 &&+ kernel_obs_load "$LOAD" kernel-obs-load.log &&test -e "/run/shirudo/bpffs/upatches/$NAME/serializers/net" &&test -e "/run/shirudo/bpffs/upatches/$NAME/serializers/socket"'@@ -109,7 +37,7 @@ test_expect_success 'TCP, UDP and additional socket families are recorded' 'python3 end2end/kernel_obs_events.py sockets \>"$WORK/expected.json" &&export_net_maps &&- python3 "$WORK/check.py" "$WORK/expected.json" \+ python3 end2end/kernel_obs_checks.py t9102_check "$WORK/expected.json" \"$OTEL_OUT/t9102-events.ndjson"'diff --git a/testing/end2end/t9103-kernel-obs-priv.sh b/testing/end2end/t9103-kernel-obs-priv.shindex 599c6d41..04b165ad 100755--- a/testing/end2end/t9103-kernel-obs-priv.sh+++ b/testing/end2end/t9103-kernel-obs-priv.sh@@ -7,19 +7,13 @@ cd "$(dirname "$0")/.."target_guardcommand -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"+. ./end2end/kernel-obs-lib.sh+kernel_obs_setupANOMALY_LOAD="$FIXTURES/kernel-obs-cred-anomaly.upatch"ANOMALY_UNLOAD="$FIXTURES/kernel-obs-cred-anomaly.unload.upatch"BPF_FILTER_LOAD="$FIXTURES/shirudo-test-map-export.upatch"BPF_FILTER_UNLOAD="$FIXTURES/shirudo-test-map-export.unload.upatch"-PIN="/run/shirudo/bpffs/upatches/$NAME/link_0"MODPROBE_FILE=/proc/sys/kernel/modprobe-WORK=$(mktemp -d)-. ./end2end/otel-export.sh-otel_setupMODPROBE_BACKUP="$WORK/kernel.modprobe"EVENT_PID=@@ -29,26 +23,16 @@ cleanup()kill "$EVENT_PID" 2>/dev/null || truewait "$EVENT_PID" 2>/dev/null || truefi- if [ -e "/run/shirudo/bpffs/upatches/shirudo-test-map-export/link_0" ] ||- [ -e "/run/shirudo/bpffs/upatches/shirudo-test-map-export/link" ]; then- "$SHIRUDO_BIN" upatch unload "$BPF_FILTER_UNLOAD" --no-precheck \- >/dev/null 2>&1 || true- fi+ kernel_obs_unload shirudo-test-map-export "$BPF_FILTER_UNLOAD"if [ -s "$MODPROBE_BACKUP" ] || [ -e "$MODPROBE_BACKUP" ]; thencat "$MODPROBE_BACKUP" >"$MODPROBE_FILE" || truefi- if [ -e "$PIN" ] || [ -e "/run/shirudo/bpffs/upatches/$NAME/link" ]; then- "$SHIRUDO_BIN" upatch unload "$ANOMALY_UNLOAD" --no-precheck \- >/dev/null 2>&1 || true- "$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck \- >/dev/null 2>&1 || true- fi+ kernel_obs_unload "$NAME" "$ANOMALY_UNLOAD"+ kernel_obs_unload "$NAME" "$UNLOAD"rm -rf "$WORK"}trap cleanup EXIT HUP INT TERM-[ -s "$LOAD" ] || test_skip_all "missing kernel-obs fixture"-[ -s "$UNLOAD" ] || test_skip_all "missing kernel-obs unload fixture"[ -s "$BPF_FILTER_LOAD" ] || test_skip_all "missing BPF filter fixture"[ -s "$BPF_FILTER_UNLOAD" ] || test_skip_all "missing BPF filter unload fixture"mkfifo "$WORK/events.in" "$WORK/events.out"@@ -81,26 +65,13 @@ run_module_request()return "$result"}-load_observability()-{- if "$SHIRUDO_BIN" upatch load "$1" --no-precheck --report=- \- >"$WORK/load.log" 2>&1; then- return 0- fi- cat "$WORK/load.log" >&2- if [ -d /mnt/shirudo-out ]; then- cp "$WORK/load.log" /mnt/shirudo-out/kernel-obs-priv-load.log- fi- return 1-}-export_priv(){otel_export priv "$1"}test_expect_success 'kernel-obs upatch loads with the priv serializer' '- load_observability "$LOAD" &&+ kernel_obs_load "$LOAD" kernel-obs-priv-load.log &&test -e "/run/shirudo/bpffs/upatches/$NAME/serializers/priv"'@@ -139,7 +110,7 @@ test_expect_success 'credential anomalies are recorded once per task' '[ -s "$ANOMALY_LOAD" ] && [ -s "$ANOMALY_UNLOAD" ] &&"$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck \>/dev/null &&- load_observability "$ANOMALY_LOAD" &&+ kernel_obs_load "$ANOMALY_LOAD" kernel-obs-priv-load.log &&python3 end2end/priv_events.py anomaly \"$WORK/anomaly-expected.json" &&export_priv "$OTEL_OUT/t9103-anomaly.ndjson" &&diff --git a/testing/end2end/t9104-kernel-obs-dns-matrix.sh b/testing/end2end/t9104-kernel-obs-dns-matrix.shindex e662f898..47b81624 100755--- a/testing/end2end/t9104-kernel-obs-dns-matrix.sh+++ b/testing/end2end/t9104-kernel-obs-dns-matrix.sh@@ -7,61 +7,24 @@ cd "$(dirname "$0")/.."target_guardcommand -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)-. ./end2end/otel-export.sh-otel_setup+. ./end2end/kernel-obs-lib.sh+kernel_obs_setupcleanup(){- if [ -e "$PIN" ] || [ -e "/run/shirudo/bpffs/upatches/$NAME/link" ]; then- "$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck \- >/dev/null 2>&1 || true- fi+ kernel_obs_unload "$NAME" "$UNLOAD"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"--cat >"$WORK/check.py" <<'PYTHON'-import json-import sys--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--cat >"$WORK/check-empty.py" <<'PYTHON'-import json-import sys--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-test_expect_success 'DNS observations use real loopback UDP traffic' '- "$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck >/dev/null 2>&1 &&+ kernel_obs_load "$LOAD" kernel-obs-load.log &&python3 end2end/kernel_obs_events.py dns-long &&python3 end2end/kernel_obs_events.py dns-many &&otel_export dns "$OTEL_OUT/t9104-dns.ndjson" &&- python3 "$WORK/check.py" "$OTEL_OUT/t9104-dns.ndjson" &&+ python3 end2end/kernel_obs_checks.py t9104_check "$OTEL_OUT/t9104-dns.ndjson" &&otel_export dns "$OTEL_OUT/t9104-dns-empty.ndjson" &&- python3 "$WORK/check-empty.py" "$OTEL_OUT/t9104-dns-empty.ndjson"+ python3 end2end/kernel_obs_checks.py t9104_check_empty "$OTEL_OUT/t9104-dns-empty.ndjson"'test_done