eBPF-based security platform
testing: check kernel verification of config images
KP Singh6f11ee8be5fc
diff --git a/testing/tamperproof/t1154-verity-config.py b/testing/tamperproof/t1154-verity-config.pynew file mode 100644index 00000000..440a43d7--- /dev/null+++ b/testing/tamperproof/t1154-verity-config.py@@ -0,0 +1,212 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++import errno+import hashlib+import json+import os+from pathlib import Path+import secrets+import shutil+import struct+import subprocess+import sys+import tempfile+import time+++BINARY = os.environ["SHIRUDO_BIN"]+IMAGES = Path("/var/lib/shirudo/images")+CONFIG = Path("/run/shirudo/config")+RUNTIME = Path("/run/shirudo/runtime")+JOURNAL = Path("/var/lib/shirudo/config-update")+RESULTS = Path(sys.argv[2]).resolve()+NAMES = ("config-a", "config-b", "config-boot-keys", "config-revoke",+ "config-tree-stable", "config-tree-updated", "config-tree-deleted",+ "config-tree-restored", "config-otel", "config-interrupted", "config-builtin")+++def require(condition, message):+ if not condition:+ raise AssertionError(message)+++def run(label, *arguments, success=True):+ result = subprocess.run([BINARY, *map(str, arguments)],+ capture_output=True, text=True, timeout=120)+ (RESULTS / (label + ".stdout")).write_text(result.stdout)+ (RESULTS / (label + ".stderr")).write_text(result.stderr)+ require(result.returncode == (0 if success else 1),+ f"{arguments}: exit {result.returncode}\n"+ f"{result.stdout}\n{result.stderr}")+ return result.stdout+++def root(name):+ data = (IMAGES / (name + ".roothash")).read_bytes()+ require(len(data) == 64 and all(c in b"0123456789abcdef" for c in data),+ f"invalid root encoding: {name}")+ return data.decode("ascii")+++def load(name):+ return json.loads((RESULTS / (name + ".json")).read_text())+++def save(name, data):+ (RESULTS / (name + ".json")).write_text(json.dumps(data, indent=2))+++def mount(path):+ rows = [line for line in Path("/proc/self/mountinfo").read_text().splitlines()+ if line.split()[4] == str(path)]+ require(len(rows) == 1, f"expected one mount at {path}: {rows}")+ flags = os.statvfs(path).f_flag+ expected = os.ST_RDONLY | os.ST_NOSUID | os.ST_NODEV+ if path == CONFIG:+ expected |= os.ST_NOEXEC+ require(flags & expected == expected, f"unsafe mount flags: {path}")+ return rows[0]+++def mapping_inventory():+ # Deferred verification cleanup can race with sysfs inventory reads.+ deadline = time.monotonic() + 5+ while True:+ try:+ mappings = sorted(+ (p.read_text().strip(),+ (p.parent.parent / "dev").read_text().strip())+ for p in Path("/sys/class/block").glob("dm-*/dm/name"))+ except OSError as error:+ if error.errno not in (errno.ENOENT, errno.EINVAL):+ raise+ pending = str(error)+ else:+ pending = [name for name, _ in mappings+ if name.startswith("shirudo-verify-")]+ if not pending:+ return mappings+ require(time.monotonic() < deadline,+ f"DM inventory did not settle: {pending}")+ time.sleep(0.05)+++def snapshot(label):+ effects = {+ "mount": mount(CONFIG), "runtime_mount": mount(RUNTIME),+ "settings": (CONFIG / "etc/shirudo/shirudo.conf").read_text(),+ "journal": {p.name: p.read_bytes().hex()+ for p in sorted(JOURNAL.iterdir()) if p.is_file()},+ "mappings": mapping_inventory(),+ }+ status = json.loads(run(label + "-status", "image", "status"))+ require(status["consistent"] and not status["pending"], status)+ records = [json.loads(line) for line in (JOURNAL / "events").read_text().splitlines()]+ records = [r for r in records if r["reset_count"] == status["reset_count"] and+ r["restart_count"] == status["restart_count"]]+ require(records and records[0]["kind"] == 1, "missing boot event")+ events = [{k: r[k] for k in ("sequence", "kind", "root_hash")} for r in records]+ view = {"events": events, "initial_pcr": records[0]["initial_pcr"]}+ result = subprocess.run(["tpm2_pcrread", "sha256:" + str(status["pcr"])],+ capture_output=True, text=True, timeout=30)+ require(result.returncode == 0, result.stderr)+ (RESULTS / (label + ".pcr.stdout")).write_text(result.stdout)+ import re+ match = re.search(r"\b" + str(status["pcr"]) + r"\s*:\s*0x([0-9a-fA-F]{64})", result.stdout)+ require(match is not None, "missing PCR value")+ pcr = match.group(1).lower()+ value = bytes.fromhex(view["initial_pcr"])+ for event in events:+ digest = hashlib.sha256(b"shirudo-config-root-v1\0" ++ struct.pack(">I", event["kind"]) ++ bytes.fromhex(event["root_hash"])).digest()+ value = hashlib.sha256(value + digest).digest()+ require(value.hex() == pcr, "journal replay differs from direct PCR read")+ require(events[-1]["root_hash"] == status["root_hash"] and+ events[-1]["sequence"] == status["sequence"], "history/status mismatch")+ report = json.loads(run(label + "-register", "status", "--json"))+ effects.update(status=status, config=view, pcr=pcr, chain=report["tpm"]["chain"])+ effects = json.loads(json.dumps(effects))+ save(label, effects)+ return effects+++def changed(before, after, name):+ require(after["status"]["root_hash"] == root(name), "wrong selected root")+ require(after["status"]["sequence"] == before["status"]["sequence"] + 1,+ "activation did not add exactly one event")+ require(after["config"]["events"][:-1] == before["config"]["events"],+ "activation rewrote config history")+ event = after["config"]["events"][-1]+ digest = hashlib.sha256(b"shirudo-config-root-v1\0" ++ struct.pack(">I", 2) + bytes.fromhex(root(name))).digest()+ expected = hashlib.sha256(bytes.fromhex(before["pcr"]) + digest).hexdigest()+ require(event["kind"] == 2 and after["pcr"] == expected,+ "wrong live UPDATE measurement")+ require(before["pcr"] != after["pcr"], "PCR did not change")+ require(before["mount"] != after["mount"], "active mount did not change")+ require(before["runtime_mount"] == after["runtime_mount"],+ "runtime mount changed")+ require(before["chain"] == after["chain"], "upatch register changed")+++def main():+ mode = sys.argv[1]+ if mode == "initial":+ # Reusing a results directory starts a fresh session pin.+ (RESULTS / "anchor.json").unlink(missing_ok=True)+ require(root("config-a") != root("config-b"), "A/B fixtures are identical")+ snapshot("initial")+ elif mode == "builtin":+ before = snapshot("builtin-before")+ public = Path(os.environ["SHIRUDO_TEST_KEY_FIXTURES"])+ require((public / "builtin.der").read_bytes() !=+ (RUNTIME / "etc/shirudo/config-cert.der").read_bytes(),+ "built-in certificate duplicates the boot-enrolled config certificate")+ run("builtin-update", "image", "update", IMAGES / "config-builtin")+ changed(before, snapshot("builtin-after"), "config-builtin")+ elif mode in ("corrupt-data", "corrupt-hash", "corrupt-root", "corrupt-signature"):+ before = snapshot(mode + "-before")+ with tempfile.TemporaryDirectory(prefix="shirudo-image-") as directory:+ prefix = Path(directory) / "image"+ for suffix in (".img", ".verity", ".roothash", ".p7s"):+ shutil.copyfile(IMAGES / ("config-b" + suffix),+ prefix.with_suffix(suffix))+ suffix = {"corrupt-data": ".img", "corrupt-hash": ".verity",+ "corrupt-root": ".roothash", "corrupt-signature": ".p7s"}[mode]+ with prefix.with_suffix(suffix).open("r+b") as stream:+ stream.seek(-1, os.SEEK_END)+ value = stream.read(1)+ stream.seek(-1, os.SEEK_END)+ stream.write(bytes([value[0] ^ 1]))+ run(mode + "-update", "image", "update", prefix, success=False)+ after = snapshot(mode + "-after")+ differences = [key for key in before if before[key] != after[key]]+ require(not differences, f"{mode} changed state: {differences}")+ elif mode == "update":+ before = snapshot("before-a")+ if before["status"]["root_hash"] != root("config-a"):+ run("activate-a", "image", "update", IMAGES / "config-a")+ current = snapshot("a")+ changed(before, current, "config-a")+ before = current+ run("activate-b", "image", "update", IMAGES / "config-b")+ changed(before, snapshot("b"), "config-b")+ elif mode in ("malformed", "repeat"):+ before = snapshot(mode + "-before")+ require(before["status"]["root_hash"] == root("config-b"),+ "A to B test did not leave B active")+ name = "config-bad" if mode == "malformed" else "config-b"+ run(mode + "-update", "image", "update", IMAGES / name,+ success=mode == "repeat")+ after = snapshot(mode + "-after")+ differences = [key for key in before if before[key] != after[key]]+ require(not differences, f"{mode} changed state: {differences}")+ else:+ raise ValueError(mode)+++if __name__ == "__main__":+ main()diff --git a/testing/tamperproof/t1154-verity-config.sh b/testing/tamperproof/t1154-verity-config.shnew file mode 100755index 00000000..36b51d26--- /dev/null+++ b/testing/tamperproof/t1154-verity-config.sh@@ -0,0 +1,59 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++cd "$(dirname "$0")/.."+. ./integration-lib.sh+verity_required() {+ printf 'Bail out! %s\n' "$*" >&2+ exit 1+}+target_guard++mountpoint -q /run/shirudo/runtime && mountpoint -q /run/shirudo/config ||+ verity_required "dm-verity image mode is not active"+command -v python3 >/dev/null 2>&1 || verity_required "no python3"+for name in config-a config-b config-bad; do+ for suffix in img verity roothash p7s; do+ [ -r "/var/lib/shirudo/images/$name.$suffix" ] ||+ verity_required "missing signed CONFIG fixture: $name.$suffix"+ done+done++# This fixture changes CONFIG and leaves config-b active.+if [ -n "${SHIRUDO_TEST_CONFIG_RESULTS:-}" ]; then+ work=$SHIRUDO_TEST_CONFIG_RESULTS+ mkdir -p "$work"+else+ work=$(mktemp -d)+ trap 'rm -rf "$work"' EXIT HUP INT TERM+fi+export SHIRUDO_BIN++test_expect_success 'current CONFIG and direct PCR replay agree' '+ python3 tamperproof/t1154-verity-config.py initial "$work"+'++if [ -f "$SHIRUDO_TEST_KEY_FIXTURES/builtin.der" ]; then+ test_expect_success 'kernel built-in certificate accepts a signed config root' '+ python3 tamperproof/t1154-verity-config.py builtin "$work"+ '+else+ TAP_COUNT=$((TAP_COUNT + 1))+ printf 'ok %d - built-in config signer # SKIP kernel signing fixture unavailable\n' "$TAP_COUNT"+fi++test_expect_success 'unused data corruption fails before PCR or journal changes' '+ python3 tamperproof/t1154-verity-config.py corrupt-data "$work"+'++test_expect_success 'hash padding corruption fails before PCR or journal changes' '+ python3 tamperproof/t1154-verity-config.py corrupt-hash "$work"+'++test_expect_success 'kernel rejects a modified root or detached root signature' '+ python3 tamperproof/t1154-verity-config.py corrupt-root "$work" &&+ python3 tamperproof/t1154-verity-config.py corrupt-signature "$work"+'++test_done