eBPF-based security platform
Documentation: rework the manual into sections
Daniel Borkmann82d895086fe7
diff --git a/.github/scripts/build-commits.sh b/.github/scripts/build-commits.shindex 5e9875ba..682e1119 100755--- a/.github/scripts/build-commits.sh+++ b/.github/scripts/build-commits.sh@@ -4,9 +4,9 @@## .github/scripts/build-commits.sh -- build every commit in a range on its# own, oldest first, so that the history bisects as-# Documentation/contributing.rst asks: the binary, the shirudo-build helper-# and the test helpers. The first commit that does not build is named and-# the ones after it are not tried.+# Documentation/contribute/contributing.rst asks: the binary, the+# shirudo-build helper and the test helpers. The first commit that does+# not build is named and the ones after it are not tried.## .github/scripts/build-commits.sh [<rev-list arguments>]#diff --git a/.github/scripts/check-dco.sh b/.github/scripts/check-dco.shindex d11af21f..f5d822f0 100755--- a/.github/scripts/check-dco.sh+++ b/.github/scripts/check-dco.sh@@ -2,13 +2,13 @@# SPDX-License-Identifier: BSD-2-Clause# Copyright (c) 2026 Authors of shirudo#-# .github/scripts/check-dco.sh -- verify that every commit in a range has the-# message Documentation/contributing.rst asks for: a one-line subject, a-# body that says more than its tags, and the Signed-off-by of its author,-# the Developer's Certificate of Origin, from an identity a person answers-# at: a noreply address or a bot is no identity, as author, signer or-# co-developer. Merge commits are not signed in the kernel's process and-# are skipped.+# .github/scripts/check-dco.sh -- verify that every commit in a range has+# the message Documentation/contribute/contributing.rst asks for: a+# one-line subject, a body that says more than its tags, and the+# Signed-off-by of its author, the Developer's Certificate of Origin, from+# an identity a person answers at: a noreply address or a bot is no+# identity, as author, signer or co-developer. Merge commits are not+# signed in the kernel's process and are skipped.## .github/scripts/check-dco.sh [<rev-list arguments>]#diff --git a/.github/scripts/check-docs.sh b/.github/scripts/check-docs.shnew file mode 100755index 00000000..9a656268--- /dev/null+++ b/.github/scripts/check-docs.sh@@ -0,0 +1,112 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# .github/scripts/check-docs.sh -- check Documentation/ against the tree:+# every option a console example passes to shirudo exists in a parser,+# every failure category the code emits and every tamper counter has its+# entry in the reference, and every hook, counter, test and unit a page+# names exists.+#+# .github/scripts/check-docs.sh+#+# Runs from anywhere inside the checkout.++set -eu++cd "$(git rev-parse --show-toplevel)"++work=$(mktemp -d)+trap 'rm -rf "$work"' EXIT++# Loops on the right of a pipe run in subshells, so findings go to a file.+report() {+ printf '%s: %s\n' "$1" "$2" >>"$work/errors"+ if [ -n "${GITHUB_ACTIONS:-}" ]; then+ printf '::error file=%s::%s\n' "$1" "$2"+ fi+ printf '%s: %s\n' "$1" "$2" >&2+}++find Documentation -name '*.rst' -not -path 'Documentation/output*' \+ -not -path 'Documentation/contribute/coding-style.rst' | sort >"$work/pages"++# The options of the command lines in console blocks, by page.+while IFS= read -r page; do+ grep -E '^[[:space:]]+(operator\$|target#|\$|#) shirudo( |$)' "$page" |+ grep -oE -- '--[a-z0-9][a-z0-9-]*' | sort -u |+ sed "s|^|$page |"+done <"$work/pages" >"$work/options"++cat shirudo.c builtin-*.c tools/shirudo-build/*.c tools/gen-image/* \+ tools/gen-initrd/* >"$work/parsers"+while read -r page option; do+ grep -qF -- "\"$option" "$work/parsers" ||+ grep -qE -- "(^|[^a-z0-9-])$option([^a-z0-9-]|\$)" \+ tools/gen-image/* tools/gen-initrd/* ||+ report "$page" "no parser accepts $option"+done <"$work/options"++# Every failure category the code emits has an entry.+categories=Documentation/reference/failure-categories.rst+{+ grep -ohE 'rep_fail\([^,]+, "[a-z_]+", "[a-z_]+"' builtin-*.c util/*.c |+ sed -E 's/.*"([a-z_]+)"$/\1/'+ grep -ohE '(cat|category) = "[a-z_]+"' builtin-*.c util/*.c |+ sed -E 's/.*"([a-z_]+)"$/\1/'+ sed -n '/^static const char \*cat_from_load_errno/,/^}/p' builtin-upatch.c |+ grep -oE 'return "[a-z_]+"' | sed -E 's/.*"([a-z_]+)"$/\1/'+} | sort -u >"$work/categories"+while IFS= read -r category; do+ grep -qF "\`\`$category\`\`" "$categories" ||+ report "$categories" "no entry for the emitted category $category"+done <"$work/categories"++# Every tamper counter has an entry, and a page names no other.+counters=Documentation/security/tamper-counters.rst+grep -oE '= \{ "[A-Za-z]+",' util/tamper.c | sed -E 's/.*"([A-Za-z]+)".*/\1/' |+ sort -u >"$work/counters"+while IFS= read -r counter; do+ grep -qF "\`\`$counter\`\`" "$counters" ||+ report "$counters" "no entry for the counter $counter"+done <"$work/counters"++# The hooks, counters and tests a threat fact box names exist.+grep -ohE 'SEC\("lsm(\.s)?/[a-z_]+"\)' bpf/*.c bpf/*.h |+ sed -E 's/SEC\("lsm(\.s)?\/([a-z_]+)"\)/\2/' | sort -u >"$work/hooks"+while IFS= read -r page; do+ grep -E '^:(Enforced at|Counters|Tests):' "$page" >"$work/facts" || continue+ grep '^:Enforced at:' "$work/facts" | grep -oE '``(lsm/)?[a-z_]+``' |+ tr -d '`' | sed 's|^lsm/||' | sort -u | while IFS= read -r hook; do+ grep -qx "$hook" "$work/hooks" ||+ report "$page" "no BPF program attaches to $hook"+ done+ grep '^:Counters:' "$work/facts" | grep -oE '``[A-Za-z]+``' |+ tr -d '`' | sort -u | while IFS= read -r counter; do+ grep -qx "$counter" "$work/counters" ||+ report "$page" "no tamper counter is named $counter"+ done+done <"$work/pages"++# Every test id a page names exists under testing/.+find testing -name 't[0-9][0-9][0-9][0-9]-*' | sed -E 's|.*/(t[0-9]{4}).*|\1|' |+ sort -u >"$work/tests"+while IFS= read -r page; do+ grep -oE '``t[0-9]{4}[a-z0-9-]*``' "$page" | tr -d '`' | cut -c1-5 |+ sort -u | while IFS= read -r test; do+ grep -qx "$test" "$work/tests" ||+ report "$page" "no test is numbered $test"+ done+done <"$work/pages"++# Every unit a page names exists under systemd/.+while IFS= read -r page; do+ grep -oE 'shirudo(-[a-z0-9]+)*\.(service|timer)' "$page" | sort -u |+ while IFS= read -r unit; do+ [ -e "systemd/$unit" ] || [ -e "systemd/$unit.in" ] ||+ report "$page" "no unit is named $unit"+ done+done <"$work/pages"++printf 'docs: %s pages checked\n' "$(wc -l <"$work/pages")"+[ ! -s "$work/errors" ]diff --git a/.github/scripts/check-spdx.sh b/.github/scripts/check-spdx.shindex 3a03ddd6..8ac4c374 100755--- a/.github/scripts/check-spdx.sh+++ b/.github/scripts/check-spdx.sh@@ -39,7 +39,7 @@ report() {# generated from BTF.excluded() {case "$1" in- Documentation/coding-style.rst|vmlinux.h|*/vmlinux.h)+ Documentation/contribute/coding-style.rst|vmlinux.h|*/vmlinux.h)return 0 ;;esacreturn 1diff --git a/.github/scripts/check-style.sh b/.github/scripts/check-style.shindex acdc92a5..cff8ab6c 100755--- a/.github/scripts/check-style.sh+++ b/.github/scripts/check-style.sh@@ -310,12 +310,13 @@ check_spellings() {' "$1"}-# checkpatch enforces the kernel's block-comment form everywhere but at the-# opener, which only the netdev trees have an opinion on, and theirs is-# the opposite of Documentation/coding-style.rst: a comment that runs on-# past its first line opens with /* alone on that line. Report an added-# line that opens a comment with text and does not close it, in the form-# checkpatch reports in. String literals are blanked first.+# checkpatch enforces the kernel's block-comment form everywhere but at+# the opener, which only the netdev trees have an opinion on, and theirs+# is the opposite of Documentation/contribute/coding-style.rst: a comment+# that runs on past its first line opens with /* alone on that line.+# Report an added line that opens a comment with text and does not close+# it, in the form checkpatch reports in. String literals are blanked+# first.check_block_comments() {awk '/^\+\+\+ / { file = $0; sub(/^\+\+\+ b\//, "", file); next }diff --git a/.github/workflows/build-commits.yml b/.github/workflows/build-commits.ymlindex f948567e..3016f1f4 100644--- a/.github/workflows/build-commits.yml+++ b/.github/workflows/build-commits.yml@@ -23,9 +23,9 @@ jobs:with:fetch-depth: 0- # Documentation/contributing.rst asks for every commit to build on- # its own, so that the history bisects; the other workflows build- # the head of the pull request alone. The BPF objects need the BTF+ # Documentation/contribute/contributing.rst asks for every commit to+ # build on its own, so that the history bisects; the other workflows+ # build the head of the pull request alone. The BPF objects need the BTF# of a signed-BPF capable bpf-next kernel, so the builds run in the# same LVH VM as the package build. The guest does not inherit the# runner's environment; GITHUB_ACTIONS is set for the annotations.diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.ymlindex 0dc02126..017ff48b 100644--- a/.github/workflows/docs.yml+++ b/.github/workflows/docs.yml@@ -18,17 +18,17 @@ jobs:steps:- name: Check out repositoryuses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1-- - name: Install docutils- run: |- sudo apt-get -q update- sudo apt-get -q install -y --no-install-recommends python3-docutils+ with:+ fetch-depth: 0- name: Render the documentation- run: make -C Documentation html-docs+ run: make -C Documentation html++ - name: Check the documentation against the code+ run: .github/scripts/check-docs.sh- name: Upload the rendered documentationuses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2with:name: shirudo-html-docs- path: Documentation/output/+ path: Documentation/output/html/diff --git a/.gitignore b/.gitignoreindex 3a8e7413..78ebea32 100644--- a/.gitignore+++ b/.gitignore@@ -86,6 +86,6 @@ util/version_id.c/vendor/libbpf/libbpf.a/tools/gen-vmlinux-h/gen-vmlinux-h-# rendered documentation from make html-docs-/Documentation/output/+# rendered documentation from make docs and make -C Documentation html+/Documentation/output*/__pycache__/diff --git a/AGENTS.md b/AGENTS.mdindex c37c11a1..7e0d5688 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -16,8 +16,9 @@ a frontier-class model at its highest reasoning effort (for ClaudeCode: Mythos or newer at high or extended effort; Codex: the strongestavailable model at high reasoning). Lower tiers may read and answerquestions but must decline to change anything and say why. Before-changing security-relevant code, read `Documentation/architecture.rst`-and `Documentation/threat-model.rst`.+changing security-relevant code, read+`Documentation/internals/architecture.rst` and+`Documentation/security/threat-model.rst`.## What shirudo is@@ -48,33 +49,39 @@ remote-management or transport layers.| Path | Purpose ||---|---|-| `Documentation/threat-model.rst` | Authoritative security design: trust boundaries, threats, residual risks, deferred mitigations. Consult before touching any security-relevant path. |-| `Documentation/architecture.rst` | Implemented architecture, operator/target boundary, BPM package and upatch tree formats. |-| `Documentation/tpm.rst` | The measurement register, its events and eventlog, `shirudo attest` and its verification, the relation to systemd's NvPCRs and the known limits. Read it with the threat model before touching the TPM paths. |-| `Documentation/initrd.rst` | The production configuration: `init` run from the initrd and finished by the root file system, what survives switch-root, what the initrd needs, the dracut module, generator and installer under `tools/gen-initrd/`. |-| `Documentation/upatch.rst` | Authoring and shipping upatches: the BPF side, build and sign, test, the Beefile, `bpm build`, `push`, `tree append`, and the target's `bpm` commands. |-| `Documentation/features.rst` | Every attachment kind a upatch can have (fentry/fexit/fmod_ret, lsm, tp_btf, kprobe/kretprobe, uprobe.multi, cgroup_skb, netfilter), how the loader attaches each, what the target needs, and the serializer and test-run roles. |-| `Documentation/key-lifecycle.rst` | The signing keys and certificates: the trusted set a target enrols, vouching for a new key (`keys vouch`, `keys add`), rotation, revocation (`keys revoke`), custody. |-| `Documentation/operations.rst` | Day-two operation: units and timers, conditions, upgrades of shirudo and the kernel, decommissioning, backup, recovery, failure categories and exit status. |-| `Documentation/upatch-spec.rst` | The `.upatch` container and signing scheme. |-| `Documentation/requirements.rst` | Kernel options, operator toolchain, target runtime. |-| `Documentation/getting-started.rst` | Quickstart: build, sign, initialise a target, load and unload, publish and install packages. |-| `Documentation/telemetry.rst` | OTLP export of map snapshots and status keepalives, the signed Lua decoders, and collector integration (OpenTelemetry Collector, ClickHouse, Splunk, custom). |-| `Documentation/developer-guide.rst` | Working from a checkout, the operator-only tools, the test tiers (unit, functional, end-to-end), the test numbers, running the tests and the test VM. Read it before adding or moving a test. |-| `Documentation/coding-style.rst` | The kernel's coding style, applied to all C here. |-| `Documentation/contributing.rst` | Commit message form, the mandatory `Signed-off-by:` and the kernel's attribution tags. Read it before crafting a commit. |+| `Documentation/security/threat-model.rst` | Authoritative security design: assumptions, assets, trust boundaries, adversaries, threats with the hooks, counters and tests behind each, residual risks, threats to resolve, deferred mitigations. Consult before touching any security-relevant path. |+| `Documentation/internals/` | How shirudo works and why: architecture, signed loader path, enforcement in the kernel (every LSM hook), seal labels and task marks, boot from initrd to root, measurement register and attestation, config images, kernel interfaces, carried kernel patches, design decisions. Read the page for a mechanism before changing it. |+| `Documentation/concepts/` | The concepts and the background mechanisms shirudo builds on (BPF, CO-RE, BPF signing, the BPF LSM, keyrings, xattrs, dm-verity, initrd, boot, TPM, post-quantum cryptography, OCI, OpenTelemetry, LuaJIT) and the glossary. |+| `Documentation/start/` | Quickstart, installation and short guides. |+| `Documentation/operate/` | Operator how-tos: system requirements, deployment, boot integration, keys, attestation, reading status, telemetry, upgrades, recovery, troubleshooting, incident response, hardening. |+| `Documentation/upatches/` | Authoring and shipping upatches: attach kinds, maps and serializers, decoders, the Beefile, publishing, debugging a failed load. |+| `Documentation/reference/` | Every command (`reference/cli/`), the formats and settings (`reference/formats/`, including the `.upatch` container), failure categories and exit status, files, units, environment variables, the cheat sheet. |+| `Documentation/contribute/` | Developer guide, test tiers and the test VM (read `testing.rst` before adding or moving a test), test coverage, the kernel coding style, commits and sign-off (read `contributing.rst` before crafting a commit), and the documentation style guide `writing-docs.rst`. |The kernel side of the signing design is the kernel's own`Documentation/bpf/signing.rst`; `bpf_prog_verify_signature()` runs-before the LSM hooks and `attr.keyring_id` is a key serial, not a name.+inside the verifier, after the `bpf` LSM hook and before the+`bpf_prog_load` one, and `attr.keyring_id` is a key serial, not a name.-New documentation extends `Documentation/`, an existing document or a new-one listed above and in `Documentation/index.rst`. Only what concerns the-project as a whole goes in the top-level directory (`README.md`,-`CONTRIBUTING.md`, `SECURITY.md` and their kind). No README, plan or notes-file goes beside the code; the exceptions are `vendor/libbpf/README.md`,-which belongs to the vendored copy, and a package's `README.md` under-`upatches/`, which `bpm build` ships in the package for `bpm info`.+The documentation is kept in sync with the code. A change to behavior+updates the pages that describe it in the same commit: a command, an+option, a message, an exit status, a failure category, a tamper+counter, an LSM hook, a file, a unit, a format, a threat or a test+that is added, changed or removed is added, changed or removed in+`Documentation/` too, and a residual risk or threat to resolve that a+change closes leaves the threat model. A page that no longer matches+the code is a bug, whichever of the two is wrong.+`.github/scripts/check-docs.sh` catches the names it can; the prose is+the author's to check.++New documentation extends an existing page or adds one to its section's+toctree, and follows `Documentation/contribute/writing-docs.rst`. Only+what concerns the project as a whole goes in the top-level directory+(`README.md`, `CONTRIBUTING.md`, `SECURITY.md` and their kind). No+README, plan or notes file goes beside the code; the exceptions are+`vendor/libbpf/README.md`, which belongs to the vendored copy, and a+package's `README.md` under `upatches/`, which `bpm build` ships in the+package for `bpm info`.## Coding conventions@@ -121,10 +128,11 @@ which belongs to the vendored copy, and a package's `README.md` underdescending line length; a declaration whose initializer references anearlier local must stay after it (correctness wins over the sort).Apply this whenever you add or touch a declaration block.-- **Linux kernel coding style** (`Documentation/coding-style.rst` —- the kernel's own coding-style.rst, copied into this tree). Tabs- (8-wide), 80-col soft limit and 100-col hard limit (checkpatch),- K&R braces, no spaces inside parens.+- **Linux kernel coding style**+ (`Documentation/contribute/coding-style.rst` — the kernel's own+ coding-style.rst, copied into this tree). Tabs (8-wide), 80-col soft+ limit and 100-col hard limit (checkpatch), K&R braces, no spaces+ inside parens.Apply to userspace too — eases review. **Comments are rare andfollow §8** (see below): at the function head, not inside thebody; file headers are SPDX + Copyright + at most one line of@@ -147,7 +155,7 @@ which belongs to the vendored copy, and a package's `README.md` underThis applies to every block comment — function-head doc comments,TODO blocks, struct-internal explanations, multi-line trailingcomments inside a function body. The rule mirrors the kernel- example in `Documentation/coding-style.rst` §8.+ example in `Documentation/contribute/coding-style.rst` §8.- **`//` is for SPDX only.** Per the kernel convention, .c filesuse `// SPDX-License-Identifier: …` and nothing else `//`-style;.h files use `/* SPDX-License-Identifier: … */` and nothing else@@ -169,16 +177,16 @@ which belongs to the vendored copy, and a package's `README.md` under## Commits-`Documentation/contributing.rst` is the kernel's process applied here-and is the reference for every commit an agent prepares: a subject of-the form `area: imperative summary`, a body that explains why before-what, and the `Co-developed-by`, `Fixes`, `Reported-by`, `Suggested-by`,-`Tested-by`, `Reviewed-by`, `Acked-by` and `Cc` tags used as the kernel-uses them. Every commit needs a `Signed-off-by:` from a real identity,-and only a person can give one: an agent never adds a sign-off, on its-own or anyone else's behalf, and leaves that line to the human who-reviews and submits the work. One logical change per commit, each one-building and passing on its own.+`Documentation/contribute/contributing.rst` is the kernel's process+applied here and is the reference for every commit an agent prepares: a+subject of the form `area: imperative summary`, a body that explains why+before what, and the `Co-developed-by`, `Fixes`, `Reported-by`,+`Suggested-by`, `Tested-by`, `Reviewed-by`, `Acked-by` and `Cc` tags+used as the kernel uses them. Every commit needs a `Signed-off-by:` from+a real identity, and only a person can give one: an agent never adds a+sign-off, on its own or anyone else's behalf, and leaves that line to+the human who reviews and submits the work. One logical change per+commit, each one building and passing on its own.## Invariants that are easy to break@@ -281,14 +289,15 @@ one usually still compiles and passes tests.- **Kernel + shirudo is the target TCB.** Ask of every change whether itgrows the TCB; the agentless design exists to keep it minimal.- **Bleeding-edge kernel and toolchain only.** The signed-loader ABI- described in `Documentation/requirements.rst` and current clang/LLVM are- hard prerequisites. Development trees can expose that ABI before the- corresponding release number changes; use a verified commit, not just- `uname`, to identify the tested kernel. No legacy-kernel fallback paths;- a missing kernel feature fails the build or the load. x86-64, arm64 and- riscv64 are the supported architectures.+ described in `Documentation/operate/system-requirements.rst` and+ current clang/LLVM are hard prerequisites. Development trees can+ expose that ABI before the corresponding release number changes; use a+ verified commit, not just `uname`, to identify the tested kernel. No+ legacy-kernel fallback paths; a missing kernel feature fails the build+ or the load. x86-64, arm64 and riscv64 are the supported architectures.- **BPF is CO-RE.** Hard-coded struct offsets sign fine and fail on the- wrong kernel as `btf_mismatch`.+ wrong kernel, where the verifier rejects the payload+ (`verifier_rejected`).- **Upatch state lives in BPF arenas where possible.** A upatch thataccumulates records keeps them in its one `BPF_MAP_TYPE_ARENA` map andships a `shirudo_serialize__<map>` program that walks them; hash and@@ -357,14 +366,20 @@ one usually still compiles and passes tests.- `util/<m>.c` is unit tested by `testing/unit/<m>.c`: a change to a utilfunction adds or updates its cases there. A shell test is named`t<F><K><NN>`, family, operator (0) or target (1), and order, and lives in- its family's directory; `Documentation/developer-guide.rst` has the families.+ its family's directory; `Documentation/contribute/testing.rst` has the+ families.- `make -C testing fuzz [FUZZ_SECONDS=60]` runs the libFuzzer targets in`testing/fuzz/` for the parsers of input from outside the host, underASan and UBSan, on their seed corpora; CI runs them too. A parser thattakes such input gets a target there.-- `make -C Documentation html-docs` renders `Documentation/*.rst` with docutils in strict- mode into `Documentation/output/`; CI runs it on every push, so run it- after touching any document (python3-docutils provides `rst2html`).+- `make docs` renders the documentation with Sphinx in a container and+ serves it on 127.0.0.1:8000. `make -C Documentation check` renders it+ with every warning an error and runs `.github/scripts/check-docs.sh`,+ which checks the options, failure categories, tamper counters, hooks,+ tests and units the pages name against the tree. CI runs both on every+ push, so run the check after touching a document or one of those names+ in the code. It needs podman or docker; `DOCS_CONTAINER=0` uses a host+ Sphinx installed from `Documentation/requirements.txt`.- `.github/scripts/check-spdx.sh` checks the SPDX tag of every trackedsource against the licensing rules above: the form for the file type,the expression, the dual licence for everything a BPF object compiles@@ -405,5 +420,5 @@ Do not propose features in these areas; the design delegates them:dm-verity, measured boot.- Kernel hardening and TPM hardware attacks: trusted components.-Deferred work that is in scope is listed under deferred mitigations in-`Documentation/threat-model.rst`.+Deferred work that is in scope is listed under deferred mitigations and+threats to resolve in `Documentation/security/threat-model.rst`.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 9a9a8c80..73763936 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1,3 +1,3 @@# Contributing-Thanks for your interest in contributing to shirudo. Please see the [contribution guide](Documentation/contributing.rst) for instructions.+Thanks for your interest in contributing to shirudo. Please see the [contribution guide](Documentation/contribute/contributing.rst) for instructions.diff --git a/Documentation/Containerfile b/Documentation/Containerfilenew file mode 100644index 00000000..e5de8fa1--- /dev/null+++ b/Documentation/Containerfile@@ -0,0 +1,13 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# The documentation toolchain: Sphinx and MyST from requirements.txt, by+# hash, on a base image pinned by digest. Builds and serves the HTML.++FROM docker.io/library/python:3.12-slim-bookworm@sha256:e697c81897302a4c4333bade000d98038fbb21eb064f8ee1fd42d02ebcd9d337++COPY requirements.txt /tmp/requirements.txt+RUN pip install --no-cache-dir --no-deps --require-hashes \+ -r /tmp/requirements.txt && rm /tmp/requirements.txt++ENV PYTHONDONTWRITEBYTECODE=1 HOME=/tmpdiff --git a/Documentation/Makefile b/Documentation/Makefileindex 6c61e1da..6977bbb9 100644--- a/Documentation/Makefile+++ b/Documentation/Makefile@@ -1,9 +1,10 @@# SPDX-License-Identifier: BSD-2-Clause# Copyright (c) 2026 Authors of shirudo#-# Documentation rendering. Run with make -C Documentation html-docs.+# Documentation: Sphinx in a container, or on the host with DOCS_CONTAINER=0.ROOT := $(abspath $(dir $(lastword $(MAKEFILE_LIST)))/..)+DOCS := $(ROOT)/DocumentationMAKEFLAGS += -rR --no-print-directoryifeq ($(V),1)@@ -13,37 +14,103 @@ elseendifexport Q V-root-path = $(if $(filter /%,$(1)),$(1),$(ROOT)/$(1)).DEFAULT_GOAL := help-RST2HTML ?= rst2html-DOCS_HTML_DIR ?= output-DOCS_RST := $(sort $(wildcard *.rst))--.PHONY: help clean html-docs--# Render every document with docutils and fail on anything it reports, so a-# Sphinx-only role, a duplicate link target or a mis-parsed table breaks the-# build rather than the rendered page. coding-style.rst is the kernel's text-# verbatim; its restarted enumerated list is an informational note that is not-# ours to fix, so that one file halts at warnings instead.-html-docs:- $(Q)command -v $(RST2HTML) >/dev/null 2>&1 || { \- printf 'shirudo: %s not found; install python3-docutils\n' '$(RST2HTML)' >&2; \- exit 1; }- $(Q)mkdir -p $(DOCS_HTML_DIR)- $(Q)for f in $(DOCS_RST); do \- out=$(DOCS_HTML_DIR)/$$(basename $$f .rst).html; \- case $$f in \- coding-style.rst) halt=--halt=warning ;; \- *) halt=--strict ;; \- esac; \- printf ' HTML %s\n' "$$out"; \- $(RST2HTML) $$halt --no-generator "$$f" > "$$out" || { \- rm -f "$$out"; exit 1; }; \- done++DOCS_OUT ?= $(DOCS)/output+DOCS_PORT ?= 8000+DOCS_BIND ?= 127.0.0.1+DOCS_CONTAINER ?= 1+CONTAINER ?= $(shell command -v podman 2>/dev/null || command -v docker 2>/dev/null)+SPHINXBUILD ?= sphinx-build+SPHINXOPTS ?= -W --keep-going -n -q++OUT := $(abspath $(DOCS_OUT))+IMAGE := shirudo-docs:$(shell cat $(DOCS)/Containerfile $(DOCS)/requirements.txt | \+ sha256sum | cut -c1-16)++# The build sees the tree read-only and no network; the server sees only+# the rendered pages, read-only, as nobody, published on DOCS_BIND alone.+RUN_BUILD = $(CONTAINER) run --rm --network=none --read-only --tmpfs /tmp \+ --user "$$(id -u):$$(id -g)" -e DOCS_LASTCHANGE=/out/lastchange.txt \+ -v "$(ROOT):/src:ro" -v "$(OUT):/out" $(IMAGE)+RUN_SERVE = $(CONTAINER) run --rm --init --read-only --cap-drop=ALL \+ --security-opt=no-new-privileges --user 65534:65534 \+ -p "$(DOCS_BIND):$(DOCS_PORT):8000" -v "$(OUT)/html:/srv:ro" $(IMAGE)++.PHONY: help container-check image lastchange html html-docs serve check \+ linkcheck cleanhelp:- @printf '%s\n' 'make -C Documentation html-docs'+ @printf '%s\n' \+ 'make -C Documentation html render the HTML into $(DOCS_OUT)/html' \+ 'make -C Documentation serve render, then serve it on $(DOCS_BIND):$(DOCS_PORT)' \+ 'make -C Documentation check render, then check the docs against the code' \+ 'make -C Documentation linkcheck check external links (needs the network)' \+ 'DOCS_CONTAINER=0 renders with the host sphinx-build from requirements.txt.'++container-check:+ $(Q)[ -n "$(CONTAINER)" ] || { \+ printf 'shirudo: no podman or docker; use DOCS_CONTAINER=0 with %s\n' \+ 'the packages in Documentation/requirements.txt' >&2; \+ exit 1; }++# Built from a context holding only what the Containerfile copies, and+# tagged by the hash of both files so a change rebuilds it.+image: container-check+ $(Q)$(CONTAINER) image inspect $(IMAGE) >/dev/null 2>&1 || { \+ ctx="$(OUT)/.image" && rm -rf "$$ctx" && mkdir -p "$$ctx" && \+ cp $(DOCS)/Containerfile $(DOCS)/requirements.txt "$$ctx" && \+ printf ' IMAGE %s\n' '$(IMAGE)' && \+ $(CONTAINER) build -q -t $(IMAGE) -f "$$ctx/Containerfile" "$$ctx" \+ >/dev/null && rm -rf "$$ctx"; }++# The commit that last changed each document and when, in UTC, for the+# page footers.+lastchange:+ $(Q)mkdir -p "$(OUT)"+ $(Q)if git -C $(ROOT) rev-parse --git-dir >/dev/null 2>&1; then \+ TZ=UTC git -C $(ROOT) log --date=format-local:'%Y-%m-%d %H:%M' \+ --format='@%h%x09%cd' --name-only -- Documentation | \+ awk '/^@/ { c = substr($$0, 2); next } \+ NF && !($$0 in s) { s[$$0] = c; print $$0 "\t" c }' \+ >"$(OUT)/lastchange.txt"; \+ else \+ : >"$(OUT)/lastchange.txt"; \+ fi++# The plain-text pages under _text/ are what "View as text", "Copy page"+# and llms.txt point to, for readers that are agents.+ifeq ($(DOCS_CONTAINER),1)+html: image lastchange+ $(Q)printf ' HTML %s\n' '$(DOCS_OUT)/html'+ $(Q)$(RUN_BUILD) sphinx-build $(SPHINXOPTS) -b html -d /out/doctrees \+ /src/Documentation /out/html+ $(Q)$(RUN_BUILD) sphinx-build $(SPHINXOPTS) -b text -d /out/doctrees \+ /src/Documentation /out/html/_text+else+html: lastchange+ $(Q)printf ' HTML %s\n' '$(DOCS_OUT)/html'+ $(Q)DOCS_LASTCHANGE="$(OUT)/lastchange.txt" $(SPHINXBUILD) $(SPHINXOPTS) \+ -b html -d "$(OUT)/doctrees" $(DOCS) "$(OUT)/html"+ $(Q)$(SPHINXBUILD) $(SPHINXOPTS) -b text -d "$(OUT)/doctrees" $(DOCS) \+ "$(OUT)/html/_text"+endif++html-docs: html++serve: html+ @printf 'shirudo: serving http://%s:%s/ (Ctrl-C stops it)\n' \+ '$(DOCS_BIND)' '$(DOCS_PORT)'+ $(Q)$(RUN_SERVE) python3 -m http.server --directory /srv --bind 0.0.0.0 8000++check: html+ $(Q)$(ROOT)/.github/scripts/check-docs.sh++linkcheck: image+ $(Q)$(CONTAINER) run --rm --read-only --tmpfs /tmp --user "$$(id -u):$$(id -g)" \+ -v "$(ROOT):/src:ro" -v "$(OUT):/out" $(IMAGE) \+ sphinx-build -q -b linkcheck -d /out/doctrees /src/Documentation \+ /out/linkcheckclean:- $(Q)rm -rf "$(DOCS_HTML_DIR)"+ $(Q)rm -rf "$(OUT)"diff --git a/Documentation/_ext/shirudo_docs.py b/Documentation/_ext/shirudo_docs.pynew file mode 100644index 00000000..0a005491--- /dev/null+++ b/Documentation/_ext/shirudo_docs.py@@ -0,0 +1,129 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# Sphinx extension for the shirudo documentation: the page type and+# reader line under each title, the source and last change in the page+# footer, and console blocks whose prompts name the role a command runs in.++import os++from docutils import nodes+from pygments.lexer import RegexLexer, bygroups, default, using+from pygments.lexers.shell import BashLexer+from pygments.token import Generic, Whitespace+++# "operator$ " runs on the operator host, "target# " as root on a target,+# "$ " and "# " anywhere. A backslash at the end continues the command.+class ConsoleLexer(RegexLexer):++ name = "shirudo console"+ aliases = ["console", "shell-session"]+ tokens = {+ "root": [+ (r"^(operator\$|target#|\$|#)( )",+ bygroups(Generic.Prompt, Whitespace), "command"),+ (r"[^\n]*\n", Generic.Output),+ (r"[^\n]+", Generic.Output),+ ],+ "command": [+ (r"[^\n]*\\\n", using(BashLexer)),+ (r"[^\n]*\n", using(BashLexer), "#pop"),+ (r"[^\n]+", using(BashLexer), "#pop"),+ default("#pop"),+ ],+ }+++def meta_line(app, doctree, docname):+ meta = app.env.metadata.get(docname, {})+ parts = [meta.get(key) for key in ("page-type", "audience")]+ parts = [part for part in parts if part]+ if not parts:+ return+ for section in doctree.findall(nodes.section):+ title = section.next_node(nodes.title)+ if title is not None:+ line = nodes.paragraph("", " · ".join(parts), classes=["meta"])+ title.parent.insert(title.parent.index(title) + 1, line)+ return+++CHANGES = {}+++def last_changes():+ path = os.environ.get("DOCS_LASTCHANGE")+ changes = {}+ if not path or not os.path.exists(path):+ return changes+ with open(path, encoding="utf-8") as stream:+ for line in stream:+ fields = line.rstrip("\n").split("\t")+ if len(fields) == 3 and fields[0]:+ changes[fields[0]] = (fields[1], fields[2])+ return changes+++def page_context(app, pagename, templatename, context, doctree):+ if doctree is None:+ return+ source = "Documentation/" + pagename + ".rst"+ context["source_file"] = source+ context["last_change"], context["last_change_date"] = \+ CHANGES.get(source, (None, None))+ context["edit_url"] = "%s/blob/%s/%s" % (+ context.get("repository"), context.get("branch"), source)+++def first_paragraph(doctree, limit=300):+ for para in doctree.findall(nodes.paragraph):+ if "meta" in para.get("classes", []):+ continue+ text = " ".join(para.astext().split())+ if len(text) > limit:+ cut = text.rfind(". ", 0, limit)+ text = text[:cut + 1] if cut > 0 else text[:limit] + "..."+ return text+ return ""+++def toctree_walk(env, docname):+ yield docname+ for child in env.toctree_includes.get(docname, []):+ yield from toctree_walk(env, child)+++# llms.txt: an index of the plain-text pages for readers that are agents.+def write_llms(app, exception):+ if exception is not None or app.builder.name != "html":+ return+ env = app.env+ root = app.config.root_doc+ lines = ["# shirudo documentation", ""]+ intro = first_paragraph(env.get_doctree(root), 1000)+ if intro:+ lines += ["> " + intro, ""]+ lines += ["Every page below is plain text; the HTML version has the "+ "same path without _text/ and with .html.", ""]+ for section in env.toctree_includes.get(root, []):+ lines += ["## " + env.titles[section].astext(), ""]+ for docname in toctree_walk(env, section):+ title = env.titles[docname].astext()+ desc = first_paragraph(env.get_doctree(docname))+ entry = "- [%s](_text/%s.txt)" % (title, docname)+ lines.append(entry + (": " + desc if desc else ""))+ lines.append("")+ path = os.path.join(app.outdir, "llms.txt")+ with open(path, "w", encoding="utf-8") as stream:+ stream.write("\n".join(lines))+++def setup(app):+ app.add_lexer("console", ConsoleLexer)+ app.add_lexer("shell-session", ConsoleLexer)+ CHANGES.update(last_changes())+ app.connect("doctree-resolved", meta_line)+ app.connect("html-page-context", page_context)+ app.connect("build-finished", write_llms)+ return {"parallel_read_safe": True, "parallel_write_safe": True}diff --git a/Documentation/_themes/shirudo/favicon.svg b/Documentation/_themes/shirudo/favicon.svgnew file mode 100644index 00000000..dfa03417--- /dev/null+++ b/Documentation/_themes/shirudo/favicon.svg@@ -0,0 +1,7 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 420 448" width="420" height="448">+<style>path, rect { fill: #000; } @media (prefers-color-scheme: dark) { path, rect { fill: #fff; } }</style>+<path d="M420 323.382C417.671 392.229 324.579 447.606 210.07 447.606C169.946 447.606 132.447 440.8 100.563 429.002C156.118 407.482 197.109 369.084 210.211 323.382V319.437H420V323.382Z"/>+<rect x="210.986" width="209.014" height="118.31"/>+<path d="M0 0L210.986 118.31V205.07H0V0Z"/>+<rect y="205.07" width="420" height="118.31"/>+</svg>diff --git a/Documentation/_themes/shirudo/layout.html b/Documentation/_themes/shirudo/layout.htmlnew file mode 100644index 00000000..12a03b11--- /dev/null+++ b/Documentation/_themes/shirudo/layout.html@@ -0,0 +1,84 @@+{#- SPDX-License-Identifier: BSD-2-Clause -#}+{#- Copyright (c) 2026 Authors of shirudo -#}+{%- extends "basic/layout.html" %}++{%- block htmltitle %}+<title>{% if pagename == root_doc %}shirudo documentation{% else %}{{ title|striptags|e }} · shirudo docs{% endif %}</title>+{%- endblock %}++{%- block extrahead %}+<meta name="viewport" content="width=device-width, initial-scale=1">+<script src="{{ pathto('_static/shirudo.js', 1) }}" defer></script>+{%- endblock %}++{%- block relbar1 %}{% endblock %}+{%- block relbar2 %}{% endblock %}++{%- block header %}+<header class="bar">+ <div class="bar-in">+ <a class="brand" href="{{ pathto(root_doc) }}" aria-label="shirudo documentation home">+ <img class="logo" src="{{ pathto('_static/shirudo-horizontal-for-light-back.svg', 1) }}" alt="shirudo">+ <img class="logo on-dark" src="{{ pathto('_static/shirudo-horizontal-for-dark-back.svg', 1) }}" alt="shirudo">+ <span>docs</span>+ </a>+ <div class="tools">+ <form class="search" action="{{ pathto('search') }}" method="get" role="search">+ <input type="search" name="q" placeholder="Search docs" aria-label="Search the documentation">+ <kbd>/</kbd>+ </form>+ <a class="gh" href="{{ repository }}">GitHub</a>+ </div>+ </div>+</header>+{%- endblock %}++{%- block content %}+<div class="shell">+ <nav class="side" aria-label="Documentation">+ <button class="menu-toggle" type="button" aria-expanded="false">Menu</button>+ <div class="tree">+ {{ toctree(collapse=False, includehidden=True, titles_only=True, maxdepth=-1) }}+ </div>+ </nav>+ <main>+ <div class="pagebar">+ <div class="crumbs">+ {%- if pagename != root_doc %}+ <a href="{{ pathto(root_doc) }}">Docs</a>+ {%- for parent in parents %}+ <a href="{{ parent.link|e }}">{{ parent.title }}</a>+ {%- endfor %}+ <span>{{ title|striptags|e }}</span>+ {%- endif %}+ </div>+ {%- if source_file %}+ <div class="pageactions">+ <button type="button" class="copy-page" data-src="{{ pathto('_text/' + pagename + '.txt', 1) }}">Copy page</button>+ <a href="{{ pathto('_text/' + pagename + '.txt', 1) }}">View as text</a>+ </div>+ {%- endif %}+ </div>+ <article class="body" role="main">+ {% block body %}{% endblock %}+ </article>+ {%- if source_file %}+ <footer class="pfoot">+ <span>Source: <code>{{ source_file }}</code></span>+ {%- if last_change %}+ <span>Last change: <code>{{ last_change }}</code>, {{ last_change_date }} UTC</span>+ {%- endif %}+ <a href="{{ edit_url }}">Edit this page on GitHub</a>+ </footer>+ {%- endif %}+ </main>+ <nav class="toc" aria-label="On this page">+ {%- if display_toc %}+ <h2>On this page</h2>+ {{ toc }}+ {%- endif %}+ </nav>+</div>+{%- endblock %}++{%- block footer %}{% endblock %}diff --git a/Documentation/_themes/shirudo/static/shirudo.css b/Documentation/_themes/shirudo/static/shirudo.cssnew file mode 100644index 00000000..e65106eb--- /dev/null+++ b/Documentation/_themes/shirudo/static/shirudo.css@@ -0,0 +1,224 @@+/* SPDX-License-Identifier: BSD-2-Clause */+/* Copyright (c) 2026 Authors of shirudo */++@import url("basic.css");++:root {+ --bar: #000;+ --bar-fg: #b4bcc7;+ --bar-hi: #fff;+ --bar-dim: #7d8693;+ --bar-field: #15181d;+ --bar-line: #2a2f37;+ --logo-light-back: none;+ --logo-dark-back: block;++ --bg: #fff;+ --soft: #f4f6f8;+ --fg: #171b22;+ --muted: #5d6675;+ --line: #e2e6eb;+ --accent: #8b1e3f;+ --accent-soft: #f8ecf0;++ --code-bg: #0d1117;+ --code-fg: #e3e8ee;+ --p-op: #7fc3ec;+ --p-tg: #efb35c;+ --p-dim: #7a8594;++ --warn-bg: #fff7e6;+ --warn-line: #ecc77a;+ --stop-bg: #fdf0ef;+ --stop-line: #ebb0aa;++ --sans: "IBM Plex Sans", system-ui, -apple-system, "Segoe UI", Roboto,+ "Helvetica Neue", Arial, sans-serif;+ --mono: "IBM Plex Mono", ui-monospace, "SFMono-Regular", "DejaVu Sans Mono",+ Menlo, Consolas, monospace;+}++@media (prefers-color-scheme: dark) {+ :root {+ --bar: #fff;+ --bar-fg: #5d6675;+ --bar-hi: #171b22;+ --bar-dim: #8a93a0;+ --bar-field: #f4f6f8;+ --bar-line: #e2e6eb;+ --logo-light-back: block;+ --logo-dark-back: none;+ --bg: #0e1116;+ --soft: #161b22;+ --fg: #e4e8ee;+ --muted: #9ba5b3;+ --line: #262d37;+ --accent: #e8899f;+ --accent-soft: #3a1b25;+ --code-bg: #080a0d;+ --warn-bg: #261f10;+ --warn-line: #6e5520;+ --stop-bg: #2a1614;+ --stop-line: #6f2e28;+ color-scheme: dark;+ }+}++* { box-sizing: border-box; }+html { scroll-padding-top: 72px; }+body { margin: 0; background: var(--bg); color: var(--fg); font: 400 15px/1.65 var(--sans); }+a, a:visited { color: var(--accent); text-decoration: none; }+a:hover { text-decoration: underline; }+a:focus-visible, button:focus-visible, input:focus-visible {+ outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 3px;+}+code, pre, kbd { font-family: var(--mono); }+code.literal { font-size: 0.9em; background: none; padding: 0; }++/* top bar */+.bar { position: sticky; top: 0; z-index: 20; background: var(--bar); border-bottom: 1px solid var(--bar-line); }+.bar-in { display: flex; align-items: center; gap: 24px; height: 56px; padding: 0 20px; }+.brand { display: flex; align-items: center; gap: 10px; color: var(--bar-hi); flex: none; }+.brand:hover { text-decoration: none; }+.brand .logo { height: 21px; width: auto; display: var(--logo-light-back); }+.brand .logo.on-dark { display: var(--logo-dark-back); }+.brand span { font: 500 13px var(--mono); color: var(--bar-fg); padding-left: 10px; border-left: 1px solid var(--bar-line); }+.tools { margin-left: auto; display: flex; align-items: center; gap: 18px; }+.search { position: relative; margin: 0; }+.search input { width: 260px; background: var(--bar-field); border: 1px solid var(--bar-line); color: var(--bar-hi); border-radius: 6px; padding: 6px 30px 6px 10px; font: 400 13px var(--sans); }+.search input::placeholder { color: var(--bar-dim); }+.search kbd { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); font-size: 11px; color: var(--bar-dim); }+.gh { color: var(--bar-fg); font-size: 13.5px; }+.gh:hover { color: var(--bar-hi); text-decoration: none; }++/* columns */+.shell { display: grid; grid-template-columns: 280px minmax(0, 1fr) 220px; gap: 48px; max-width: 1480px; margin: 0 auto; padding: 0 20px; }+.side, .toc { position: sticky; top: 56px; align-self: start; max-height: calc(100vh - 56px); overflow-y: auto; padding: 24px 0 40px; }+.side { border-right: 1px solid var(--line); padding-right: 16px; }+.menu-toggle { display: none; }++/* navigation tree */+.tree ul { list-style: none; margin: 0; padding: 0; }+.tree ul ul { margin: 2px 0 6px 12px; padding-left: 10px; border-left: 1px solid var(--line); display: none; }+.tree li.open > ul { display: block; }+.tree li { position: relative; }+.tree a { display: block; padding: 5px 30px 5px 8px; border-radius: 6px; font-size: 14px; line-height: 1.35; color: var(--fg); }+.tree a:hover { background: var(--soft); text-decoration: none; }+.tree .toctree-l1 > a { font-weight: 600; margin-top: 4px; }+.tree a.current { color: var(--accent); background: var(--accent-soft); font-weight: 500; }+.tree .chev { position: absolute; right: 4px; top: 4px; width: 22px; height: 22px; border: 0; background: none; color: var(--muted); cursor: pointer; border-radius: 4px; padding: 0; }+.tree .toctree-l1 > .chev { top: 8px; }+.tree .chev:hover { background: var(--soft); }+.tree .chev svg { width: 10px; height: 10px; transition: transform .15s; }+.tree li.open > .chev svg { transform: rotate(90deg); }++/* on this page */+.toc h2 { font: 600 13px var(--sans); margin: 0 0 10px; }+.toc ul { list-style: none; margin: 0; padding: 0; }+.toc > ul > li > a { display: none; }+.toc > ul > li > ul ul { display: none; }+.toc a { display: block; padding: 4px 0; color: var(--muted); font-size: 13px; line-height: 1.4; }+.toc a:hover { color: var(--fg); text-decoration: none; }+.toc a.on { color: var(--accent); }++/* page */+main { min-width: 0; padding: 28px 0 56px; }+.pagebar { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: baseline; gap: 6px 16px; max-width: 780px; margin-bottom: 12px; font-size: 13px; }+.crumbs { color: var(--muted); }+.pageactions { display: flex; gap: 14px; margin-left: auto; }+.pageactions a, .pageactions button { color: var(--muted); font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }+.pageactions a:hover, .pageactions button:hover { color: var(--accent); text-decoration: none; }+.crumbs a { color: var(--muted); }+.crumbs > * + *::before { content: "/"; margin: 0 6px; color: var(--line); }+div.body, article.body { max-width: 780px; min-width: 0; padding: 0; background: none; color: var(--fg); }+.body h1 { font-size: 2rem; line-height: 1.2; font-weight: 600; letter-spacing: -0.01em; margin: 0 0 6px; text-wrap: balance; }+.body h2 { font-size: 1.3rem; line-height: 1.3; font-weight: 600; margin: 2.1em 0 .5em; }+.body h3 { font-size: 1.02rem; font-weight: 600; margin: 1.5em 0 .35em; }+.body h4 { font-size: .95rem; font-weight: 600; margin: 1.3em 0 .3em; }+.body p { margin: 0 0 1em; }+.body p.meta { font-size: 13px; color: var(--muted); margin: 0 0 22px; }+.body ul, .body ol { padding-left: 1.3em; margin: 0 0 1em; }+.body li { margin: .2em 0; }+.body li > p { margin: 0 0 .4em; }+a.headerlink { visibility: hidden; margin-left: 6px; color: var(--muted); font-weight: 400; }+h1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink,+h4:hover > a.headerlink, a.headerlink:focus-visible { visibility: visible; }+.body dl dt { font-weight: 600; }+.body dl dd { margin: 0 0 .8em 1.4em; }+.body blockquote { margin: 0 0 1em; padding-left: 1em; border-left: 2px solid var(--line); color: var(--muted); }++/* code */+div.highlight { position: relative; margin: 10px 0 18px; background: var(--code-bg); border-radius: 8px; }+div.highlight pre { margin: 0; background: var(--code-bg); color: var(--code-fg); border-radius: 8px; padding: 12px 14px; overflow-x: auto; font-size: 13px; line-height: 1.65; border: 0; }+.highlight .gp { color: var(--p-dim); user-select: none; }+.highlight .gp.op { color: var(--p-op); }+.highlight .gp.tg { color: var(--p-tg); }+.highlight .go { color: #aab4c1; }+.copy { position: absolute; top: 7px; right: 7px; opacity: 0; background: #1c232c; color: #c9d1db; border: 1px solid #2e3743; border-radius: 5px; font: 500 11.5px var(--sans); padding: 2px 8px; cursor: pointer; }+div.highlight:hover .copy, .copy:focus-visible { opacity: 1; }+@media (hover: none) { .copy { opacity: 1; } }++/* admonitions */+div.admonition { background: var(--warn-bg); border: 1px solid var(--warn-line); border-radius: 8px; padding: 12px 16px; margin: 0 0 20px; }+div.admonition.danger, div.admonition.error { background: var(--stop-bg); border-color: var(--stop-line); }+div.admonition.note, div.admonition.seealso { background: var(--soft); border-color: var(--line); }+p.admonition-title { font-weight: 600; margin: 0 0 4px; }+p.admonition-title::after { content: ""; }+div.admonition p:last-child { margin-bottom: 0; }++/* tables */+table.docutils { border-collapse: collapse; width: 100%; font-size: 14px; margin: 10px 0 20px; border: 0; display: block; overflow-x: auto; }+table.docutils th, table.docutils td { text-align: left; vertical-align: top; padding: 8px 12px 8px 0; border: 0; border-bottom: 1px solid var(--line); }+table.docutils th { font-weight: 600; font-size: 13px; color: var(--muted); background: none; }+table.docutils td p { margin: 0 0 .4em; }++/* threat fact box and other field lists */+dl.field-list { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 4px 16px; margin: 0 0 1em; }+dl.field-list > dt { font-weight: 600; }+dl.field-list > dd { margin: 0; }+dl.field-list > dt .colon { display: none; }+dl.field-list.facts { border: 1px solid var(--line); border-radius: 8px; gap: 0; grid-template-columns: 140px minmax(0, 1fr); margin: 16px 0 24px; }+dl.field-list.facts > dt, dl.field-list.facts > dd { padding: 8px 14px; border-top: 1px solid var(--line); font-size: 14px; }+dl.field-list.facts > dt:first-of-type, dl.field-list.facts > dt:first-of-type + dd { border-top: 0; }+dl.field-list.facts > dt { color: var(--muted); font-weight: 400; }+dl.field-list.facts p { margin: 0; }++/* landing boxes */+.grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; margin: 12px 0 8px; }+.grid > div { border: 1px solid var(--line); border-radius: 10px; padding: 16px 18px; min-width: 0; }+.grid > div > p:first-child { margin: 0 0 6px; font-size: 1.05rem; font-weight: 600; color: var(--fg); }+.grid > div p { font-size: 14.5px; margin: 0 0 8px; color: var(--muted); }+.grid > div p:last-child { margin: 0; }++/* figures and footnotes */+figure { margin: 20px 0; }+figure img, figure svg { max-width: 100%; height: auto; }+figcaption { font-size: 13.5px; color: var(--muted); margin-top: 6px; }+figcaption p { margin: 0; }+aside.footnote-list { border-top: 1px solid var(--line); margin-top: 2em; padding-top: 8px; font-size: 14px; color: var(--muted); }++/* search page */+#search-results ul.search { list-style: none; padding: 0; }+#search-results ul.search li { padding: 8px 0; border-bottom: 1px solid var(--line); background: none; }++/* footer */+.pfoot { max-width: 780px; margin-top: 48px; border-top: 1px solid var(--line); padding-top: 14px; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 8px 20px; font-size: 13px; color: var(--muted); }++@media (max-width: 1180px) {+ .shell { grid-template-columns: 260px minmax(0, 1fr); gap: 40px; }+ .toc { display: none; }+}+@media (max-width: 860px) {+ .bar-in { padding: 0 16px; }+ .search input { width: 160px; }+ .gh { display: none; }+ .shell { grid-template-columns: minmax(0, 1fr); gap: 0; padding: 0 16px; }+ .side { position: static; max-height: none; border-right: 0; padding: 14px 0 0; }+ .menu-toggle { display: block; width: 100%; text-align: left; background: var(--soft); border: 1px solid var(--line); border-radius: 8px; padding: 9px 12px; font: 500 14px var(--sans); color: var(--fg); cursor: pointer; }+ .side .tree { display: none; margin-top: 8px; }+ .side.open .tree { display: block; }+ .grid { grid-template-columns: minmax(0, 1fr); }+ dl.field-list, dl.field-list.facts { grid-template-columns: minmax(0, 1fr); }+ .body h1 { font-size: 1.7rem; }+}+@media (prefers-reduced-motion: reduce) { .tree .chev svg { transition: none; } }diff --git a/Documentation/_themes/shirudo/static/shirudo.js b/Documentation/_themes/shirudo/static/shirudo.jsnew file mode 100644index 00000000..5c549d75--- /dev/null+++ b/Documentation/_themes/shirudo/static/shirudo.js@@ -0,0 +1,204 @@+/* SPDX-License-Identifier: BSD-2-Clause */+/* Copyright (c) 2026 Authors of shirudo */++(function () {+ "use strict";++ var chevron = '<svg viewBox="0 0 10 10" aria-hidden="true">' ++ '<path d="M3 1.5 6.5 5 3 8.5" fill="none" stroke="currentColor" ' ++ 'stroke-width="1.5"/></svg>';++ function tree() {+ var root = document.querySelector(".tree");+ var opened = false;++ if (!root)+ return;+ root.querySelectorAll("li").forEach(function (li) {+ var sub = li.querySelector(":scope > ul");+ var link = li.querySelector(":scope > a");+ var button;++ if (!sub || !link)+ return;+ button = document.createElement("button");+ button.type = "button";+ button.className = "chev";+ button.innerHTML = chevron;+ button.setAttribute("aria-label", "Expand " + link.textContent);+ li.insertBefore(button, sub);+ if (li.classList.contains("current")) {+ li.classList.add("open");+ opened = true;+ }+ button.setAttribute("aria-expanded",+ String(li.classList.contains("open")));+ button.addEventListener("click", function () {+ var open = li.classList.toggle("open");++ button.setAttribute("aria-expanded", String(open));+ });+ });+ if (!opened) {+ var first = root.querySelector(".toctree-l1");++ if (first && first.querySelector(":scope > ul")) {+ first.classList.add("open");+ first.querySelector(":scope > .chev")+ .setAttribute("aria-expanded", "true");+ }+ }+ }++ function menu() {+ var side = document.querySelector(".side");+ var button = document.querySelector(".menu-toggle");++ if (!side || !button)+ return;+ button.addEventListener("click", function () {+ var open = side.classList.toggle("open");++ button.setAttribute("aria-expanded", String(open));+ });+ }++ /* The command a block shows, without its prompts and output. */+ function command(pre) {+ var parts = [];++ if (!pre.querySelector(".gp"))+ return pre.textContent;+ pre.childNodes.forEach(function (node) {+ if (node.nodeType === 1 &&+ (node.classList.contains("gp") ||+ node.classList.contains("go")))+ return;+ parts.push(node.textContent);+ });+ return parts.join("").replace(/^\s+$/gm, "").replace(/\n{2,}/g, "\n");+ }++ function code() {+ document.querySelectorAll("div.highlight").forEach(function (block) {+ var pre = block.querySelector("pre");+ var button = document.createElement("button");++ if (!pre)+ return;+ pre.querySelectorAll(".gp").forEach(function (prompt) {+ if (prompt.textContent.indexOf("operator$") === 0)+ prompt.classList.add("op");+ else if (prompt.textContent.indexOf("target#") === 0)+ prompt.classList.add("tg");+ });+ button.type = "button";+ button.className = "copy";+ button.textContent = "Copy";+ button.addEventListener("click", function () {+ var done = function (label) {+ button.textContent = label;+ setTimeout(function () {+ button.textContent = "Copy";+ }, 1400);+ };+ var select = function () {+ var range = document.createRange();+ var selection = window.getSelection();++ range.selectNodeContents(pre);+ selection.removeAllRanges();+ selection.addRange(range);+ done("Selected");+ };++ if (!navigator.clipboard) {+ select();+ return;+ }+ navigator.clipboard.writeText(command(pre)).then(+ function () { done("Copied"); }, select);+ });+ block.appendChild(button);+ });+ }++ function spy() {+ var links = document.querySelectorAll(".toc > ul > li > ul > li > a");+ var targets = [];+ var observer;++ links.forEach(function (link) {+ var id = decodeURIComponent(link.hash.slice(1));+ var target = id && document.getElementById(id);++ if (target)+ targets.push({ link: link, target: target });+ });+ if (!targets.length || !("IntersectionObserver" in window))+ return;+ observer = new IntersectionObserver(function (entries) {+ entries.forEach(function (entry) {+ if (!entry.isIntersecting)+ return;+ targets.forEach(function (t) {+ t.link.classList.toggle("on",+ t.target === entry.target);+ });+ });+ }, { rootMargin: "-70px 0px -70% 0px" });+ targets.forEach(function (t) { observer.observe(t.target); });+ }++ function copyPage() {+ var button = document.querySelector(".copy-page");++ if (!button || !navigator.clipboard || !window.fetch)+ return;+ button.addEventListener("click", function () {+ var done = function (label) {+ button.textContent = label;+ setTimeout(function () {+ button.textContent = "Copy page";+ }, 1400);+ };++ fetch(button.dataset.src).then(function (response) {+ if (!response.ok)+ throw new Error(response.status);+ return response.text();+ }).then(function (text) {+ return navigator.clipboard.writeText(text);+ }).then(function () {+ done("Copied");+ }, function () {+ done("Not available");+ });+ });+ }++ function search() {+ var input = document.querySelector(".search input");++ if (!input)+ return;+ document.addEventListener("keydown", function (event) {+ var active = document.activeElement;++ if (event.key !== "/" || active === input ||+ /^(INPUT|TEXTAREA|SELECT)$/.test(active.tagName))+ return;+ event.preventDefault();+ input.focus();+ });+ }++ document.addEventListener("DOMContentLoaded", function () {+ tree();+ menu();+ code();+ spy();+ copyPage();+ search();+ });+})();diff --git a/Documentation/_themes/shirudo/theme.toml b/Documentation/_themes/shirudo/theme.tomlnew file mode 100644index 00000000..033c6ec2--- /dev/null+++ b/Documentation/_themes/shirudo/theme.toml@@ -0,0 +1,10 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++[theme]+inherit = "basic"+stylesheets = ["shirudo.css"]+sidebars = []+pygments_style = { default = "github-dark" }++[options]diff --git a/Documentation/architecture.rst b/Documentation/architecture.rstdeleted file mode 100644index 8726258a..00000000--- a/Documentation/architecture.rst+++ /dev/null@@ -1,827 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--shirudo architecture-====================--This document describes the implemented design: what runs where, which-kernel mechanisms carry the enforcement, what state a target holds, and-how artifacts, packages and telemetry move. The code is authoritative;-when this document and the code disagree, the code is right and this-document has a bug. The security argument behind the design is in-`threat-model <threat-model.rst>`__, the byte-level artifact format in-`upatch-spec <upatch-spec.rst>`__, and the export path in-`telemetry <telemetry.rst>`__.--1) What shirudo is---------------------shirudo is a BPF security platform. It ships BPF live patches-("upatches") to Linux targets, and it makes sure a target runs only the-BPF its operator signed. Both halves are needed: a patching mechanism-any root process can use is an attack surface, and an enforcement-mechanism without a way to ship fixes is a wall nobody can work behind.--Once ``shirudo init`` has run, the kernel accepts BPF programs from-userspace only through signed loader programs. A loader is a-``BPF_PROG_TYPE_SYSCALL`` program generated by libbpf's gen_loader on-the operator; it embeds the ``bpf()`` calls that create the maps and-load the payload program. The operator CMS-signs the loader-instructions and data with an ML-DSA-87 key. The target kernel-verifies that signature at ``BPF_PROG_LOAD`` against the certificate in-the sealed bpf keyring, before the verifier and before any LSM hook-runs. The payload program is hash-locked to the loader-(``excl_prog_hash``), so a signature over a few kilobytes of loader-covers every instruction that ends up attached.--The kernel-side enforcement is a set of embedded BPF LSM programs loaded-during trusted bootstrap, before the signature-admission gates attach.-Authenticated initrd boot protects that bootstrap; subsequent upatch loads-use the signed-loader path above. Every upatch state change extends a-per-boot TPM measurement register-anchored in a PCR, so an operator predicts from the signed set what a-target must report and has the TPM certify that it does.-The userspace side is one binary with git-like subcommands; on the-target there is no daemon and no socket, only one-shot invocations-driven by systemd timers.--2) Why shirudo exists------------------------The kernel's CVE stream runs at dozens of fixes a day, and that churn-is not going to end. The distribution model of enabling every Kconfig-option for compatibility and then carrying a kernel that deviates from-upstream stable does not survive it, and rolling a new kernel across a-fleet for every batch of fixes is not feasible when a reboot cycle-takes weeks. Mean time to exploit has gone negative: exploitation-regularly precedes the patch. A deploy cycle built for a slow human-adversary is too slow for one that reads a fix on the list and has a-working exploit the same day; the acceptable time to mitigate a-critical bug is hours, not a day.--Three conclusions, first stated at LSF/MM/BPF, shape the design:--1. the kernel surface a fleet exposes needs massive hardening, and- that hardening has to be deployable without a reboot;-2. mitigations have to be produced at the speed of agents, from the- fix on the list to a signed BPF shield in the fleet;-3. BPF security has to be part of the trusted computing base, or the- mechanism that ships the fixes becomes the next hole.--The CopyFail CVE of May 2026 is the reference case: a publicly-documented BPF LSM mitigation reached a large edge fleet in 26 to 30-hours, where the regular kernel update and reboot cycle of that fleet-was four weeks. shirudo is built to make that the normal path, and to-make it signed, measured and agentless.--3) Design properties-----------------------Agentless. The BPF security layer is part of the TCB and always on,-launched from early boot. It is signed, verified against a sealed-kernel keyring, and resilient to a malicious root user. The BPF-control plane lives in the kernel, so every operation on it is-signature-verified, and a TPM register the TPM certifies on request-keeps the record of every operation since boot. No daemon, no-listening socket, no open port on the target.--Packaging. The platform itself protects only its own assets; every-piece of functionality, observability or a CVE shield, ships as a BPF-upatch. An upatch is a signed set of related BPF programs, maps and-metadata: a light-skeleton loader plus the assets it installs. In an-agentic age shirudo ships code, not a DSL or an API, because agents-work better with code and because a DSL is a second thing to get-right. The agentless platform pulls upatches from a registry and-pushes telemetry to a collector; nothing ever connects in.--Agentic. Every command has structured input and output so agents can-read and act on it: JSON status and reports, named failure-categories, verifier logs captured in full. The intended loop is to-ingest the fix stream (lore, git trees, advisories, code audit),-classify, reproduce in a pinned kernel VM, derive a shield as a-``.bpf.c``, build and sign it, and publish it; targets pull it. The-source tree is a set of small gadgets so an agent can hold the relevant-context at once. The outcome is always an operator-signed upatch: the-agent proposes, the key holder signs.--4) Operator and target-------------------------The same ``shirudo`` executable runs on both sides. Roles are decided-by what is on disk, not by separate builds: the operator has the-private key ``signing_key.pem`` under ``/var/lib/shirudo/keys/``, the-target has the trusted set of certificates and a kernel keyring.-``shirudo status``-prints the roles it detects. A development host may be both.--The operator holds the private signing key and runs ``genkey``,-``build`` and the ``bpm build``, ``bpm push`` and ``bpm tree append``-commands. Those are implemented in the separate ``shirudo-build``-helper (``$(libexecdir)/shirudo/shirudo-build``), which links the CMS-signer and executes clang. Image building and offline ``image verify`` also-dispatch to this helper; it runs the standard ``veritysetup`` executable-for formatting and verification. These subprocesses belong to operator-operations. Target commands use linked libraries and kernel APIs. The-operator never opens the TPM or the kernel keyring, and persists nothing-but the keypair and the files the caller names.--The core binary exposes the operator-only BPM commands only when it can-resolve ``shirudo-build``. The installed operator package provides the-helper; a checkout must set ``SHIRUDO_BUILD`` or put both the checkout-root and ``tools/shirudo-build`` on ``PATH``. Without the helper,-``shirudo bpm --help`` shows the target command set and rejects ``build``.--The target holds the certificate, the sealed keyring, the private bpffs-mount, the installed upatches, the eventlog and the TPM register. It runs-``init``, ``upatch load``, ``upatch unload`` and the install side of-``bpm``. The target never sees the operator's private key. Its separate-boot-scoped RSA key authorizes only local TPM register extensions.--Delivery is pull-based. The operator publishes a package to an OCI-registry; the target pulls it on a timer or by hand, verifies the-signed index and the package digest, and loads the upatches inside.-shirudo owns no push transport, no fleet inventory and no rollout-coordinator. A single ``.upatch`` copied to the target by any means-loads through the same path.--5) The signed-loader path----------------------------Build. ``shirudo build fix.bpf.c -o fix.upatch`` compiles the source-with ``clang -target bpf -O2 -g``, opens the object with libbpf, calls-``bpf_object__gen_loader()`` with ``gen_hash`` set and-``bpf_object__load()`` to produce the loader instructions and data,-appends the name, the attach metadata and the decoders to the data as-signed sections, CMS-signs ``loader_insns || data``, and writes the-``.upatch`` container with the name and the payload SHA-256 in its-header.-A pre-compiled ``.bpf.o`` is accepted as input too. ``shirudo build --unload-<name>`` emits an unload directive instead: the same container with-flag bit 0 set, carrying the compiled ``bpf/unload.c`` template-parameterised with the target name and the expected payload digest.--Load. ``shirudo upatch load fix.upatch`` on the target:--1. runs the pre-flight: the kernel exposes the signed-loader ABI, the- kernel BPF keyring matches the serial ``init`` froze, the- enforcement link is pinned, the eventlog has room, the binary's- version identity matches ``--expect-version-id`` when given, and- the register is the one ``init`` bound and equals ``--expect-chain``- when given;-2. parses and bounds-checks the container;-3. loads the signed loader with ``BPF_PROG_LOAD``, naming that keyring- as ``attr.keyring_id`` (``KEY_SPEC_BPF_KEYRING``); the kernel verifies the CMS signature here;-4. runs the loader under ``BPF_PROG_TEST_RUN``; it creates the maps and- loads the payload program, which the kernel checks against the- loader's ``excl_prog_hash``;-5. attaches the payload (``BPF_LINK_CREATE`` or- ``BPF_RAW_TRACEPOINT_OPEN``), checks that the link the kernel- reports is at the site the metadata names (the root cgroup of the- initial cgroup namespace, the initial network namespace, the kprobe- symbol and offset, the uprobe offsets) and refuses- ``attach_scope_mismatch`` otherwise, pins the link at- ``/run/shirudo/bpffs/upatches/<name>/link`` and every map under- ``maps/`` beside it, and records the payload digest as the- ``security.bpf.shirudo.payload`` xattr on the pin directory;-6. copies the artifact to ``/var/lib/shirudo/upatches/`` for- boot-restore;-7. extends the register with ``SHA256("shirudo-upatch\0" ||- payload_sha256 || name)`` and appends the event to the eventlog; an- archive copy that fails, or a register that refuses the event, undoes- the load, pins and archive.--Unload. ``shirudo upatch unload fix.unload.upatch`` runs the same-pre-flight and the same signature-gated ``BPF_PROG_LOAD`` of the-directive's loader, so the kernel authorises the directive exactly as-it authorises a load. The detach itself is userspace: shirudo reads the-``security.bpf.shirudo.payload`` xattr of the live pin, compares it-constant-time against the directive's expected payload, and refuses-with ``payload_mismatch`` on disagreement or when the xattr cannot be-read. Otherwise it extends the register with-``SHA256("shirudo-unload\0" || payload_sha256 || name)`` and only then-unlinks the map pins, the link pin and the pin directory and removes-the persisted ``.upatch``: a process stopped between the two leaves a-register that says more than happened, never a detach it does not-know. A missing pin is ``already_unloaded`` and extends nothing. The kernel's-``bpf_sys_bpf()`` allowlist has no detach or unlink command, which is-why the detach is not inside the signed BPF; the target name and the-expected payload are signed sections of the directive, so what that-costs the trust model is the moment of the detach alone, residual risk-1 in the threat model.--Attach kinds. The attach metadata selects a raw tracepoint attach-(``tp_btf``, ``fentry``/``fexit``, ``lsm``), kprobe and kretprobe,-``fmod_ret``, cgroup v2 root ``cgroup_skb`` ingress and egress, IPv6-pre-routing netfilter, or ``uprobe.multi`` entry probes bound to the-target ELF's GNU build ID. The format specification has the encoding.--6) Enforcement in the kernel-------------------------------The target requires an authenticated runtime image and a signed config image.-The runtime is mounted at ``/run/shirudo/runtime`` and the config at-``/run/shirudo/config`` with ``noexec``. Neither replaces the host root.-Every runtime executable is eligible for task authority after successful exec.--The binary embeds ``bpf/bpf2.c`` for admission, device and mount protection,-and ``bpf/seal.c`` for writable-state labels and process protection.-``bpf/admission.h`` and ``bpf/seal.h`` contain the checks shared by their-programs; ``bpf/verity_policy.h`` supplies runtime-device and task lookups.-Initialization always loads this pair and all its hooks. There is no mode-selector, executable inode identity or user-keyring staging path.--These are bootstrap objects, not signed upatch-loader artifacts. In the-production boot flow their provenance comes from the authenticated initrd.-The map-access, ``bpf_prog_load`` and ``bpf`` gates attach last, after the-selected objects have loaded and their identity maps are frozen. Subsequent-upatch code must enter through the signature-gated loader path.-Both objects contain BPF LSM programs. Their verdicts compose with-SELinux, AppArmor, SMACK and Yama to the most restrictive result, and-they never override another LSM's deny.--bpf() admission. ``lsm/bpf`` sees every ``bpf()`` command with a-``kernel`` flag that is true when the caller is a loader running in-kernel context and false for userspace. Kernel-context calls are-allowed; 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``. Userspace ``BPF_PROG_TEST_RUN`` is-restricted to tasks authorized by successful exec from the runtime image;-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. Map creation, update and freeze, object pin, link creation-and raw tracepoint open also require that task authority, and so does-``PERF_EVENT_IOC_SET_BPF``, the perf event ioctl that attaches a program-without a ``bpf()`` command, which ``lsm/file_ioctl`` and-``lsm/file_ioctl_compat`` deny to every other caller.-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``, ``TASK_FD_QUERY``) 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, including-``LINK_DETACH``, ``LINK_UPDATE``, ``PROG_ATTACH``/``PROG_DETACH``,-``BTF_LOAD`` and every map delete variant, is denied with ``-EACCES``.--``lsm/bpf_map`` denies writable map descriptors to tasks without authority.-Root can retrieve read-only map descriptors for observation, but direct map-updates and writable arena mappings require an authorized task. Device records-are private because they contain kernel pointers. ``task_prctl`` denies-``PR_SET_MM_EXE_FILE`` and ``PR_SET_MM_MAP`` to untrusted tasks. Rewriting-``mm->exe_file`` never creates task authority.--``lsm/bprm_check_security`` keeps that boundary from being stepped-around through the environment: every exec from the runtime image runs in secure-exec mode (``AT_SECURE``), as a-set-user-ID program does. The dynamic loader then ignores-``LD_PRELOAD``, ``LD_AUDIT``, ``LD_LIBRARY_PATH`` and the other-variables glibc treats as unsafe, and libraries ignore what they read-with ``secure_getenv()``, among them OpenSSL's ``OPENSSL_CONF`` and-``OPENSSL_MODULES``. The same hook refuses the exec, counted as-``ExecTraced``, when the task is traced (``LSM_UNSAFE_PTRACE``): a-tracer that carries over into the new image, set up with-``PTRACE_TRACEME`` or attached to the parent, would own it, and the-seal's ptrace guard only stops a tracer attaching later. ``strace``-and ``gdb`` therefore cannot start shirudo on a target. The hook runs-on every binary handler pass, so a script that names shirudo as its-interpreter gets the same.--``lsm/bpf_prog_load`` runs after the kernel's signature check and admits-a program only when the verdict is ``BPF_SIG_VERIFIED`` and the signature-was resolved from the kernel's BPF keyring. The kernel normally records no-serial for this singleton; a nonzero serial must match the frozen record.-A certificate in another caller keyring cannot authorize a load.--Image content by descriptor. Everything a command takes from the-runtime or config image, the bootstrap settings, the configuration,-the certificate, the key set, the registries, the tree configuration-and the node labels, is opened from the verified root descriptor with-``openat2`` under ``RESOLVE_BENEATH``, never through a path string;-``/proc/self/fd`` names in particular are not used for them.-bpffs and keyring guards. The identity map contains the bpffs and run-device-numbers, runtime root hash, BPF keyring kind and serial, enrolled key-serials, the selected NV index, the NV writer's public modulus and-nonsecret input, and the name of the TPM's attestation key, which-every later TPM handle is compared against.-It is written and frozen before the admission gates attach.-The task map is seeded with the authenticated bootstrap task, then frozen-against userspace writes. Runtime exec and fork hooks maintain its marks.-Expected config roots remain writable only by trusted tasks preparing a-mapping. Other device records are maintained by the kernel hooks.-``lsm/inode_unlink``, ``lsm/inode_rename``,-``lsm/inode_setxattr`` and ``lsm/inode_removexattr`` on shirudo's bpffs-allow the operation only for a task with runtime authority: root ``rm`` cannot drop a pin, ``mv`` cannot replace-one (the VFS unlinks a rename's victim without ``inode_unlink``), and-nobody else can forge the payload xattr. ``lsm/inode_mkdir``,-``lsm/inode_symlink`` and ``lsm/inode_link`` there are shirudo's too,-so that no symbolic link of root's stands where a load would make its-pin directory and no hard link of root's keeps a pin past its unlink. ``lsm/key_permission`` applies the same test-to the trust anchors in the kernel's keyrings: write, setattr and unlink-on the sealed bpf and dm-verity keyrings and on the keys they hold, and the unpossessed-search ``keyctl invalidate`` uses to reach a key by serial, are denied-to every task but shirudo, while viewing, listing and the possessed-search the kernel verifies signatures with stay open. Sealing stops-keys from being added; this stops root from taking them away, so that-signer removal happens through signed config activation.-``lsm/kernel_load_data`` and ``lsm/kernel_read_file`` refuse a kexec-image or initramfs to every task, since a kexec would carry this boot's-TPM state under a kernel of root's choosing.-``lsm/sb_umount``, ``lsm/move_mount``,-``lsm/sb_mount`` and ``lsm/sb_remount`` deny unconditionally, for every-caller including shirudo, direct unmount, relocation, mount-over and-remount of that superblock. ``lsm/sb_umount`` also walks what an unmount-would take down, the subtree of the mount and what propagation carries to-its peers and slaves, and refuses one that reaches the bpffs mount init-recorded when it opened the bpffs root with the guards live; a copy in-another mount namespace is any process's to drop. See residual risk 3 in-the threat model.-The pins are the only thing-keeping the enforcement programs alive, and one ``umount`` would-otherwise detach everything. Named refusal points increment counters in-a frozen map pinned beside the identity map-(``bpf/lib/shirudo_tamper.h``); ``shirudo status`` reads it back. Device, parent-mount and process checks do not yet have counters. A refusal-at an earlier image check therefore need not increment a shared counter.-Search denials on NV keys are not counted: traversal probes use the-same permission as signing and invalidation.--Filesystem seal. Initialization labels existing state under-``/var/lib/shirudo/`` with ``security.bpf.shirudo``. The fixed 64-byte label-marks a protected target; its public value does not authorize a caller.-The ``file_open`` (for write), ``inode_unlink``, ``inode_rename``,-``inode_setattr``, ``inode_setxattr`` and ``inode_removexattr`` hooks require-the caller's committed task authority, and so do ``inode_create``,-``inode_mkdir``, ``inode_symlink``, ``inode_mknod``, ``inode_link`` and a-rename into a marked directory: a sealed directory takes new entries from-shirudo alone. ``inode_copy_up`` refuses the overlay copy-up of a marked-inode, so a write through an overlay mounted over sealed state fails-rather than landing, label and all, in the upper directory. Runtime and-config files use dm-verity and receive no seal writes.-Only an authorized caller may set the exact seal xattr, including on an-unlabelled inode. A binary carrying a copied label gains no authority.-A path the caller names for shirudo to write (``--report``, ``--out``,-``--json``, a ``bpm pull``) is opened by ``seal_output_open()``: a-regular file without a label, not created under a labelled directory,-not reached through a symbolic link, so root cannot point the authority-at sealed state.--A label of any size, or an error reading it, requires caller authority,-except for ``ENODATA``, ``EOPNOTSUPP``, ``EACCES`` and ``EPERM``. The latter-two exceptions preserve write-only opens and unlinking unreadable files:-the xattr kfunc checks the caller's read permission. Failure to allocate-scratch storage also requires caller authority. Rename checks both the-source and an existing destination. ``inode_setattr``-covers truncate, chmod, chown and timestamp changes to labelled targets.--``inode_init_security`` uses ``bpf_inode_init_xattr()`` to give a new inode-its parent's label inside the filesystem's creation transaction. That hook-cannot sleep to read the parent xattr, so it uses an inode-storage directory-mark populated by directory opens, post-xattr hooks and directory creation-under a marked parent. Shirudo's writers hold an open parent directory and-create files relative to it; they also apply the label after creation when-the kernel could not. Cached marks can be absent after inode eviction, when-a creation, link or rename can introduce an unlabelled inode; shirudo opens-sealed state without following symbolic links, refuses an entry under a-labelled directory that lacks the label, and ``init`` ignores such an entry-instead of labelling it. Existing writable descriptors and mappings are not-revoked.--``ptrace_access_check`` and ``perf_event_alloc`` deny against tasks already-marked when those hooks run. The perf allocation check is not serialized with-exec; the separate `perf/exec race investigation-<https://github.com/shirudo-dev/shirudo/issues/11>`__ records this limitation.--Process hardening. ``util/harden.c`` runs before command dispatch in-both the core executable and ``shirudo-build``: ``PR_SET_DUMPABLE`` off,-``PR_SET_NO_NEW_PRIVS``, ``PR_SET_PTRACER`` cleared and ``RLIMIT_CORE`` zero.-``mlockall(MCL_CURRENT | MCL_FUTURE)`` keeps current and future mappings-out of swap for the process lifetime; failure is logged and refuses-startup. Sensitive buffers are scrubbed after use.-No host file may name code for it to load:-OpenSSL reads no configuration file, so none can activate a provider-module, and host names resolve through glibc's built-in ``files`` and-``dns`` services alone, so ``nsswitch.conf`` cannot add a module-either; ``/etc/hosts`` and ``/etc/resolv.conf``, a local resolver stub-included, still apply. The zeroing allocator in ``util/malloc.c``-wipes freed memory; the libc allocators are poisoned project-wide.--Runtime and config enforcement. The UKI authenticates a runtime image mounted at-``/run/shirudo/runtime``; signed configuration is mounted separately at-``/run/shirudo/config`` with ``noexec``. Neither is the host root filesystem.-Every executable on the runtime image is equally eligible for authority.-``bprm_check_security`` stages the candidate decision and-``bprm_committed_creds`` commits it after successful exec. ``task_alloc``-inherits the mark. A failed exec leaves the current mark alone; a successful-outside-image exec clears it. Protected operations consult this mark rather-than mutable ``mm->exe_file``. ``PR_SET_MM`` cannot grant authority.--``bdev_setintegrity`` records metadata available through the existing-upstream hook. Device lookup checks the block-device pointer, device number-and disk sequence. Runtime records require the authenticated bootstrap root.-Config records require an authorized task and the expected root it staged-for that mapping. ``bdev_free_security`` attempts cleanup, but upstream-can omit the notification.-The ``file_ioctl`` and ``file_ioctl_compat`` hooks deny untrusted-callers mutating device-mapper control operations, including through old or-inherited FDs. This restriction applies to all DM devices on the target.-Trusted image tasks retain control access. These checks use existing LSM-hooks. Direct keyring access additionally requires the upstream-``KEY_SPEC_DM_VERITY_KEYRING`` API described in the requirements.-The metadata hook does not expose all verity options; complete mount-tree-protection remains unestablished. ``mmap_file`` and-``file_mprotect`` prevent trusted tasks from introducing host or anonymous-executable pages. Existing ptrace and process-memory checks still apply.--Writable state keeps its seal xattrs, while neither image receives seal-writes. The task mark authorizes writable-state and bpffs access.-The authorized BPF signing keys are enrolled at boot and the ``.bpf``-keyring then receives the existing reject-all restriction. A live config-update refuses a candidate requiring a signer absent from that sealed-keyring before measurement; new keys require boot-time enrollment and a-reboot. The existing key protection remains in place.--Image bundles use a standard verity superblock and a 64-character lowercase-SHA-256 root hash. The detached config signature covers exactly those ASCII-root bytes. The kernel verifies config signatures through its ``.dm-verity``-trust path, including built-in trusted keys. The trusted initrd enrolls the-bootstrap config certificate and seals the dedicated keyring. Runtime-acceptance instead requires the exact root authenticated by the UKI; a-valid config signature never grants executable authority.--Target image preflight validates the fixed verity format and exact backing-file sizes, creates or validates a strict read-only mapping and reads the-entire data device through kernel dm-verity before parsing contents. The-target has no userspace hash-tree implementation or external verifier.--Config activation verifies the candidate, persists its pending selection,-measures its root into the reserved static PCR, finishes key and mount-effects, then records completion. Its measurement log is separate from the-upatch NV register. Once pending, an interruption blocks further state-changes and config attestation until an operator reboots. The node keeps-running; Shirudo never triggers a reboot. Trusted startup verifies that-selection again, measures a fresh BOOT event and completes initialization;-it never retries the previous boot's PCR extension. The-`config-images <config-images.rst>`__ guide describes this flow and the-deferred TPM writer limitation.--The boot-scoped NV writer is separate from the operator's artifact key.-Trusted initialization creates its private key inside the TPM and freezes-its public modulus and the nonsecret 32-byte input needed to recreate it.-Each one-shot command checks the recreated key, signs the exact NV-extension and flushes the handle. The input is not an access control:-another process may recreate the key and ask the TPM to sign. The-``tpm_command`` LSM hook instead denies an untrusted ``TPM2_NV_Extend``-to Shirudo's selected NV index. The selected index is frozen during-initialization. Other TPM signing and PCR extension remain available.-A TPM reset in the same host boot keeps the writer identity; a TPM Clear-does not. `The TPM design <tpm.rst#write-policy>`__ describes the policy-and the remaining limits.--7) Target state------------------The authenticated initrd runs ``shirudo init`` before untrusted workloads.-The root service runs it again using the packaged runtime interpreter and-libraries. Both runs use the same enforcement and records; no fallback mode-exists. Initialization performs these steps:--1. Load authenticated bootstrap settings, including the runtime image root,- then run prerequisite checks. Missing image settings are an error.- ``--check-only`` stops before changing kernel state.-2. Bind ``/sysroot/var/lib/shirudo`` writable at its usual path in the initrd,- so config selection and recovery can be recorded durably. Mount the private- bpffs under ``/run/shirudo``.-3. Verify the runtime and selected config, enroll the config verification- certificate in ``.dm-verity``, and seal it. Enroll the initial BPF certificate- plus vouched config signers, less config revocations, in ``.bpf`` and seal it.- Both enrollment boot parameters are required. A sealed empty BPF ring is an- error, rather than a reason to stage keys in a user keyring.-4. Label writable state. Load both bootstrap BPF objects, populate and freeze- their shared maps, seed bootstrap authority, attach device, mount and seal- hooks, then attach the map-access and BPF admission gates last.-5. Mount the runtime under those guards, verify and measure the config- selection, apply its revocations, and label state again to populate the- inode protection cache. All image files stay read-only.-6. Restore the archived signed upatches in sorted order. Any failure leaves- config completion pending and blocks changes and config attestation.-7. Bind this boot's upatch register and extend it once with- ``SHA256("shirudo-init\0" || cert_sha256 || set_digest || tree_root)``.- Append its event and mark config startup complete. The root service later- adopts the pending initrd eventlog record without another extension.--Boot-restore extends the register by exactly one event however many-upatches it restores. The register starts from zero at every boot, so-an operator predicts its value from the certificate and the installed-set alone (``shirudo attest predict``); no history is needed. If any-re-apply fails the register is not written and ``status`` reports-``degraded``. A re-run of ``init`` finds the register bound and on-record and leaves it alone, and restores nothing: an archived artifact-that is not loaded by then, which root can arrange by renaming a-signed artifact into the archive, is refused ``tampered`` rather than-attached without an event; one that finds the recorded register gone-refuses ``tampered`` until the next TPM reset.--Measurement register. The measurement lives in a TPM 2.0 NV index-(default ``0x01818E00``) built the way systemd builds its NvPCRs: an-extend-only index (``TPM2_NT_EXTEND``) whose contents clear at every-TPM reset (``TPMA_NV_CLEAR_STCLEAR``) and whose write policy is-bound to PCRs 9 and 11 and the boot writer's public key.-Both the first and subsequent writes require command-bound authorization;-the complete policy is specified in `the TPM design <tpm.rst#write-policy>`__.-``init`` runs from the initrd,-after systemd has-measured ``enter-initrd`` into PCR 11 and before ``leave-initrd``-moves it, performs the first write through the PCR branch and then-extends PCR 9 with the record ``nvpcr-init:shirudo:0x1818e00:<name>``-(systemd's ``nvpcr-init`` format, ``<name>`` being the index's TPM-name), so that branch can never be satisfied again until the next-reset and nothing that runs after the initrd can bind at all; every-later extend presents the written branch. An index undefined and-recreated at runtime therefore stays unwritable, and one recreated-under a weaker policy has a name other than the one ``init`` recorded-and anchored. The record carries both PCR values and whether the-initrd was running, so a verifier pins the ``enter-initrd`` value and-refuses a binding made from the root file system.-Reads and certification use the index's empty authorization; no writer-secret is needed. Defining and undefining the index need the owner-hierarchy. Its authorization is empty by default; when set, the-password comes from ``tpm.owner_auth`` in-``/etc/shirudo/shirudo.conf``. Every-state-changing command reads the register first and refuses with-``tampered`` when ``--expect-chain`` disagrees or the index is not the-one ``init`` recorded. There is no TPM opt-out; an unmeasured target-is indistinguishable from a tampered one.--Eventlog. ``/var/lib/shirudo/eventlog`` (mode 0600) holds one JSON-line per register extension: timestamp, boot ID, type (``init``,-``upatch_load``, ``upatch_unload``, ``tree_op``), the digest extended,-and the name and payload digest, the set digest or the tree operation.-The ``init`` record also carries the binding: the PCR value the policy-was computed from, the index name, the anchor record with its digest,-and the TPM's reset count, which tells one register period from the-next. Replaying this boot's records from its ``init`` on must-reproduce the live value; ``shirudo status`` does that replay, checks-that the live index carries the recorded name, and reports ``Chain vs-eventlog`` and ``Anchored``. When ``eventlog.max_bytes`` would be-exceeded, the operation refuses with ``eventlog_full`` before any load-or extend, so register and log never diverge.--Attestation. ``shirudo attest --nonce=<hex>`` emits a JSON evidence-document: a ``TPM2_Quote`` over the SHA-256 bank (PCRs 0-7, 9 and-11-15 by default) and a ``TPM2_NV_Certify`` of the register, both-signed by the attestation key and carrying the nonce, the key's public-area and name, the PCR values, this boot's eventlog records, the-endorsement key certificate when the TPM holds one, and the firmware-and systemd measurement logs. The attestation key is a restricted-P-256 ECDSA primary under the endorsement hierarchy with a fixed-template, so the same TPM always yields the same key; an operator-records its name once when enrolling the target. ``shirudo attest-challenge`` makes a credential under the target's endorsement key for-that name, ``attest --challenge`` activates it in the TPM while-attesting, and ``verify --expect-credential`` checks the recovered-value, so the key is shown to sit in the TPM the endorsement-certificate describes instead of being taken on trust. ``shirudo-attest verify`` on the operator checks the signatures and the nonce,-that the-quote covers the listed PCRs, that the certified index has the public-area a register bound to the recorded PCR value must have, that the-records replay to the certified value, that the anchoring PCR carries-the anchor, and that the register equals the value ``shirudo attest-predict`` computes from the certificate, the installed artifacts and-the tree root, or an ``--expect-chain`` the operator computed from-those plus the events since boot. ``attest`` touches only the-target's TPM; ``verify`` and ``predict`` touch no TPM at all.--Files. Writable state under ``/var/lib/shirudo`` includes archived upatches,-eventlogs, locks, downloaded packages, tree state, cached images and the config-activation record. Initial BPF keys and bootstrap settings live in the runtime;-repository definitions, node labels, export settings, additional signer vouches-and revocations live in config. The operator keeps its private signing key-outside both images. Per-boot mounts and pins live under ``/run/shirudo``;-``eventlog.pending`` bridges the initrd and root service runs.--8) Packages and registries-----------------------------A BPM package (``.bee``) is a gzip tarball with the ``Beefile``, the-built ``upatches/*.upatch`` and their unload directives, a-``README.md``, the signing ``cert.der`` and a ``build-environment.json``.-``shirudo bpm build <dir> --version <v>`` builds and signs every-``[[upatches]]`` entry through ``shirudo-build``. ``shirudo bpm push-<pkg.bee> oci://host/ns/name`` uploads it as an OCI artifact-(``application/vnd.shirudo.bpm.package.v1+gzip``) with the certificate-as a referrer and, when given the signing material, adds the version to-the registry's detached-CMS-signed index at-``shirudo/bpm-index:stable``. Published versions are immutable; an-index that already lists a version with other digests is refused.--Repository definitions and index verification certificates are prepared on the-operator and shipped in the signed config image. ``shirudo bpm repo update`` fetches and verifies-the index; ``shirudo bpm install <name>/<pkg>[@ver]`` (or an ``oci://``-reference) pulls, verifies, unpacks and loads; ``upgrade`` moves-installed packages to the newest indexed version; ``uninstall`` loads-the package's unload directives; ``list`` and ``info`` inspect.-``shirudo bpm key`` manages the active certificate and refuses to switch-to a different one while a key is active. The ``repo update`` and-``tree sync`` timers (60 s) and the map-export and keepalive timers-(5 s) are the only always-on infrastructure.--Repository definitions and verification certificates come-from the signed config. Local repository and key mutations refuse with-instructions for config activation or boot-time signer enrollment. The-package and tree update commands remain available. Repository ``key_file``-paths are confined to the held config image; tree signatures use the runtime-image's initial certificate. Node labels and the tree subscription also-come from the selected config. Config settings are validated before their-activation is measured.--upatch trees. A tree is an append-only, globally ordered sequence of-``add`` and ``delete`` operations published as a CMS-signed JSON-document (``application/vnd.shirudo.upatch.tree.v2+json``), each-``.upatch`` pushed as an immutable OCI manifest. Every operation-carries a selector (architecture, kernel release prefix, kernel build-ID, Kconfig values, node labels) that ``shirudo bpm tree sync``-evaluates locally against ``uname``, ``/sys/kernel/notes``,-``/proc/config.gz`` and ``/etc/shirudo/node.labels``; matching-operations apply in sequence order, each applied one is measured into-the register as a ``tree_op`` event (``SHA256("shirudo-tree\0" || seq-|| operation_digest)``), and the node's projection root enters the next-boot's ``init`` event. ``shirudo bpm tree append <pkg.bee>-oci://host/repo [--op add|delete]`` publishes from the operator. The-tree is enabled by ``/etc/shirudo/bpm/upatch-tree.conf`` and its timer;-without that file nothing changes. The publication format is in the-format specification's companion section below.--Registry access honours ``BPM_OCI_SCHEME``, ``BPM_OCI_CA_FILE``,-``BPM_OCI_USERNAME``/``BPM_OCI_PASSWORD``, ``REGISTRY_AUTH_FILE`` and-``DOCKER_CONFIG``. Every libcurl client in shirudo speaks TLS 1.3 with-a hybrid ML-KEM key exchange by default (X25519MLKEM768,-SecP256r1MLKEM768). ``tls.classical_hosts`` in-``/etc/shirudo/shirudo.conf`` opts exact HTTPS DNS names into classical-key exchange, for example ``ghcr.io,quay.io``. Operator commands read-this key from the root-managed host config; target commands read it only-from the immutable runtime image's config. The list rejects wildcards-and IP addresses, and redirects are checked against each destination-host. TLS 1.3 and certificate verification remain unchanged. Shirudo-warns if an opted-in connection negotiates a non-hybrid group. An empty-list requires hybrid exchange everywhere. A classical exception-weakens transport confidentiality for that host, but signed publications-remain authenticated and cannot be forged by the registry, which can-still withhold or replay them.--Tree publication format. The ``stable`` manifest has two layers, the-publication and its detached CMS signature. The publication is::-- {"schema": 2, "tree_id": "...", "generation": N,- "parent_manifest_digest": "sha256:...",- "base": {"seq": 0}, "operations": [...], "head": {"seq": N}}--and each operation is::-- {"seq": N, "op": "add" | "delete", "id": "...",- "selector": {...},- "artifact": {"repository": "...", "manifest_digest": "sha256:...",- "layer_digest": "sha256:...", "payload_sha256": "..."},- "operation_digest": "..."}--where ``operation_digest`` is the SHA-256 of the compact JSON of the-same object without that field, with selector keys and list values-sorted. ``tree append`` fetches and verifies the current publication-(a missing one starts generation 1 with the package name as tree id),-pushes each artifact as a manifest tagged ``upatch-<id>-<payload16>``,-appends one operation per entry with ``seq = head + 1``, and-republishes with ``generation + 1`` and ``parent_manifest_digest`` set-to the manifest it replaced. A publication with a number outside the-signed 64-bit range, or a ``generation`` or ``head`` at its top that-leaves no successor, is refused. A ``delete`` publishes the entry's-unload directive and is accepted by a target only for an id it loaded-from the same tree.--9) Observability-------------------``shirudo status`` reports the machine it runs on: roles, version ID,-the conditions ``LsmAttached``, ``KeyringSealed``, ``ChainIntact`` and-``TpmMeasured`` with an ``OK``, ``WARN`` or ``ALERT`` verdict each, the-keyring serial against its pin, the register against this boot's-eventlog replay and its anchor, the on-disk assets, and with-``--include-system``, ``--include-eventlog``, ``--include-kernellog``-and ``--include-modules`` the corresponding detail. The register is-always read: a status that did not ask the TPM would be a status the-target wrote about itself. The overall-``status`` is ``ok``, ``degraded``, ``reboot-pending``,-``init-pending``, ``lsm-off`` or ``tampered``. ``--json`` emits the same as one document; ``--otel``-pushes it as a keepalive log record. ``status`` is the target's own-account of itself; ``shirudo attest`` (section 7) is the account the-TPM signs.--``shirudo upatch list``, ``info``, ``get`` and ``map`` inspect-artifacts and loaded state. ``info`` describes the container offline,-signed decoders included, and is advisory; ``get`` reads the loaded-program's ``line_info`` and BTF from the kernel and is authoritative.-``upatch map`` reads pinned maps, runs the upatch's signed Lua decoder,-and prints, appends NDJSON, or exports over OTLP. The export path, its-decoders and the collector integration are described in-`telemetry <telemetry.rst>`__.--Every command logs through ``syslog(3)`` as ``shirudo`` to-``LOG_AUTHPRIV``; ``journalctl -t shirudo`` shows it.--10) Failure reporting------------------------``upatch load`` and ``upatch unload`` take ``--report=<path>`` and write-one JSON document: ``result``, the ``phase`` reached (``pre_flight``,-``parse``, ``signed_loader_load``, ``payload_load``, ``link_create``,-``pin``, ``persist``, ``tpm_extend``, ``done``), ``errno`` and its-name, a ``category``, a message, the verifier log when the verifier-spoke, the loader's return value, the artifact's path and name, the-kernel release, and the NV index and chain value after the operation.--The categories are ``ok``, ``tampered``, ``keyring_missing``,-``lsm_denied``, ``signature_rejected``, ``signature_unsupported``,-``verifier_rejected``, ``parser_rejected``, ``btf_mismatch``,-``attach_target_missing``, ``binary_mismatch``,-``attach_scope_mismatch`` (the link the kernel made is not at the site-the metadata names: another cgroup, network namespace or PMU),-``payload_mismatch``, ``already_unloaded``, ``detach_failed``,-``tpm_error``, ``eventlog_full``, ``kernel_abi_unsupported``,-``init_prereqs_missing``, ``version_mismatch`` and ``unknown``.-Automation treats ``tampered`` as "refresh state, then decide", never-as "retry the same input": a concurrent legitimate operator produces-it too.--11) Runtime design---------------------The core binary never forks or execs; the one exception is the-operator-only ``shirudo build`` dispatch described above. Everything-else is a library call or a syscall: libbpf for BPF, raw ``keyctl``-for keyrings, tpm2-tss for the TPM, libcrypto for digests and-certificate parsing, libcurl over libssl for registries and OTLP,-libelf and zlib for objects, LuaJIT for decoders. The in-tree-``util/json.c`` is the only JSON code and ``util/parse-options.c`` the-only option parser. Nothing else is linked; every additional library-is attack surface.--Both profiles need OpenSSL 3.5 or newer for ML-DSA. The operator links-the system shared libraries. The target image (``make target``) links-a static OpenSSL, an OpenSSL-backed static libcurl and a static tpm2-tss-that ``make target-deps`` builds from source, plus static libbpf,-libelf, zlib, zstd and LuaJIT, so it runs on a-distribution whose OpenSSL predates ML-DSA. ``SHIRUDO_VERSION_ID``-hashes the source tree and build configuration, not binary bytes, so-the same source yields the same identity on x86-64, arm64 and riscv64;-the pre-flight refuses a ``version_mismatch``.--shirudo requires the signed-loader and BPF LSM interfaces in the validated-upstream development kernel and current upstream clang. The `requirements-<requirements.rst>`__ document identifies the tested bpf-next commit and-configuration. The signed-loader ABI check, rather than a release string,-rejects incompatible kernels; missing features fail the build or pre-flight.--12) Project layout---------------------::-- shirudo/- shirudo.c command dispatch table- builtin-*.c one file per top-level command- util/ shared userspace library- bpf/ bpf2.c, seal.c, unload.c, loaders- include/shirudo/ artifact and manifest definitions- tools/shirudo-build/ operator-only helper: compile, sign,- bpm build and publish, tree append- tools/gen-initrd/ dracut module, initrd generator,- installer- tools/gen-vmlinux-h/ vmlinux.h generator- tools/bpf-deps/ vendored libbpf refresh- upatches/ shipped packages with their Beefiles- vendor/libbpf/ vendored libbpf and UAPI headers- systemd/ target units and timers- packaging/ tar, deb and rpm packaging- testing/ TAP tests, test VM, swtpm- Documentation/ this tree--``shirudo help --list-cmds`` prints the supported command set.--13) Kernel work this design waits for----------------------------------------Several residual risks in the threat model are closed by kernel work in-flight rather than by shirudo code:--- the signed loader creating the link and pinning it, and detaching- and unloading in kernel, so the whole lifecycle is signature-covered- (residual risk 1);-- BPF in-kernel sockets, so keepalive, status and alerting can be sent- from kernel context without a userspace timer;-- xattr getters for kernfs, so ``security.bpf.*`` labels can be- enforced on cgroups;-- ``fmod_ret`` coverage of the whole kernel build, so a shield can- reject a call at any function rather than at the instrumented ones;-- signed-loader support for every program type, including struct_ops.--shirudo tracks the current upstream kernel; when one of these lands,-the corresponding shirudo change follows and the residual is removed-from the threat model.diff --git a/Documentation/concepts/background/boot.rst b/Documentation/concepts/background/boot.rstnew file mode 100644index 00000000..f1940d54--- /dev/null+++ b/Documentation/concepts/background/boot.rst@@ -0,0 +1,287 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++Boot process and measured boot+==============================++shirudo starts enforcement from the initrd, and everything it trusts+at that point came from the boot chain before it. This page explains+how a UEFI machine gets from power-on to the initrd, how Secure Boot+decides what may run, how measured boot records what did run, and+which component writes which TPM PCR. It ends with what shirudo takes+from each of these and where that stops.++From power-on to the initrd+---------------------------++Each stage of a boot runs code that the previous stage chose. The UEFI+firmware starts a boot loader from the EFI system partition, the boot+loader starts the kernel with a command line and an initrd, and the+initrd mounts the root file system and hands over to it. Whatever runs+``shirudo init`` in the initrd is only as trustworthy as every stage+that led to it.++Two mechanisms address this, and they answer different questions.+Secure Boot decides whether a stage may run at all. Measured boot+records what ran, so that someone else can decide afterwards whether+they trust it. A target needs both: Secure Boot keeps unsigned code+from starting, and measurements let a remote verifier tell which+signed code started.++Secure Boot, shim and MOK+-------------------------++With Secure Boot enabled, the firmware checks the signature of every+UEFI executable it starts against its signature database ``db`` and+refuses anything listed in the forbidden database ``dbx``. The+platform key ``PK`` and the key exchange keys ``KEK`` control who may+change those databases.++Most distributions boot through shim, a small first-stage loader+signed by Microsoft's UEFI certificate authority. shim carries the+distribution's certificate and verifies the next stage against it and+against the Machine Owner Key (MOK) list, which the machine's owner+enrolls through shim's ``MokManager``. This lets an owner sign their+own kernels or unified kernel images without changing the firmware's+databases.++Secure Boot verifies executables, not the data they load. A boot+loader that reads a kernel and a separate initrd file passes the+initrd to the kernel unchecked, and a command line typed at the boot+menu is not signed by anyone. That gap is the reason for unified+kernel images.++Unified kernel images+---------------------++A unified kernel image (UKI) is one PE executable that bundles the+``systemd-stub`` boot stub with the kernel (``.linux``), the initrd+(``.initrd``), the command line (``.cmdline``) and further sections+such as ``.osrel``, ``.uname`` and ``.sbat``. The firmware or shim+verifies the whole file once, so the signature covers the initrd and+the command line together with the kernel.++When Secure Boot is enabled and the UKI has a ``.cmdline`` section,+``systemd-stub`` ignores any command line a boot loader passes to+it. The command line that reaches the kernel is then exactly the+signed one.++Kernel command line+-------------------++The command line configures the kernel before any userspace runs, and+some parameters change security properties. ``lsm=``, for example,+selects which LSMs run, and a list without ``bpf`` leaves no BPF LSM+for shirudo to attach to. shirudo needs two parameters of its own:+``bpf.keyring_unsealed=1`` and ``dm_verity.keyring_unsealed=1``. They+leave the kernel's ``.bpf`` and ``.dm-verity`` keyrings open until+``shirudo init`` enrolls its certificates and seals them, see+:doc:`keyrings`. Whoever can edit the command line at the boot menu+can change all of this, so the parameters belong in the UKI's+``.cmdline`` section, where Secure Boot covers them and PCR 11 records+them.++Measured boot+-------------++A TPM has a set of platform configuration registers (PCRs). A PCR+cannot be written, only extended: the TPM replaces its value with the+hash of the old value and a new digest. Each boot stage hashes the+next stage, or a piece of configuration, and extends a PCR with the+result before handing over. Because extension is ordered and one-way,+the final value of a PCR commits to every measurement and to their+order, and no later code can bring back an earlier value. Only a new+TPM startup, at a reboot or a resume from hibernation, returns them to+their initial values.+:doc:`tpm` explains PCRs and banks in more detail.++A PCR value alone says little. Each measuring component also appends+an entry to an event log, and a verifier replays the log to check that+it produces the quoted PCR value and then judges the entries. The logs+are not protected; the PCRs are what make them trustworthy. Linux+exposes the firmware's log, which also holds what the boot loader and+the kernel's EFI stub measured before the kernel took over, at+``/sys/kernel/security/tpm0/binary_bios_measurements``. systemd keeps+its userspace log at ``/run/log/systemd/tpm2-measure.log``.++Table 1 lists the common assignments on a Linux system that boots a+UKI. The TCG PC Client firmware profile defines PCRs 0 to 7. The+Linux TPM PCR Registry of the UAPI group lists what Linux components+use, and systemd's documentation of its measurements gives the+details.++.. list-table:: Table 1. PCR assignments relevant to shirudo+ :header-rows: 1+ :widths: 10 30 60++ * - PCR+ - Measured by+ - What+ * - 0-3+ - Firmware+ - Firmware code and configuration, option ROMs and their data.+ * - 4+ - Firmware, shim+ - Each UEFI executable started: shim, the boot loader, the UKI.+ * - 5+ - Firmware, ``systemd-boot``+ - The GPT partition table; ``systemd-boot``'s ``loader.conf``.+ * - 7+ - Firmware, shim+ - The Secure Boot state and the certificates used; shim adds its+ own certificates and SBAT data.+ * - 8+ - GRUB+ - GRUB commands and the kernel command line, when GRUB boots.+ * - 9+ - Kernel EFI stub, GRUB, systemd, shirudo+ - The initrd and the command line the kernel's EFI stub receives;+ files GRUB reads; systemd's NvPCR anchors and separators;+ shirudo's anchor.+ * - 10+ - IMA+ - The IMA measurement list, when IMA is enabled.+ * - 11+ - ``systemd-stub``, ``systemd-pcrphase``+ - Every section of the UKI except ``.pcrsig``; the boot phase+ strings.+ * - 12+ - ``systemd-stub``+ - A command line passed in place of ``.cmdline``, credentials,+ configuration extensions and add-ons.+ * - 13+ - ``systemd-stub``+ - System extension images for the initrd.+ * - 14+ - shim+ - The MOK list.+ * - 15+ - systemd+ - The machine ID, file system identities and LUKS volume keys.++The kernel's own PCR 9 measurements are made by its EFI stub, in+``drivers/firmware/efi/libstub/efi-stub-helper.c``. It extends PCR 9+with the initrd as a tagged event ``Linux initrd`` and, when it is not+empty, with the command line as ``LOADED_IMAGE::LoadOptions``.++Boot phases in PCR 11+---------------------++PCR 11 is predictable. ``systemd-stub`` measures only the UKI's+sections into it, so a vendor can compute its value from the UKI file+alone. systemd then extends it at fixed points of the boot with phase+strings: ``enter-initrd``, ``leave-initrd``, ``sysinit``, ``ready``,+``shutdown`` and ``final``, in this order.+``systemd-pcrphase-initrd.service`` extends ``enter-initrd`` when it+starts, early in the initrd, and ``leave-initrd`` when it stops, right+before the switch to the root file system.++So the value PCR 11 holds while the initrd runs exists only in the+initrd. Once ``leave-initrd`` is measured, nothing can bring that+value back before the next TPM reset. A TPM object whose policy+requires that value can be used from the initrd and from nowhere else.+``systemd-measure calculate --phase=enter-initrd`` computes the value+from the UKI.++systemd makes these phase measurements only when the kernel was+started by ``systemd-stub`` from a UKI. A kernel and initrd that a+boot loader or QEMU loads separately leave PCR 11 without them.++NvPCRs+------++A PC Client TPM has 24 PCRs, and most of them have an owner. systemd+259 and later add NvPCRs: TPM NV indices of the extend type, which+behave like PCRs but are allocated from NV index space and defined by+``/usr/lib/nvpcr/*.nvpcr`` files. An NV index can be deleted and+recreated by anyone who satisfies the owner authorization, which is+often empty, so systemd protects an NvPCR in two ways.++Its write policy allows the first write only from the initrd, through+a policy on PCR 11, and later writes need no further authorization.+And ``systemd-tpm2-setup-early.service`` extends PCR 9 with the+index's name as ``nvpcr-init:<name>:0x<handle>:<tpm-name>``, so a+recreated index with other attributes or another policy has a name+that does not match the one PCR 9 recorded.+``systemd-pcrnvdone.service`` then extends PCR 9 with+``nvpcr-separator`` to mark the end of the initializations.++shirudo's measurement register follows this construction with one+important difference: every write, not only the first, needs a+signature from a TPM-held key and is checked by an LSM hook.+:doc:`tpm` describes it.++How shirudo uses the boot chain+-------------------------------++A production target boots a UKI whose initrd carries the shirudo+bootstrap binary, ``shirudo-initrd.service`` and the bootstrap+settings, including ``runtime.image`` and ``runtime.root_hash``, the+expected root hash of the dm-verity runtime image. Its ``.cmdline``+carries the two keyring parameters. The dracut module and+``shirudo-gen-initrd`` build the initrd, see :doc:`initrd-dracut`.+shirudo does not build or sign the UKI.++The boot chain gives shirudo an authenticated starting point. Secure+Boot ensures the initrd and command line are the signed ones, and the+root hash in the initrd's settings then authenticates the runtime+image, see :doc:`dm-verity`. shirudo itself checks neither the Secure+Boot state nor kernel lockdown. It relies on the deployment to enable+Secure Boot, and a verifier can check PCR 7 in the evidence.++``shirudo-initrd.service`` orders itself after+``systemd-pcrphase-initrd.service`` and+``systemd-tpm2-setup-early.service`` and before the switch to the root+file system. When it runs ``shirudo init``, PCR 11 therefore holds the+``enter-initrd`` value and PCR 9 holds the initrd, the command line and+any NvPCR anchors. ``init`` reads both values, binds its measurement+register to them and extends PCR 9 with its own anchor. Once+``leave-initrd`` is measured, the register can no longer be bound+again this boot. Its record waits in ``/run/shirudo/eventlog.pending``+until ``shirudo.service`` re-runs ``init`` from the root file system+and adopts it without another TPM extension. :doc:`tpm` explains the+binding, and :doc:`/internals/boot-flow` gives the whole sequence.++A remote verifier ties all of this together. ``shirudo attest`` quotes+PCRs 0 to 7, 9 and 11 to 15 by default, and the operator pins the PCR 9+and PCR 11 values the register was bound under with+``--expect-bind-pcr``, computing the PCR 11 value from the UKI. See+:doc:`/operate/attest`.++Limits+------++- Without a UKI booted through ``systemd-stub``, PCR 11 holds no phase+ measurement. ``init`` warns, and only PCR 9 can tell an initrd+ binding from a later one.+- Measured boot records and does not prevent. A host booted with+ another UKI, or one where the initrd run of ``init`` failed, still+ comes up. Only a verifier that compares the quoted PCRs and the+ register binding with approved values notices. The+ :doc:`/security/threat-model` describes the fail-open boot.+- ``shirudo-initrd.service`` is not ordered against+ ``systemd-pcrnvdone.service``, and any process that can send TPM+ commands can extend PCR 9. When PCR 9 holds measurements after+ shirudo's anchor, the anchor check in ``attest verify`` is a note,+ and ``--strict-anchor`` turns it into a failure.+- The evidence carries the firmware and systemd event logs, but+ ``attest verify`` does not replay them. It compares the PCR values+ the operator pins with ``--expect-pcr`` and ``--expect-bind-pcr``.++Related+-------++- :doc:`tpm` for PCRs, NV indices and the register binding.+- :doc:`initrd-dracut` for the initrd shirudo runs from.+- :doc:`/internals/boot-flow` for the initrd and root runs of ``init``.+- :doc:`/operate/boot-integration` to set up the boot of a target.+- `TPM2 PCR Measurements Made by systemd+ <https://systemd.io/TPM2_PCR_MEASUREMENTS/>`__+- `UAPI.7 Linux TPM PCR Registry+ <https://uapi-group.org/specifications/specs/linux_tpm_pcr_registry/>`__+- `UAPI.5 Unified Kernel Image+ <https://uapi-group.org/specifications/specs/unified_kernel_image/>`__diff --git a/Documentation/concepts/background/bpf-lsm.rst b/Documentation/concepts/background/bpf-lsm.rstnew file mode 100644index 00000000..7fc2d0a6--- /dev/null+++ b/Documentation/concepts/background/bpf-lsm.rst@@ -0,0 +1,158 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++BPF LSM+=======++File permissions and capabilities decide most access checks in Linux,+and root passes nearly all of them. A policy that must hold against root+needs a check that runs inside the kernel, at the operation itself, and+that root cannot turn off. Linux security modules (LSMs) provide those+checks, and the BPF LSM lets BPF programs act as one. This page explains+the parts of the LSM framework shirudo builds on.++LSM hooks+---------++The kernel calls into the LSM framework at fixed points: before a file is+opened (``file_open``), before an inode is unlinked (``inode_unlink``),+at the entry of the ``bpf()`` system call (``bpf``), before a key is used+(``key_permission``), and at a few hundred other places. Each such call+site is a hook. A hook passes the objects involved, such as the file,+the inode or the key, and most hooks return an integer: ``0`` allows the+operation, a negative error number refuses it, and the system call fails+with that error.++A hook can only refuse what reaches it. An operation the kernel routes+past every hook cannot be denied by any LSM; ``mount_setattr(2)``, for+example, calls no LSM hook.++Stacking and order+------------------++Several LSMs can be active at once: SELinux or AppArmor, Yama, Landlock,+IMA, the BPF LSM and others. For each hook, the kernel calls every active+LSM that implements it, in order, and stops at the first one that+returns a refusal. The capability checks always run first, and IMA and+EVM always run last.++The order of the others comes from ``CONFIG_LSM`` or, if given, the+``lsm=`` kernel parameter, which overrides it. An LSM that is built in+but missing from that list does not run. ``/sys/kernel/security/lsm``+lists the active LSMs of the running kernel.++Because the first refusal ends the walk, an LSM placed late in the list+does not see an operation that an earlier one already refused.++BPF programs on LSM hooks+-------------------------++With ``CONFIG_BPF_LSM`` and ``bpf`` in the active list, the BPF LSM+registers an empty default function for nearly every hook. A program of+type ``BPF_PROG_TYPE_LSM`` attaches to one of these through a BPF+trampoline, with ``BPF_RAW_TRACEPOINT_OPEN`` or ``BPF_LINK_CREATE``, and+then runs whenever the kernel calls that hook. In source, the section+name names the hook, as in ``SEC("lsm/file_open")``. The kernel refuses+programs whose license is not GPL-compatible, and a small set of hooks+takes no BPF programs at all.++If ``bpf`` is missing from the active list, the kernel never calls the+BPF LSM's functions, so programs attached there never run.++On a hook that returns an integer, a program receives the hook's+arguments plus one more, ``ret``: the value the previous BPF program on+the same hook returned, or ``0`` for the first. By convention, a program+that sees a non-zero ``ret`` returns it unchanged, so that one refusal is+not overwritten by a later program.++Return values+-------------++The verifier restricts what an LSM program may return. For a hook that+returns an integer, the program returns ``0`` or a negative error number.+A few hooks return a boolean, and the program returns ``0`` or ``1``. A+hook that returns nothing, such as ``bprm_committed_creds``, only+observes; its program cannot refuse anything and is used to record+state.++Sleepable hooks+---------------++Some hooks run where the kernel may sleep. A program attached to one of+them with the ``lsm.s/`` section prefix is loaded as sleepable and may+call kfuncs that sleep, such as the ones that read extended attributes+(see :doc:`xattrs`). The kernel keeps a list of the hooks that accept+sleepable programs and refuses the ``lsm.s/`` form on any other hook.++Task and inode storage+----------------------++An LSM program often needs to remember something about a kernel object:+that a task has some authority, or that an inode carries some label. Two+map types attach that state to the object itself. A+``BPF_MAP_TYPE_TASK_STORAGE`` map holds one value per task, and a+``BPF_MAP_TYPE_INODE_STORAGE`` map one value per in-memory inode.++The value lives as long as the object. It is freed when the task exits,+or when the inode leaves the inode cache, even if the file still exists+on disk. Inode storage needs the BPF LSM to be active at boot; without it+the kernel refuses to create such a map.++Kernel argument of the bpf hook+-------------------------------++The ``bpf`` hook runs at the entry of every ``bpf()`` call. Its last+argument, ``kernel``, is ``true`` when the call came from inside the+kernel rather than from a userspace process. That is the case for calls a+signed loader makes through the ``bpf_sys_bpf()`` helper (see+:doc:`bpf`) and for BPF that kernel code loads itself. The+``bpf_prog_load`` and ``bpf_map_create`` hooks carry the same argument.++This one bit lets a policy close ``bpf()`` to userspace while leaving it+open to code that is already inside the kernel: the loader passed the+policy's checks when userspace loaded it, so what it does next does not+have to pass them again.++How shirudo uses the BPF LSM+----------------------------++shirudo's enforcement is two BPF objects of LSM programs, ``bpf2`` and+``seal``, embedded in the binary. ``shirudo init`` checks that ``bpf``+appears in ``/sys/kernel/security/lsm`` (preflight check+``bpf_lsm_active``), loads both objects, attaches every program and pins+the links in its private bpffs.++``bpf2`` gates BPF itself. Its ``lsm/bpf`` program returns ``0`` at once+when ``kernel`` is set; for userspace callers it admits only a signed+loader's ``BPF_PROG_LOAD``, the commands the signed-loader pattern needs+from a task with runtime authority, and read-only commands, and refuses+every other command. ``lsm/bpf_prog_load`` checks the signature verdict+(see :doc:`bpf-signing`). Further ``bpf2`` programs guard, among other+things, the private bpffs and its mount, the kernel keyrings, the+device-mapper controls and the TPM.++``seal`` protects writable state and decides which tasks have runtime+authority. A task gains it by a successful exec of a binary from the+verified runtime image. A ``BPF_MAP_TYPE_TASK_STORAGE`` map records the+mark, ``lsm/task_alloc`` passes it to children, and the void hook+``lsm.s/bprm_committed_creds`` commits or clears it after each exec. A+``BPF_MAP_TYPE_INODE_STORAGE`` map caches the seal label of directories.+Many seal programs are sleepable because they read extended attributes.++See :doc:`/internals/enforcement` for the inventory of hooks and+:doc:`/internals/seal` for the seal.++Limits+------++The BPF LSM refuses only what reaches its hooks. Operations without a+hook, and access to the machine below the kernel, are outside it. When+an earlier LSM in the list refuses an operation, shirudo's program for+that hook does not run, so the refusal moves none of shirudo's tamper+counters. Inode storage is lost when an inode leaves the cache, which is+a limitation of the seal's directory marks. :doc:`/security/threat-model`+lists the residual risks.diff --git a/Documentation/concepts/background/bpf-signing.rst b/Documentation/concepts/background/bpf-signing.rstnew file mode 100644index 00000000..a4f180b0--- /dev/null+++ b/Documentation/concepts/background/bpf-signing.rst@@ -0,0 +1,221 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++BPF program signing in the kernel+=================================++The kernel can check a signature over BPF code when it is loaded. The+check establishes who produced the code and that nobody changed it on the+way. It does not stop an unsigned load by itself: the kernel records a+verdict, and a security module decides what to do with it. This page+explains the mechanism, then how shirudo builds on it and where it stops.++Why a program cannot be signed directly+---------------------------------------++The obvious scheme signs a program's instructions at build time and+checks the signature at ``BPF_PROG_LOAD``. It fails because the bytes the+kernel finally loads are not the bytes that were built. Between the two,+libbpf and the kernel rewrite the program:++- map file descriptors are patched into instructions, and a descriptor+ number differs on every run;+- CO-RE relocations rewrite field offsets for the running kernel (see+ :doc:`co-re-btf`);+- references to kfuncs and kernel symbols are resolved to the running+ kernel;+- global data is created and filled as maps at load time.++No fixed byte string is both signable at build time and what the kernel+loads.++Signed loader+-------------++The kernel's answer is to move that rewriting into a small BPF program,+the loader, and to sign the loader instead of the programs. libbpf's+gen_loader emits the loader as a ``BPF_PROG_TYPE_SYSCALL`` program (see+:doc:`bpf`). Its data, everything it installs, lives in a separate array+map, the metadata map. The signature covers both::++ Sig(I_loader || D_meta)++``I_loader`` is the loader's instruction stream and ``D_meta`` the+content of the metadata map. Both are the same on every kernel: the+loader's instructions carry no relocations and refer to the metadata map+by its index in the load's ``fd_array``, not by a descriptor number. The+host-specific rewriting still happens, inside the loader at run time, on+data the kernel has already verified.++Two map properties keep the metadata map trustworthy between the check+and the run:++Exclusive maps+ A map created with ``excl_prog_hash`` may only be used by a program+ whose SHA-256 digest matches that hash. The metadata map is bound to+ exactly one loader.++Frozen maps+ The metadata map is frozen with ``BPF_MAP_FREEZE`` before the loader+ is loaded, so userspace cannot change the signed bytes afterwards.++Verification inside the verifier+--------------------------------++The loader is loaded with ``signature``, ``signature_size`` and+``keyring_id`` set, the metadata map in ``fd_array``, and+``fd_array_cnt`` set so that the kernel resolves every entry up front.+The checks then run in this order:++#. ``security_bpf()`` (``lsm/bpf``) runs at the entry of the ``bpf()``+ system call, before any of what follows.+#. Inside ``bpf_check()``, the kernel resolves ``fd_array`` into the maps+ the program uses.+#. ``bpf_prog_verify_signature()`` refuses a signed program that carries+ CO-RE relocations, checks that each bound map is an exclusive, frozen+ array map without active writers, appends each map's contents to the+ instructions in order and verifies the PKCS#7 signature over the+ result.+#. ``security_bpf_prog_load()`` (``lsm/bpf_prog_load``) runs with the+ verdict already recorded.+#. The verifier analyzes the program. Any map the signature does not+ cover, and any BTF, is refused when the verifier tries to bind it.++Because the maps folded into the signature are the ones the program+binds, from a single resolution of ``fd_array``, nothing can swap the+verified bytes for others after the check.++Verdict+-------++The kernel records the outcome in ``prog->aux->sig``. The verdict is+``BPF_SIG_UNSIGNED`` or ``BPF_SIG_VERIFIED``; there is no partial state.+A signature that fails verification aborts the load. Beside the verdict+the kernel records which kind of keyring verified the signature and, for+a keyring the caller supplied, its serial:++.. list-table::+ :header-rows: 1+ :widths: 40 35 25++ * - ``keyring_id``+ - ``keyring_type``+ - ``keyring_serial``+ * - ``0``+ - ``BPF_SIG_KEYRING_BUILTIN``+ - ``0``+ * - ``VERIFY_USE_SECONDARY_KEYRING`` (``1``)+ - ``BPF_SIG_KEYRING_SECONDARY``+ - ``0``+ * - ``VERIFY_USE_PLATFORM_KEYRING`` (``2``)+ - ``BPF_SIG_KEYRING_PLATFORM``+ - ``0``+ * - ``KEY_SPEC_BPF_KEYRING`` (``-9``)+ - ``BPF_SIG_KEYRING_BPF``+ - ``0``+ * - any other key or keyring+ - ``BPF_SIG_KEYRING_USER``+ - its serial++The system keyrings and the ``.bpf`` keyring are trusted as a whole and+expose no serial, so a policy tells them apart by ``keyring_type``. See+:doc:`keyrings` for what each keyring holds.++BPF keyring+-----------++A key in a system keyring is trusted for more than BPF, for kernel+modules for example. A keyring the caller supplies is filled by the same+process that loads the program, so it carries no trust of its own. The+``.bpf`` keyring fills the gap: a keyring scoped to BPF program loading,+provisioned at boot.++The kernel creates ``.bpf`` sealed and empty: it carries a restriction+that rejects every key, and a load that names it fails with ``-ENOKEY``.+Booting with ``bpf.keyring_unsealed=1`` leaves it open so that the initrd+can add keys and then restrict it. The kernel consults ``.bpf`` only once+it is both non-empty and restricted, so a half-provisioned keyring is+inert rather than weak.++``bpf.keyring_unsealed=1`` also makes ``.bpf`` the only non-system+keyring a loader may name for the rest of the boot. From the first load+on, a caller-supplied keyring is refused with ``-EPERM``, whether or not+provisioning completed. The builtin, secondary and platform keyrings+stay selectable.++Kernel records, LSM decides+---------------------------++Signing does not change the permission model. A signed load still needs+the usual privileges, and an unsigned load proceeds as before unless a+security module refuses it. A policy that requires signatures acts at+``lsm/bpf_prog_load``: deny unless the verdict is ``BPF_SIG_VERIFIED``+and the keyring is the one the policy trusts. The kernel then refuses on+its own any loader that uses a map its signature does not cover, so the+admission hook needs no second enforcement point. See :doc:`bpf-lsm` for+how such a policy is attached.++How shirudo uses it+-------------------++``shirudo build`` runs gen_loader with ``gen_hash`` set. In that mode+the loader takes map sizes and initial values only from its signed data,+never from the context the caller passes at run time. The build appends+the upatch's name, attach metadata and decoders to the loader's data as+signed sections and signs ``loader_insns || data`` with the operator's+ML-DSA-87 key. Everything the target later trusts about the upatch is+inside that signature.++``shirudo upatch load`` on the target:++#. creates the metadata map ``__loader.map`` as a single-entry array whose+ ``excl_prog_hash`` is the SHA-256 of the loader's instructions;+#. writes the signed data into it and freezes it;+#. loads the loader as a sleepable ``BPF_PROG_TYPE_SYSCALL`` program with+ the signature, ``keyring_id`` set to ``KEY_SPEC_BPF_KEYRING``, the map+ in ``fd_array`` and ``fd_array_cnt`` set to ``1``;+#. runs the loader with ``BPF_PROG_TEST_RUN``. The loader creates the+ payload's maps and loads its programs from inside the kernel.++shirudo's ``lsm/bpf`` program admits a ``BPF_PROG_LOAD`` from userspace+only for a ``BPF_PROG_TYPE_SYSCALL`` program with a non-zero signature+size. Its ``lsm/bpf_prog_load`` program admits a userspace load only with+verdict ``BPF_SIG_VERIFIED`` and keyring type ``BPF_SIG_KEYRING_BPF``.+Both allow calls with ``kernel`` set, which is how the loader's own calls+pass. ``shirudo init`` enrolls the operator's certificates in ``.bpf``+and seals it from the initrd (see :doc:`keyrings`).++A failed signature check maps to a failure category: ``-EKEYREJECTED`` to+``signature_rejected``, ``-ENOKEY`` to ``keyring_missing``, ``-ENOPKG``+(a kernel without the ML-DSA verifier) to ``signature_unsupported``. See+:doc:`/internals/signed-loader` for the full load path and+:doc:`/internals/enforcement` for the admission hooks.++Limits+------++A valid signature establishes origin and integrity, not safety, and not+time. Any artifact ever signed by an enrolled key passes the kernel's+check, so root, which can run shirudo's runtime binary, can choose which+signed upatches run and when. The measurement register records every+such choice; see :doc:`/concepts/measurement-register`.++The ``kernel`` argument is also set for BPF that kernel code loads+itself, such as the in-kernel light skeleton of the ``bpf_preload``+module. shirudo's admission programs allow those loads as they allow a+signed loader's own calls.++shirudo's two enforcement objects are not signed. ``shirudo init`` loads+them before their admission programs attach; production targets+authenticate them as part of the initrd. See+:doc:`/internals/boot-flow`.++Signing covers eBPF loaded through ``bpf()``. Classic BPF filters, such+as seccomp filters and socket filters attached with ``SO_ATTACH_FILTER``,+do not pass through it. The kernel verifies the instructions and folded+metadata as one buffer of at most about 16 MiB. The threat model lists+the residual risks: :doc:`/security/threat-model`.diff --git a/Documentation/concepts/background/bpf.rst b/Documentation/concepts/background/bpf.rstnew file mode 100644index 00000000..04fc48fb--- /dev/null+++ b/Documentation/concepts/background/bpf.rst@@ -0,0 +1,158 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++BPF in brief+============++The Linux kernel can run small programs that userspace hands it at run+time, at points the kernel defines, without a kernel module and without a+reboot. This mechanism is BPF. shirudo uses it twice: its own enforcement+is a set of BPF programs, and every upatch it ships is one. This page+explains the parts of BPF that the rest of the documentation relies on.++Programs and the verifier+-------------------------++A BPF program is a sequence of instructions for a small virtual machine+with ten general-purpose 64-bit registers and a read-only frame pointer.+Userspace passes the instructions to the kernel with the ``bpf()``+system call and its ``BPF_PROG_LOAD`` command.++The kernel does not trust these instructions. Before it accepts a+program, the verifier walks every path through it and tracks the type+and value range of every register and stack slot. It rejects a program+that could read uninitialized memory, access memory out of bounds, call a+function it may not call or fail to terminate. A program that passes is+translated to native code by the JIT compiler.++Every program has a type, such as ``BPF_PROG_TYPE_LSM`` or+``BPF_PROG_TYPE_CGROUP_SKB``. The type decides where the program can run,+what context it receives as its argument and which functions it may+call.++The verifier proves that a program is safe to run in the kernel. It does+not prove that the program does what its author meant: a program that+passes can still deny an operation it should allow, or slow down a hot+path. Trust in who wrote a program has to come from somewhere else, which+is what :doc:`bpf-signing` provides.++Maps+----++A program keeps state in maps, key-value stores that live in the kernel.+A map has a type (array, hash, per-task storage, ring buffer, arena and+others), a key size, a value size and a maximum number of entries.++A program refers to a map through an instruction that the loader patches+with the map's reference before the load. Userspace reaches the same map+through a file descriptor and the map commands of ``bpf()``, such as+``BPF_MAP_LOOKUP_ELEM`` and ``BPF_MAP_UPDATE_ELEM``. ``BPF_MAP_FREEZE``+makes a map read-only to userspace for the rest of its life. Programs can+still write a frozen map.++Helpers and kfuncs+------------------++A program cannot call arbitrary kernel functions. It can call helpers, a+fixed set of functions with numbers in the kernel's userspace API, such+as ``bpf_map_lookup_elem()``. It can also call kfuncs, kernel functions+that the kernel exports to BPF and describes in its type information.++Helpers are a stable interface. kfuncs are not: they can change or+disappear between kernel releases, and each is available only to the+program types and hooks the kernel registers it for. The verifier checks+every call against the function's prototype.++Attach points and links+-----------------------++Loading a program does not run it. A program runs once it is attached to+a hook: the entry or exit of a kernel function, an LSM hook, a+tracepoint, a kprobe, the packet path of a cgroup or a netfilter hook.++The attachment is a kernel object of its own, a BPF link. Userspace+creates it with ``BPF_LINK_CREATE`` or, for some tracing and LSM+programs, with ``BPF_RAW_TRACEPOINT_OPEN``. While the link exists, the+program runs at the hook. When the last reference to the link goes away,+the kernel detaches the program.++Pinning in bpffs+----------------++Programs, maps and links are reference counted. A file descriptor holds+a reference, and so does a program's use of a map. When a process+exits, its descriptors close, and an object that nothing else holds is+freed. An attached program detaches with its link.++To make an object outlive the process that created it, userspace pins+it. ``BPF_OBJ_PIN`` creates a file for the object in a BPF file system,+bpffs (file system type ``bpf``). The pin holds a reference until it is+removed, and ``BPF_OBJ_GET`` turns a pin back into a file descriptor.++A pin is an inode, so file system operations apply to it. Removing the+file drops its reference, and unmounting a bpffs instance that no other+mount shares drops every pin in it.++Programs that load programs+---------------------------++A program of type ``BPF_PROG_TYPE_SYSCALL`` attaches nowhere. Userspace+runs it on demand with ``BPF_PROG_TEST_RUN``. It is always sleepable and+may call the ``bpf_sys_bpf()`` helper, which issues a subset of+``bpf()`` commands from inside the kernel: it creates, updates and+freezes maps, loads programs and type information, and creates links.++libbpf's gen_loader turns a whole BPF object into one such program, the+loader, plus a data blob that holds everything the loader needs: the+programs' instructions, the map definitions with their initial contents,+and the relocation records. A light skeleton, generated with+``bpftool gen skeleton -L``, wraps the loader and its data in a C header.+The generated code places the data in an array map, loads the loader and+runs it. The loader then creates the maps and loads the programs.++A loader issues its ``bpf()`` commands from inside the kernel. The LSM+hooks therefore see them with their ``kernel`` argument set, which is how+a policy can tell a loader's calls from those of a userspace process (see+:doc:`bpf-lsm`). gen_loader emits no attachments, so the process that ran+the loader attaches and pins the programs itself.++How shirudo uses BPF+--------------------++shirudo uses BPF for its enforcement and for upatches.++The ``shirudo`` binary embeds two BPF objects, ``bpf2`` and ``seal``,+that hold its LSM programs. ``shirudo init`` loads them with libbpf,+attaches each program to its hook and pins every link under+``/run/shirudo/bpffs``, a private bpffs that init mounts with mode+``0700``. shirudo runs no daemon that could hold descriptors instead, so+these pins are what keep enforcement attached after init exits. See+:doc:`/internals/enforcement` and :doc:`/internals/seal`.++An upatch carries a signed loader that gen_loader produced on the+operator host. ``shirudo upatch load`` loads the loader with its+signature, runs it with ``BPF_PROG_TEST_RUN``, attaches the payload+programs the loader created and pins their links under+``/run/shirudo/bpffs/upatches/<name>/``, with the upatch's maps under+``maps/`` beside them. See+:doc:`/internals/signed-loader` and :doc:`/upatches/attach-kinds`.++Because the pins are all that hold these links, shirudo's LSM programs+refuse to remove or rename an entry in the private bpffs for any task+without runtime authority, and refuse to unmount it for every task. They+also refuse tasks without runtime authority a descriptor to the pinned+maps and links, by pin or by id.++Limits+------++The verifier bounds what a program can do to the kernel, not what it+decides. An upatch that passes the verifier can still break a workload by+denying the wrong operation. shirudo signs and measures upatches so that+an operator knows which programs run; it does not judge whether they are+correct. See :doc:`/upatches/testing` for testing an upatch before it+ships.diff --git a/Documentation/concepts/background/co-re-btf.rst b/Documentation/concepts/background/co-re-btf.rstnew file mode 100644index 00000000..43a423e4--- /dev/null+++ b/Documentation/concepts/background/co-re-btf.rst@@ -0,0 +1,159 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++CO-RE and BTF+=============++A BPF program that reads kernel data structures depends on their layout,+and the layout changes between kernel versions and configurations. CO-RE+("compile once, run everywhere") lets one compiled program run on kernels+whose layouts differ. It rests on BTF, the type information the kernel+carries about itself. This page explains both, and why every upatch is+built this way.++Why struct offsets are a problem+--------------------------------++Consider an LSM program that reads ``file->f_inode``. The compiler turns+that expression into a load from a fixed offset into ``struct file``. The+offset is right for the kernel whose headers the program was compiled+against. Another kernel version, or the same version built with a+different configuration, may add, remove or reorder fields, and the same+instruction then reads some other field.++The obvious fix is to compile the program on each target, against that+target's headers. That needs a compiler and kernel headers on every+target. It also defeats signing: the operator signs bytes, and bytes+compiled on the target were never signed.++BTF+---++BTF (BPF Type Format) is a compact encoding of C types: structs and+unions with their members, offsets and sizes, enums, typedefs and+function prototypes. clang emits BTF for a BPF object compiled with+``-g`` into the ``.BTF`` section. It also writes ``.BTF.ext``, which holds+per-instruction information: function and line records and the CO-RE+relocations described below.++A kernel built with ``CONFIG_DEBUG_INFO_BTF`` carries BTF for all of its+own types and exposes it at ``/sys/kernel/btf/vmlinux``. With+``CONFIG_DEBUG_INFO_BTF_MODULES``, each module's types appear under+``/sys/kernel/btf/`` too. The verifier uses this vmlinux BTF to type-check+accesses through kernel pointers in tracing and LSM programs, and CO-RE+resolves against it.++A header generated from vmlinux BTF, ``vmlinux.h``, declares every kernel+type, so a BPF program needs no kernel headers. The generator marks every+struct and union with clang's ``preserve_access_index`` attribute, which+makes each field access in the program relocatable.++Relocations+-----------++For each access to a field of such a type, or each one wrapped in+``BPF_CORE_READ()``, clang emits the instruction with the offset it knows+from the local header. It also records a CO-RE relocation: which+instruction, which type, and the access path by member name, such as+member ``f_inode`` of ``struct file``.++At load time, a type of the same name is looked up in the target+kernel's BTF, the same path is followed by member name, and the+instruction is patched with the offset found there. Other relocation+kinds answer other questions: whether a field or type exists, how large a+field is, what value an enumerator has. A type name with a ``___suffix``+matches the kernel type without the suffix, which lets one program carry+definitions for several kernel variants.++A relocation that cannot be resolved, because the field does not exist+on the target, does not fail the load at once. The instruction is+replaced by an invalid call. If the program can reach that instruction,+the verifier rejects the program with this message:++.. code-block:: text++ invalid func unknown#195896080++If the instruction sits behind a ``bpf_core_field_exists()`` check that+is false on this kernel, the verifier never reaches it and the program+loads.++Who applies the relocations+---------------------------++Usually libbpf applies the relocations in userspace before it calls+``BPF_PROG_LOAD``, reading the target's BTF from+``/sys/kernel/btf/vmlinux``.++A loader generated by gen_loader (see :doc:`bpf`) cannot do that, because+it runs inside the kernel. It passes the relocation records to the kernel+together with each program it loads, and the kernel applies them itself,+against its own BTF, before the verifier analyzes the program.++The signed loader itself carries no CO-RE relocations. The kernel refuses+a signed program that does, because the relocations would rewrite signed+instructions with values the caller chooses, and logs:++.. code-block:: text++ signed program cannot carry CO-RE relocations++The records the payload needs travel in the loader's data, which the+signature covers (see :doc:`bpf-signing`).++How shirudo uses CO-RE+----------------------++``shirudo build`` compiles a ``.bpf.c`` file with+``clang -target bpf -O2 -g`` against a ``vmlinux.h`` and hands the object+to gen_loader. Unless+the operator names a header, the build uses ``./vmlinux.h``, then+``./vendor/linux/vmlinux.h``, then the copy installed with shirudo+(``shirudo/vmlinux.h`` under the data directory, ``/usr/local/share`` by+default). The relocation records end up in the loader's data and are+signed with it.++On the target, the kernel resolves the records against its own BTF when+the loader loads the payload. One signed upatch therefore loads on every+kernel whose BTF has the types and fields it uses. A kernel without+``CONFIG_DEBUG_INFO_BTF`` has no BTF to resolve against, and shirudo's own+LSM programs need it as well.++shirudo's own enforcement objects are CO-RE as well. libbpf relocates+them in userspace when ``shirudo init`` loads them. They use+``bpf_core_field_offset()`` to find the ``struct mount`` that contains a+``struct vfsmount``, and ``bpf_core_field_exists()`` to handle a kernel+built without ``CONFIG_SECCOMP``, where ``struct seccomp`` is empty.++The ``vmlinux.h`` still has to declare every type a program names. The+admission program reads the signature verdict from+``struct bpf_prog_aux``, so shirudo itself needs a ``vmlinux.h`` from a+kernel with BPF signing.++What a mismatch looks like+--------------------------++An upatch that touches a field the target kernel lacks fails when the+loader loads the payload. ``shirudo upatch load`` reports category+``verifier_rejected`` in phase ``payload_load`` and includes the loader's+log, where the verifier's message for the payload appears. See+:doc:`/upatches/debugging` for reading that log and+:doc:`/reference/failure-categories` for the categories.++A program that hard-codes an offset carries no relocation, so nothing+adjusts it. Where the verifier can check the access against BTF, it may+reject the program. Otherwise the program loads and reads whatever lies+at that offset on the target kernel.++Limits+------++CO-RE matches types and fields by name and layout, not by meaning. A+field that keeps its name but changes what it holds relocates without+complaint, and a renamed field fails to relocate even if its meaning is+unchanged. An upatch built for one kernel release still needs testing on+every kernel it ships to; see :doc:`/upatches/testing`.diff --git a/Documentation/concepts/background/dm-verity.rst b/Documentation/concepts/background/dm-verity.rstnew file mode 100644index 00000000..89ea6748--- /dev/null+++ b/Documentation/concepts/background/dm-verity.rst@@ -0,0 +1,153 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++dm-verity+=========++shirudo runs from a read-only image whose every block the kernel checks+against a single trusted hash, and it reads its configuration from a+second image checked the same way. This page explains how dm-verity does+that, where the trusted hash comes from, and what dm-verity does not+protect.++Why signed files are not enough+-------------------------------++The binary that enforces the policy must be the one the operator built.+On a writable file system, root can replace it, edit a configuration file+beside it or swap a library underneath it. A signature checked when a+file is opened covers the bytes at that moment, and nothing ties later+reads to them.++What we want is a device on which no block can differ from what the+operator built, checked each time the kernel reads a block from it.++A hash tree over the device+---------------------------++dm-verity is a read-only device-mapper target. It combines a data device+with a hash device. The data device is divided into blocks, 4096 bytes in+shirudo's images, and the digest of each block is stored on the hash+device. The digests are packed into hash blocks, those blocks are hashed+in turn, and so on until one block remains. The digest of that block,+with a salt, is the root hash. Figure 1 shows a small tree.++.. figure:: /images/background-dm-verity-tree.svg+ :alt: A hash tree with a root hash over two hash blocks, four hash+ blocks below them and eight data blocks at the bottom. The path+ from data block D5 through H2 and H23 to the root is highlighted.++ Figure 1. A hash tree over eight data blocks, two children per node to+ keep the figure small. With SHA-256 and 4096-byte blocks, one hash+ block holds 128 digests. Changing D5 changes H2, H23 and the root+ hash.++The kernel does not hash the whole device up front. When a data block is+read from the device, dm-verity hashes it and checks the digest against+its hash block, then that hash block against the level above, up to the+root. A hash block that has passed once is remembered as verified, so+later reads stop there. If the chain does not end at the root hash the+device was set up with, the read fails. One trusted value therefore+vouches for every byte of the image.++Corruption handling+-------------------++By default a block that fails verification makes the read fail with+``EIO``. The kernel logs ``<data-device>: data block <n> is corrupted``+and sends a uevent, and from then on the device status reports the+corruption. Table options can instead only log the corruption+(``ignore_corruption``), restart the machine (``restart_on_corruption``)+or panic (``panic_on_corruption``). Optional forward error correction+can repair a block, which dm-verity then checks against its hash before+using it.++Where the root hash comes from+------------------------------++dm-verity does not decide which root hash is the right one. The kernel+expects whoever sets up the device to have been authenticated already.+There are two common ways to make a root hash trusted, and shirudo uses+both.++The first takes the root hash from something already trusted. shirudo's+runtime image, which holds its executables, gets its root hash from the+bootstrap settings in the initrd. In production, that initrd is part of+the unified kernel image, which Secure Boot verifies and the boot chain+measures into the TPM before the kernel runs (see :doc:`boot`).++The second signs the root hash. The table option+``root_hash_sig_key_desc`` names a key of type ``user`` that holds a+PKCS#7 signature over the root hash as it appears in the table, a string+of hexadecimal digits. The kernel verifies the signature when the table+is loaded, before the device can be used. It tries the keyrings in this+order (see :doc:`keyrings`):++#. the builtin trusted keyring, or the secondary trusted keyring, which+ includes it, when the kernel is built with+ ``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_SECONDARY_KEYRING``;+#. the platform keyring, when the kernel is built with+ ``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_PLATFORM_KEYRING``, which+ defaults to the value of the secondary option;+#. the ``.dm-verity`` keyring, once it holds a key and is restricted.++The kernel moves to the next keyring only when the previous one has no+matching key or rejects the signature. The first keyring that verifies+the signature admits the table.++A table without a signature still loads unless the kernel was booted+with ``dm_verity.require_signatures=1``. Whether a mapping was signed is+therefore a property of that mapping. dm-verity reports each device's+root hash and signature state to the LSMs through the+``bdev_setintegrity`` hook before the device goes live.++What shirudo adds+-----------------++shirudo sets up its mappings itself through the device-mapper ioctls,+without a userspace tool on the target: version 1 format, 4096-byte+data and hash blocks, SHA-256 and a salt, with the image files attached+to read-only loop devices. For a configuration image it adds+``root_hash_sig_key_desc`` and loads the image's signature into a+``user`` key in its thread keyring. It then reads back the table the+kernel holds and checks it.++Because dm-verity checks a block only when it is read, a corrupted+block would surface only when something happens to read it, possibly+halfway through applying a configuration. shirudo reads every data block+of a new runtime or configuration mapping once, with direct I/O, before+it mounts the image, parses its content or extends the configuration+PCR. A corrupted image fails before any of its content is used: a live+update is refused and the active configuration stays, and at boot init+fails.++shirudo's ``lsm.s/bdev_setintegrity`` program ties mappings to roots. A+mapping counts as the runtime only if its root hash equals the one frozen+from the bootstrap settings, and as a configuration only if its root+matches the one a task with runtime authority staged for it. A mount of+any other verity device gains neither status. ``shirudo init`` enrolls+the configuration verification certificate in ``.dm-verity`` and seals+it. See :doc:`/internals/config-images`.++Limits+------++dm-verity protects blocks on their way from the device into memory.+Pages already in memory, process memory, anonymous mappings and code+injected into a running task are outside its reach.++dm-verity does not decide which correctly signed root is current. An+older configuration image with a valid signature passes its check.+Choosing the active image is up to shirudo's configuration updates; see+:doc:`/internals/config-images`.++The kernel accepts a signature from any key in the keyrings it consults,+not only from ``.dm-verity``. On a kernel whose builtin, secondary or+platform keyring holds other keys, such as a distribution's module+signing key, those keys can sign a configuration root that the kernel+accepts. shirudo performs no signer check of its own. The threat model+lists this under threats to resolve: :doc:`/security/threat-model`.diff --git a/Documentation/concepts/background/index.rst b/Documentation/concepts/background/index.rstnew file mode 100644index 00000000..5ce4ea79--- /dev/null+++ b/Documentation/concepts/background/index.rst@@ -0,0 +1,30 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++Background+==========++The mechanisms that shirudo combines come from the kernel, the boot+chain, the TPM, cryptography, container registries and telemetry. Each+page here explains one of them for a reader who has not worked with it,+as far as shirudo depends on it. A reader who knows a mechanism can skip+its page.++.. toctree::+ :titlesonly:++ bpf+ co-re-btf+ bpf-signing+ bpf-lsm+ keyrings+ xattrs+ dm-verity+ initrd-dracut+ boot+ tpm+ pqc+ oci+ opentelemetry+ luajitdiff --git a/Documentation/concepts/background/initrd-dracut.rst b/Documentation/concepts/background/initrd-dracut.rstnew file mode 100644index 00000000..3ecc6ce5--- /dev/null+++ b/Documentation/concepts/background/initrd-dracut.rst@@ -0,0 +1,172 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++initrd, initramfs and dracut+============================++Before the kernel can mount the root file system, it may need drivers,+storage setup or decryption that live on that very file system. A small+file system in memory, the initramfs, breaks the circle. It is also the+first userspace that runs, before anything from the root file system,+which is why shirudo brings up its enforcement there. This page explains+the initramfs, systemd's role in it and how dracut builds it, then how+shirudo uses all three.++What the initramfs is+---------------------++The kernel always has a root file system of its own, rootfs, an instance+of tmpfs or ramfs. At boot it unpacks a cpio archive into it: the one+linked into the kernel image, which is usually empty, and the one the+boot loader passes in, which distributions build. Files from the passed+archive replace files of the same name from the built-in one.++If rootfs then contains ``/init``, the kernel runs it as process 1. That+program is responsible for the rest of the boot, including finding and+mounting the real root file system. Without ``/init``, the kernel tries+to mount a root partition itself.++The older initrd mechanism loaded a file system image onto a RAM block+device. Today the word initrd usually names the archive the boot loader+passes in, and tools use both words for it. This documentation says+initrd.++Switching to the real root+--------------------------++The init program in the initrd mounts the real root file system, usually+at ``/sysroot``, then switches to it. It carries the mounts of ``/dev``,+``/proc``, ``/sys`` and ``/run`` over into the new root, makes the new+root ``/``, frees the initrd's files and executes the real init.++Processes started from the initrd are not meant to survive the switch,+and systemd kills them. What has to survive lives in the kernel or below+``/run``: keyrings, loaded modules, TPM state, and BPF links held by pins+in a bpffs mounted under ``/run``.++systemd in the initrd+---------------------++An initrd can run systemd as its init, and shirudo's initrd does. The+file ``/etc/initrd-release`` tells systemd that it runs in an initrd. It+then mounts the root file system at ``/sysroot`` (``sysroot.mount``),+reaches ``initrd-root-fs.target`` and ``initrd.target``, and finally+switches root through ``initrd-switch-root.target`` and+``initrd-switch-root.service``. A unit ordered after+``initrd-root-fs.target`` and before ``initrd.target`` runs with the root+file system mounted but not yet in charge. On the switch, systemd carries+``/run``, with the mounts below it, into the new root.++On a measured boot, ``systemd-pcrphase-initrd.service`` measures the+word ``enter-initrd`` into PCR 11 when it starts and ``leave-initrd``+when it stops at the switch. PCR 11 therefore differs between the initrd+and the root file system. See :doc:`boot` and :doc:`tpm`.++dracut+------++dracut builds the initrd from the installed system. It copies binaries+with the libraries they need, kernel modules and configuration into a+staging directory, then archives and compresses it, usually to the+distribution's initrd path, such as ``/boot/initramfs-<release>.img``.+``lsinitrd`` lists what an initrd holds.++dracut is built from modules. Each module is a directory under+``/usr/lib/dracut/modules.d/``, named with a two-digit order and a name,+whose ``module-setup.sh`` defines up to four functions:++``check()``+ Decides whether the module is included: ``0`` includes it, ``1``+ leaves it out, ``255`` includes it only when another module depends+ on it or the configuration or command line asks for it.++``depends()``+ Names the modules this one needs.++``installkernel()``+ Installs kernel modules.++``install()``+ Installs everything else: binaries, files and systemd units.++The ``systemd`` module makes systemd the initrd's init. ``dracut.conf(5)``+files and dracut's command line choose the modules and set variables+that modules read.++In production, the initrd is packed together with the kernel and its+command line into a unified kernel image (UKI). Secure Boot verifies the+UKI as a whole, and the boot measures it into the TPM, so the initrd's+content is authenticated before any of it runs. See :doc:`boot`.++How shirudo uses the initrd+---------------------------++shirudo ships a dracut module, ``90shirudo``, from+``tools/gen-initrd/module-setup.sh``. Its ``check()`` looks for the+``shirudo`` binary and the primary certificate. It depends on the+``systemd`` and ``systemd-initrd`` modules, and on+``systemd-pcrextend`` (``systemd-pcrphase`` in older dracut releases)+and ``tpm2-tss`` when their checks pass. It installs the TPM drivers+(``tpm``, ``tpm_tis_core``, ``tpm_tis``, ``tpm_crb``) and the drivers for+the images (``dm_mod``, ``dm_verity``, ``loop``, ``ext4``). Its+``install()`` copies:++- the ``shirudo`` binary, at the path it has on the root file system;+- the primary certificate as ``/etc/shirudo/keys/cert.der``, and the+ further trusted certificates with their vouches under+ ``/etc/shirudo/keys/trusted/``;+- the bootstrap settings as ``/etc/shirudo/shirudo.conf``, which name the+ runtime image and its root hash;+- the ``mount`` tool, with which the unit remounts ``/sysroot``;+- ``shirudo-initrd.service``, enabled for ``initrd.target``.++``shirudo-gen-initrd`` runs dracut with this module, checks the result+with ``lsinitrd`` and prints the kernel parameters the initrd needs,+``bpf.keyring_unsealed=1 dm_verity.keyring_unsealed=1``. See+:doc:`/operate/boot-integration` for the procedure.++``shirudo-initrd.service`` runs ``shirudo init`` after+``initrd-root-fs.target`` and ``systemd-pcrphase-initrd.service``, and+before ``initrd.target`` and the switch. It remounts ``/sysroot``+read-write first. init runs here for three reasons:++- The ``.bpf`` and ``.dm-verity`` keyrings are open from boot until+ someone restricts them. Enrolling and sealing them in the initrd closes+ them before anything from the root file system runs (see+ :doc:`keyrings`).+- The measurement register can be bound only while PCR 11 still holds+ the value of the ``enter-initrd`` phase, which no later process can+ bring back (see :doc:`/concepts/measurement-register`).+- The LSM programs are attached before any service of the root file+ system starts.++init checks that ``/`` is tmpfs or ramfs and refuses otherwise. It binds+``/sysroot/var/lib/shirudo`` at ``/var/lib/shirudo``, writable, so that+the state paths are the same as on the root file system, and releases+the bind when it exits. Its mounts and pins live under ``/run/shirudo``,+which systemd carries across the switch. On the root file system,+``shirudo.service`` runs ``init`` again from the verified runtime image+and adopts what the initrd run recorded. See :doc:`/internals/boot-flow`.++Limits+------++``shirudo-initrd.service`` is wanted by ``initrd.target`` and has no+failure action. If init fails, the boot continues without enforcement,+and ``shirudo status`` and attestation are what reveal it. The unit is+also skipped when the initrd holds no certificate. The threat model lists+this under threats to resolve: :doc:`/security/threat-model`.++Everything that runs in the initrd before the unit runs as root, without+shirudo's enforcement. The initrd is trustworthy only as far as the boot+chain authenticates it, which is why production targets boot a signed+UKI.++When ``shirudo-gen-initrd`` receives any of ``--cert``,+``--trusted-dir``, ``--binary``, ``--unit`` or ``--bootstrap-conf``, it+runs dracut with a configuration of its own, and dracut then ignores the+host's ``/etc/dracut.conf`` and ``/etc/dracut.conf.d``.diff --git a/Documentation/concepts/background/keyrings.rst b/Documentation/concepts/background/keyrings.rstnew file mode 100644index 00000000..a1403c52--- /dev/null+++ b/Documentation/concepts/background/keyrings.rst@@ -0,0 +1,168 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++Kernel keyrings+===============++When the kernel verifies a signature, over a module, a BPF loader or a+dm-verity root hash, it needs a public key it trusts. The kernel keeps+such keys in keyrings. Which keyring a check consults, and who may change+that keyring, decides what the signature is worth. This page explains+keyrings in general, the ones the kernel uses for signatures, and how+shirudo sets up and protects its two.++Keys and keyrings+-----------------++A key is a kernel object with a serial number (a positive 32-bit+integer), a type, a description, a payload, an owner, a group and a+permission mask. A keyring is a key of type ``keyring`` whose payload is+a list of links to other keys, keyrings included. Keys of type+``asymmetric`` hold public keys; adding an X.509 certificate creates one+whose description the kernel derives from the certificate.++Userspace manages keys with the ``add_key(2)`` and ``keyctl(2)`` system+calls. ``/proc/keys`` lists the keys the reading task may view.++Special keyring ids+-------------------++Besides serial numbers, the system calls accept negative special ids that+name a keyring relative to the caller, such as+``KEY_SPEC_THREAD_KEYRING`` (``-1``), ``KEY_SPEC_PROCESS_KEYRING``+(``-2``) and ``KEY_SPEC_SESSION_KEYRING`` (``-3``).+``KEY_SPEC_BPF_KEYRING`` (``-9``) names the kernel's ``.bpf`` keyring+directly, so its serial does not have to be looked up first. Kernels+that provide ``KEY_SPEC_DM_VERITY_KEYRING`` (``-10``) name ``.dm-verity``+the same way; shirudo requires it (see+:doc:`/operate/system-requirements`).++Permissions and possession+--------------------------++The permission mask has six bits for each of four classes: possessor,+user (the owner), group and other. The bits are view, read, write,+search, link and set attribute. Write permission on a keyring allows+adding and removing links. Set attribute allows changing the+permissions and applying a restriction.++A task possesses a key when it can reach the key from its own thread,+process or session keyring, and the possessor bits then apply to it.+``KEY_SPEC_BPF_KEYRING`` hands out a reference that is not possessed, so+for the ``.bpf`` keyring only the user, group and other bits count. Both+``.bpf`` and ``.dm-verity`` are owned by root and grant their owner view,+read, write, search and set attribute. Any root process can therefore+add keys to them, remove keys and restrict them.++Restrictions+------------++``KEYCTL_RESTRICT_KEYRING`` attaches a restriction to a keyring. The+kernel checks the restriction for every new link: a key type and a+restriction string can, for example, admit only keys signed by a trusted+key. Without a type, the keyring rejects every new link with ``-EPERM``.++A keyring takes one restriction for its lifetime: a second attempt fails+with ``-EEXIST``, and none can be lifted. A restriction bounds what can+be added, never what can be taken away. A task with write permission can+still unlink a key from a restricted keyring, clear it or revoke it.++System keyrings+---------------++The kernel builds several keyrings at boot for its own signature checks:++``.builtin_trusted_keys``+ Certificates compiled into the kernel image, such as the module+ signing key.++``.secondary_trusted_keys``+ Links the builtin keyring and, when configured, ``.machine``. It+ accepts further keys at run time only if a key it already trusts+ vouches for them (``CONFIG_SECONDARY_TRUSTED_KEYRING``).++``.machine``+ Machine Owner Keys (MOK), when the kernel is built with+ ``CONFIG_INTEGRITY_MACHINE_KEYRING``.++``.platform``+ Keys the firmware provides, such as the UEFI signature database. The+ kernel uses them to verify kexec images and, when configured,+ dm-verity root hashes.++A key in these keyrings is trusted for everything that consults them.+That breadth is why the kernel adds keyrings scoped to one purpose.++Purpose-specific keyrings+-------------------------++The ``.bpf`` keyring holds keys for BPF program signatures (see+:doc:`bpf-signing`). The ``.dm-verity`` keyring holds keys for+dm-verity root hash signatures (see :doc:`dm-verity`). Both follow the+same rules:++- The kernel creates them at boot, sealed and empty, unless the boot+ parameter ``bpf.keyring_unsealed=1`` or ``dm_verity.keyring_unsealed=1``+ leaves the keyring open so that the initrd can provision it. Both+ parameters are read-only once the system runs.+- The kernel consults the keyring only once it is non-empty and+ restricted. An open keyring is ignored even when it holds keys.+- Provisioning ends with a restriction. Until then, anything that may+ write the keyring can add keys to it.++How shirudo enrolls and seals the keyrings+------------------------------------------++``shirudo init`` provisions both keyrings from the initrd, before the+root file system's services start (see :doc:`/internals/boot-flow`).++For ``.bpf``, init adds each certificate of the boot trust set: the+initial certificate from the runtime image and every certificate the+selected signed configuration vouches for. It then seals the keyring with+``KEYCTL_RESTRICT_KEYRING`` and no type, and checks that the keyring+holds exactly that set. Every link counts, whatever its type, because the+kernel's search also enters a nested keyring. For ``.dm-verity``, init+adds the configuration verification certificate from the runtime image,+seals the keyring and checks that it holds that certificate and nothing+else.++``shirudo init`` refuses a keyring it did not seal itself. For a+keyring sealed empty because the boot lacked the parameter, it says to+boot with the parameter. A keyring that another task restricted first,+or that holds keys beyond the set, is refused as well.++Init then records the serials of both keyrings, of the ``.dm-verity``+key and of the enrolled ``.bpf`` keys in a frozen map. Later commands+compare the ``.bpf`` serial with that record and refuse ``tampered`` on+a mismatch. shirudo's ``lsm/key_permission`` program refuses write, set+attribute and unlink on the recorded keyrings and keys to every task+without runtime authority, and refuses a search through an unpossessed+reference, which is how ``keyctl`` reaches a key by serial. The+refusals count as ``KeyringWrite``. The kernel's own signature checks+search through a possessed reference and are unaffected.++A signed configuration activated at run time can revoke an enrolled+key, which unlinks it. Nothing adds a key to either keyring until the+next boot, and key changes made locally on the target are refused. See+:doc:`/operate/keys` and :doc:`/internals/enforcement`.++Limits+------++Until init seals them, the keyrings accept a key from any root process+in the initrd. Init detects such a key by its exact-set check and+refuses, but it cannot remove it. The initrd itself has to be+authenticated, which production targets do through the boot chain.++A restriction does not stop removal. Between the seal and the attachment+of ``lsm/key_permission``, which both happen within init, a root process+could unlink a key and take signed loading out until the next boot.++For dm-verity, ``.dm-verity`` is consulted only after the builtin+keyring and, when configured, the secondary and platform keyrings. A key+there can sign a configuration root as well; see :doc:`dm-verity` and+:doc:`/security/threat-model`.diff --git a/Documentation/concepts/background/luajit.rst b/Documentation/concepts/background/luajit.rstnew file mode 100644index 00000000..c5da1db8--- /dev/null+++ b/Documentation/concepts/background/luajit.rst@@ -0,0 +1,182 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++LuaJIT and the decoder sandbox+==============================++A upatch that records observations leaves them in BPF maps as binary+records only its author knows how to read. shirudo turns those bytes into+OpenTelemetry records with a small Lua program, the decoder, that the+author ships and signs together with the BPF programs. This page explains+why decoders are Lua, what LuaJIT is, how shirudo runs a decoder and what+it restricts, and where those restrictions stop.++Why decoders exist+------------------++A serializer walks an arena structure in kernel context and writes+fixed-size records into 4096-byte pages. The pages are correct and+complete, but they are bytes: a timestamp in boot-time nanoseconds at+offset 16, a command name of up to 16 bytes at offset 96, a counter per+CPU. A collector cannot do anything with them until someone applies the+record layout.++The obvious places to put that knowledge do not work. Built into shirudo,+every new record layout would need a new shirudo release, while upatches+are written and shipped on their own schedule. Rendered generically from+BTF, a flat map of counters comes out readable, but a record in an arena+page has no BTF type the reader can find, and the meaning of its fields,+which timestamp to convert and which counters to sum, is the author's. A+native plug-in, a shared object loaded into shirudo, would be arbitrary+machine code running in a process that holds runtime authority.++What remains is a small program in a memory-safe language, written by the+upatch author, delivered inside the signed artifact and run by an+interpreter that shirudo embeds and restricts. shirudo uses Lua for it.++Lua and LuaJIT+--------------++Lua is a small scripting language designed to be embedded in a host+program. The host creates an interpreter state through a C API, decides+which libraries the state can see, loads code into it and calls functions+in it. Lua code has no access to files, processes or the network except+through library functions the host makes available.++LuaJIT is an implementation of Lua 5.1, with its C API and ABI, and a+few extensions from Lua 5.2. It pairs an interpreter written in assembler+with a trace compiler that turns frequently run code into machine code,+and adds an FFI library through which Lua code can call C functions and+touch raw memory. shirudo links LuaJIT as one of its fixed libraries and+uses only its interpreter.++Three statements in the LuaJIT documentation shape how shirudo uses it.+LuaJIT does not verify the bytecode it loads, so crafted bytecode can+crash the interpreter. Compiled traces ignore the debug hooks that an+embedder uses to interrupt running code. And the documentation+recommends sandboxing untrusted Lua code at the process level rather+than inside the interpreter.++How a decoder reaches the target+--------------------------------++The BPF source declares each decoder in ``.rodata`` with a+``struct shirudo_decoder_manifest`` from+``bpf/lib/shirudo_decoder.h``. The manifest starts with the magic+``DECD`` and names the language (``1``, Lua), the host API version, the+input format (``1``), the signal to export (``1`` for a log, ``2`` for a+metric), the upatch and map it decodes, the Lua source file relative to+the BPF source, and the entry point.++``shirudo-build`` finds the manifests when it builds the artifact, reads+each source file and embeds the sources in the ``DCDB`` section of the+loader's data before it signs. The kernel's signature check of the+loader therefore covers the decoders, and a decoder cannot be added or+changed without the signing key. The format is in+:doc:`/reference/formats/upatch-format`.++On the target, ``shirudo upatch load`` keeps the artifact it loaded as+``/var/lib/shirudo/upatches/<name>.upatch``, sealed state that only+shirudo writes. At export, shirudo opens that archived copy as sealed+state, looks for the decoder whose upatch and map names match the map+being exported and runs it. There is no decoder search path and no+directory to drop a script into.++Running a decoder+-----------------++shirudo creates a fresh interpreter state for every decoder run and+closes it afterwards, so nothing a decoder leaves behind reaches the next+run. The state allocates through a function that refuses to hold more+than 32 MiB in total. The limit covers everything the state allocates,+the input table included, and a decoder that reaches it fails with a+memory error.++The state opens the standard libraries and then removes these globals:+``io``, ``os``, ``package``, ``require``, ``debug``, ``jit``, ``ffi``,+``dofile``, ``loadfile``, ``load``, ``loadstring``, ``module`` and+``collectgarbage``. What remains is the language itself with ``string``,+``table``, ``math``, ``bit``, ``coroutine``, ``pcall`` and the other base+functions, ``print`` among them.++shirudo turns off the JIT compiler for the state, so every instruction+runs in the interpreter where the instruction hook sees it. It loads the+decoder as source text only, in mode ``"t"``, so LuaJIT refuses a+bytecode chunk.++A count hook runs every 10,000 interpreter instructions and draws from a+budget of one million instructions. The budget covers both running the+chunk at the top of the source and the call to the entry point. When the+budget is spent, the hook raises the error ``decoder instruction limit+exceeded``.++The entry point receives one table: the upatch and map names, the start+and current time as decimal nanosecond strings, the map's type and sizes,+and either its entries as hex strings or the serializer's pages. A global+table ``shirudo`` provides helpers that split pages into fixed-size+slots, read integers and strings from a slot at an offset, and do exact+64-bit arithmetic on decimal strings, since a Lua number cannot hold a+nanosecond timestamp. The accessors read only the copy of the data they+were given and return zero or an empty string for an offset out of range.++A log decoder returns a table, which becomes the body of the log record.+A metric decoder returns a list of OpenTelemetry metric objects. shirudo+serializes the result itself, refuses nesting deeper than 32 levels and+output larger than its size limits, and drops the snapshot with a+diagnostic on any error rather than export a partial record.+:doc:`/upatches/decoders` describes the input table, the helpers and the+return contract in full.++How shirudo uses it+-------------------++shirudo runs decoders in ``shirudo upatch map`` when it exports a map+over OTLP or as JSON, which is what the map export timer does with+``shirudo upatch map --all``. Reading shirudo's maps and+running a serializer require runtime authority, so the decoder runs+inside a process that holds it. ``--all`` decodes the maps one after the+other in that one process. :doc:`opentelemetry` explains what happens to+the records afterwards, and :doc:`/operate/telemetry` sets up the export.++Limits+------++- The instruction budget is a Lua error like any other. ``pcall``,+ ``xpcall`` and ``coroutine.resume`` catch it. Once the budget is spent,+ the hook raises again every 10,000 instructions, but a loop around+ ``pcall`` catches each error and runs without end.+- Time spent inside a C function, such as ``string.rep``, a pattern match+ in ``string.find`` or one of the ``shirudo`` helpers, does not count+ against the budget.+- There is no wall-clock deadline. A decoder that does not finish stalls+ every export after it in the same run, until the systemd unit's start+ timeout stops the service. A command run by hand has no such timeout.+- The global list is a denylist. Every function of the standard library+ that the list does not name stays available. ``print`` writes to the+ command's standard output, the stream that ``--json`` without a path+ also writes to.+- A decoder runs inside a process with runtime authority, not in a+ separate process. The LuaJIT interpreter is therefore part of the+ target's trusted computing base, and a flaw in it that a signed decoder+ can reach runs with shirudo's authority.+- At export, shirudo reads the decoder from the archived artifact again.+ The seal protects that file, but shirudo does not verify its signature+ a second time or compare it with the payload digest of the programs it+ loaded.++These limits bound a mistake or misbehavior in a decoder that carries a+valid signature. A decoder without one never runs. The threat model+lists the residual risks in :doc:`/security/threat-model`.++Related+-------++- :doc:`/upatches/decoders` for writing a decoder.+- :doc:`/upatches/maps-arenas-serializers` for the records a decoder+ reads.+- :doc:`opentelemetry` for the records a decoder produces.+- :doc:`/security/threat-model` for the residual risks.diff --git a/Documentation/concepts/background/oci.rst b/Documentation/concepts/background/oci.rstnew file mode 100644index 00000000..3d7d1ed8--- /dev/null+++ b/Documentation/concepts/background/oci.rst@@ -0,0 +1,243 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++OCI registries+==============++shirudo delivers packages and upatch trees through OCI registries, the+servers that also hold container images. This page explains what a+registry stores and how a client talks to it, and then which parts of+what ``shirudo bpm`` fetches are signed and which are only+content-addressed.++Why a registry+--------------++A target has to fetch signed artifacts from somewhere. A dedicated+update server would be one more service to build, authenticate and keep+available, and a plain web server has no notion of versions or of+immutable content. Most organizations already run an OCI registry, or+rent one, with access control, replication and mirrors in place.++We do not trust the registry. Whoever controls it, or the network path+to it, can change what it serves. Everything that decides what a target+loads is therefore either signed with the operator's key or named by a+digest inside something signed.++Repositories, blobs and tags+----------------------------++A registry is a server that implements the OCI Distribution+Specification. It holds repositories, each a named collection of+content such as ``team/kernel-fixes``. A repository contains blobs,+which are opaque byte strings, and manifests, JSON documents that+describe blobs.++A tag is a name of up to 128 characters, such as ``1.4.0`` or+``stable``, that points at one manifest in a repository. Tags are+mutable: anyone allowed to push to the repository can move a tag to+another manifest at any time.++Every blob and manifest is also addressed by its digest, the hash of+its exact bytes, written ``sha256:<hex>``. A client hashes what it+receives and compares.++A digest proves only that the bytes match the name. When a client+resolves a tag, the registry picks the manifest, and with it the+digests the client then checks. Content addressing protects integrity+only from the point where a digest comes from a source the client+already trusts.++Manifests, configs and layers+-----------------------------++An image manifest, media type+``application/vnd.oci.image.manifest.v1+json``, names a ``config`` blob+and a list of ``layers``. Each entry is a descriptor: a ``mediaType``+that says what the blob is, its ``digest`` and ``size``, and optional+``annotations`` such as ``org.opencontainers.image.title``. In a+container image the config holds runtime settings and the layers are+file system archives. Because the manifest names each blob by digest,+the manifest's own digest pins everything it references.++An image index, ``application/vnd.oci.image.index.v1+json``, is a+manifest of manifests, used mostly to publish one image for several+platforms under one tag. ``shirudo bpm`` reads image manifests only.++Version 1.1 of the image specification describes how to store content+other than container images. ``artifactType`` names the kind of+artifact. When there is no configuration to store, the ``config``+descriptor points at the two-byte blob ``{}`` with media type+``application/vnd.oci.empty.v1+json``, and ``artifactType`` is then+required. A manifest can also name another manifest as its+``subject``; registries list such referrers, for example a signature,+through the referrers API.++Talking to a registry+---------------------++The Distribution Specification is an HTTP API under ``/v2/``. A client+pulls a manifest with ``GET /v2/<name>/manifests/<reference>``, where+the reference is a tag or a digest. It pulls a blob with+``GET /v2/<name>/blobs/<digest>``, which registries often redirect to+object storage. To push a blob, it opens an upload with+``POST /v2/<name>/blobs/uploads/`` and sends the bytes with a ``PUT``+to the returned ``Location``, adding ``?digest=<digest>``. The registry+refuses bytes that do not match. A ``PUT`` to+``/v2/<name>/manifests/<tag>`` pushes a manifest and moves the tag.++Authentication is outside the OCI specifications. Most registries+implement the bearer token flow of the Distribution project. A request+without credentials gets ``401`` with a challenge such as+``WWW-Authenticate: Bearer realm="...",service="...",scope="..."``. The+client asks the realm for a token, presenting a user name and password+if it has them, and repeats the request with+``Authorization: Bearer <token>``. Some registries accept HTTP Basic+authentication instead. Container tools keep one base64+``user:password`` per registry host in the ``auths`` object of a+``config.json``.++How shirudo uses a registry+---------------------------++The operator publishes with ``shirudo bpm push`` and+``shirudo bpm tree append``, which run in the ``shirudo-build`` helper.+A target fetches with ``shirudo bpm repo update``, ``install``,+``upgrade``, ``pull`` and ``tree sync``. Every object is an image+manifest with shirudo's own media types:++.. list-table::+ :header-rows: 1+ :widths: 20 30 50++ * - Object+ - Location+ - Content+ * - Package+ - ``<repository>:<version>``+ - One ``application/vnd.shirudo.bpm.package.v1+gzip`` layer, the+ ``.bee`` archive, and a config of media type+ ``application/vnd.shirudo.bpm.config.v1+json``.+ * - Package certificate+ - Referrer of the package manifest+ - The signing certificate as ``application/pkix-cert``. No+ ``shirudo bpm`` command reads it.+ * - Repository index+ - ``shirudo/bpm-index:stable``, one per registry host+ - ``application/vnd.shirudo.bpm.index.v1+json`` and its detached+ CMS signature,+ ``application/vnd.shirudo.bpm.index.signature.v1``.+ * - Tree publication+ - ``<repository>:<reference>``, ``stable`` by default+ - ``application/vnd.shirudo.upatch.tree.v2+json`` and its detached+ CMS signature,+ ``application/vnd.shirudo.upatch.tree.signature.v2``.+ * - Tree artifact+ - ``<repository>:upatch-<id>-<hex>``+ - One ``application/vnd.shirudo.upatch.v1`` layer, a signed+ ``.upatch``. ``<hex>`` is the start of its payload SHA-256.++The index, the tree publication and the tree artifacts use the empty+config and set ``artifactType``.++``bpm push`` uploads the blobs, the package manifest by digest and the+certificate referrer, then, given signing material, a new signed index,+and moves the version tag last. The index lists every package version+pushed to that registry host with signing material, each with its+repository, manifest digest, package digest and size. ``bpm push``+refuses to list a version again with different digests.++On a target, the repository definitions and their certificates come+from the signed config image. ``bpm repo update`` fetches each+repository's index, checks both layers against their digests, verifies+the signature and caches the index. ``bpm install <source>/<name>``+then fetches the package manifest by the digest the index names, checks+the package layer against the index and loads the upatches inside+through the signed load path. ``bpm tree sync`` verifies the+publication and fetches each artifact by the manifest and layer digests+the publication names.++The client follows redirects for blob requests only and never sends+the ``Authorization`` header to another host. It accepts no response+larger than 256 MiB. Credentials come from ``BPM_OCI_USERNAME`` and+``BPM_OCI_PASSWORD``, or from the registry's ``auth`` entry in+``REGISTRY_AUTH_FILE``, ``$DOCKER_CONFIG/config.json`` or+``$HOME/.docker/config.json``, and ``BPM_OCI_BEARER_TOKEN`` supplies a+token directly. Credential helpers are not supported.++What is signed and what is only addressed+-----------------------------------------++Three kinds of objects carry a signature a target checks:++- The ``.upatch`` files inside packages and tree artifacts are signed+ loaders and unload directives. The kernel verifies their ML-DSA-87+ signature at ``BPF_PROG_LOAD`` against the ``.bpf`` keyring.+- A repository index is verified against the certificate its+ repository definition names in the signed config.+- A tree publication is verified against the runtime image's primary+ certificate, ``keys/cert.der``, and no other. Revoking that key in the+ config does not change this.++Everything else is content-addressed only: manifests, configs, package+archives and artifact blobs. They are trusted because a signed document+names their digests. The index names each package's manifest and layer,+and the publication names each artifact's manifest, layer and payload+digest. A package installed from the index is therefore the one the+operator pushed, but the registry decides whether to serve it at all.++Limits+------++A signature shows who wrote a document, not that it is current. A+validly signed older index replaces the cached one: ``repo update``+does not read the signed ``generated_at``. A registry can serve an old+index, or none, and hide newer versions. A target refuses a changed+tree publication whose generation is not higher than the one it applied+last, but the registry can keep serving an unchanged publication, and+the first sync accepts any generation.++An index names repositories, not the registry. An index signed for one+registry verifies on any other whose repository definition names the+same certificate.++``repo update`` is not measured. The register records upatch loads,+unloads and tree operations, not which index or package version a+target saw, and ``bpm list`` reports the target's own state.++``bpm install`` and ``bpm pull`` also take a direct+``oci://<registry>/<repository>:<tag>``. That path has no index: the+registry resolves the tag, and only the layer digest from that manifest+is checked. The kernel's signature check still applies to each upatch,+so the registry can choose only among artifacts a trusted key once+signed, old ones included.++Environment variables select the transport, and processes with runtime+authority honor them: ``BPM_OCI_SCHEME=http`` turns TLS off,+``BPM_OCI_CA_FILE`` adds a trust anchor, and libcurl's proxy variables+redirect traffic. The repository update and tree sync units read+``/etc/shirudo/bpm/environment``, which root can write. Signatures+still bind what a target loads, so this gives root the position of a+hostile registry.++On the operator host, ``shirudo bpm config update --base-package+oci://...`` without ``-f`` downloads the base package by tag, checks it+only against its manifest's layer digest, and runs the updater+commands of the Beefile inside it. Whoever can move that tag can run+commands on the operator host. Pass ``-f`` with a Beefile you control,+or a package file you built.++Related+-------++- :doc:`/operate/deliver-packages`+- :doc:`/upatches/publishing`+- :doc:`/reference/formats/bpm-formats`+- :doc:`/reference/cli/bpm`+- :doc:`/reference/environment`+- :doc:`pqc` for the TLS policy+- :doc:`/security/threat-model` for the residual risks of deliverydiff --git a/Documentation/concepts/background/opentelemetry.rst b/Documentation/concepts/background/opentelemetry.rstnew file mode 100644index 00000000..f316697e--- /dev/null+++ b/Documentation/concepts/background/opentelemetry.rst@@ -0,0 +1,206 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++OpenTelemetry and OTLP+======================++shirudo reports the state of a target and the observations of its+upatches to the monitoring an operator already runs. It does so in+OpenTelemetry's data model, over OpenTelemetry's wire protocol, OTLP.+This page explains the parts of OpenTelemetry that shirudo uses, how a+target exports, and what exported telemetry can and cannot tell you.++Why a standard format+---------------------++A fleet's telemetry has to land in whatever the operator uses: a log+store, a time-series database, a SIEM. A format of shirudo's own would+need a receiver written for each of them. A target that served its data+on request would need a listening socket and a process that stays+running, both of which the agentless target avoids.++OpenTelemetry is a vendor-neutral specification for telemetry data and+for the protocol that carries it. Collectors and many backends accept+OTLP directly, so a target that pushes OTLP needs nothing specific to the+backend on the other end.++Signals+-------++OpenTelemetry calls each kind of telemetry a signal. It supports traces,+metrics and logs, and baggage, which carries context between services.++A log record is one event. It carries a timestamp, the time it was+observed, a severity as a number and a text (``9`` is ``INFO``, ``13`` is+``WARN``, ``17`` is ``ERROR``), an optional event name, a body and a set+of attributes. The body is an ``AnyValue``: a string, a number, a+boolean, or arrays and key-value lists of those, so a log record can+carry a structured document.++A metric is a named series of data points with a unit and a description.+A sum adds up values, monotonic or not, and states whether each point+covers the time since the start or since the previous point. A gauge+reports a current value. Each data point has its own timestamps and+attributes.++shirudo emits logs and metrics. It emits no traces.++Resources, scopes and attributes+--------------------------------++Every record belongs to a resource, the entity that produced it,+described by resource attributes such as ``service.name`` and+``host.name``. Within a resource, records are grouped by instrumentation+scope, the name and version of the code that produced them. Each record+then has attributes of its own.++The structure of a request follows that grouping. A logs request holds+``resourceLogs``, each with a ``resource`` and its ``scopeLogs``, each+with a ``scope`` and its ``logRecords``. A metrics request has the same+shape with ``resourceMetrics``, ``scopeMetrics`` and ``metrics``.++OTLP over HTTP+--------------++OTLP sends a request per batch of records: an+``ExportLogsServiceRequest`` or ``ExportMetricsServiceRequest``. Over+HTTP, the client POSTs logs to the path ``/v1/logs`` and metrics to+``/v1/metrics``, by default on port 4318. The body is either binary+protobuf (``application/x-protobuf``) or the protobuf JSON mapping+(``application/json``). In the JSON form, 64-bit integers are decimal+strings and enumerations are integers. The client may compress the body+with gzip and say so in ``Content-Encoding``. OTLP also runs over gRPC.++The server answers ``200`` when it accepted the request. A+``partialSuccess`` object in that answer reports how many log records or+data points it rejected and why. The specification makes ``429``,+``502``, ``503`` and ``504`` retryable and lets the server ask for a delay+with ``Retry-After``.++Exporters are configured through standard environment variables.+``OTEL_EXPORTER_OTLP_ENDPOINT`` is a base URL to which the signal path is+appended, while ``OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`` and+``OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`` are used as they are. Further+variables set headers, a CA certificate, a client certificate and key,+compression, a timeout and the protocol.++Collector+---------++The OpenTelemetry Collector receives, processes and exports telemetry,+independent of any vendor. Receivers accept data, for example OTLP on+port 4318. Processors batch, filter or enrich it. Exporters send it on to+backends. A pipeline connects them for one signal. A target that sends+to a collector leaves the choice of backend, retention and routing to+the collector's configuration.++How shirudo exports+-------------------++Figure 1 shows the two paths from a target to a collector.++.. figure:: /images/background-telemetry-export.svg+ :alt: Map snapshots pass from a BPF map through a serializer or direct+ read and a signed decoder into OTLP JSON; the status report+ becomes a keepalive log; both are posted to a collector.++ Figure 1. Telemetry export. Two one-shot commands, each started by a+ systemd timer, build OTLP JSON documents and post them to the+ collector. Nothing on the target listens for connections.++``shirudo-keepalive.timer`` runs ``shirudo status --otel+--include-system``, and ``shirudo-map-export.timer`` runs ``shirudo+upatch map --all``. Each timer starts its service five seconds after boot+and again five seconds after the previous run finished.++shirudo speaks OTLP over HTTP with the JSON encoding only and refuses an+``OTEL_EXPORTER_OTLP_PROTOCOL`` other than ``http/json``. Every request+carries the resource attributes ``service.name`` (``shirudo``),+``service.version`` and ``host.name``, which is the host name+``gethostname()`` returns.++The keepalive is one log record with the event name+``shirudo.keepalive``. Its body is the ``shirudo status --json``+document. Its attributes are ``shirudo.status``, ``shirudo.version_id``+and ``shirudo.tamper_attempts``, the number of refusals the guards counted+this boot. The severity follows the status: ``INFO`` for ``ok``,+``WARN`` for ``degraded``, ``init-pending`` and ``reboot-pending``, and+``ERROR`` for every other status. ``shirudo status --otel`` sends the+keepalive only when the signed config or the environment names an+endpoint, and never falls back to the default ``localhost`` endpoint.++A map snapshot goes through the decoder the upatch signed for that map,+which declares whether the map becomes a log record or metrics. A log+record has the event name ``shirudo.bpf.map.snapshot``, the decoder's+table as its body and attributes that name the upatch and the map. A+metric decoder returns the metric objects themselves. A map without a+decoder goes through a classifier. If the classifier picks a log, the+body carries the map's entries as shirudo renders them from BTF, or the+serializer's pages in hex. If it+picks a metric, which it does for an unsigned per-CPU integer, the export+of that map fails, because only a decoder builds metrics.+:doc:`luajit` explains how decoders run.++A decoded snapshot too large for the configured record or request size+can go to S3 storage instead, when ``map_export.s3_uri`` is set. shirudo+uploads the snapshot and sends a log record with the event name+``shirudo.bpf.map.snapshot.reference`` that points to it.++The destination, tenant, retries and size limits are ``map_export.*``+settings in ``etc/shirudo/shirudo.conf`` of the signed config image. Both+units also read ``/etc/shirudo/map-export.env``, which carries the+``OTEL_EXPORTER_OTLP_*`` headers, CA certificate, client certificate and+key, compression and timeout, and the ``AWS_*`` credentials for S3.+:doc:`/reference/formats/configuration` lists the settings, and+:doc:`/reference/formats/otlp` the documents on the wire.++The connection uses TLS 1.3 with a hybrid ML-KEM key exchange, the same+policy as shirudo's other HTTPS connections. A collector that offers only+classical key exchange is refused unless its host name is listed in+``tls.classical_hosts``. Plain ``http://`` is allowed only to a loopback+address, unless ``map_export.otel_insecure`` is set, which also turns off+certificate verification for ``https://``. shirudo retries the retryable+answers and transport errors with backoff, and counts a+``partialSuccess`` that rejected records as a failure.++A serializer-backed map hands over what it collected since the previous+read and, in the double-buffered tables of the shipped ``kernel-obs``+upatch, clears it. ``shirudo upatch map`` reads the map before it sends,+so a failed export loses that interval. There is no spool on the+target.++Limits+------++Telemetry carries no proof of origin. The documents are not signed and+not bound to the TPM. The host name in them is whatever the host+reports. The credentials and the CA certificate for the collector come+from ``/etc/shirudo/map-export.env``, a file root on the target can+change, and ``map_export.otel_insecure`` turns off certificate+verification.++Root on the target can therefore stop the timers, drain a map by running+``shirudo upatch map`` itself, point the keepalive at another collector+when the signed config names none, or post a keepalive of its own that+reports ``ok`` with no refusals. A missing keepalive, or one at+``ERROR``, is worth acting on. A keepalive that reports ``ok`` proves+nothing.++Telemetry is the target's own account of itself. The evidence of what a+target runs is the TPM-signed record that ``shirudo attest`` produces and+``shirudo attest verify`` checks on the operator host, described in+:doc:`/operate/attest`. The threat model covers exported telemetry in+:doc:`/security/threat-model`.++Related+-------++- :doc:`/operate/telemetry` to set up export on a target.+- :doc:`/reference/formats/otlp` for the exported documents.+- :doc:`/reference/systemd-units` for the timers and services.+- :doc:`luajit` for the decoder sandbox.+- :doc:`/upatches/decoders` for writing a decoder.diff --git a/Documentation/concepts/background/pqc.rst b/Documentation/concepts/background/pqc.rstnew file mode 100644index 00000000..08ea3071--- /dev/null+++ b/Documentation/concepts/background/pqc.rst@@ -0,0 +1,236 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++Post-quantum cryptography+=========================++shirudo signs everything it ships with ML-DSA-87 and negotiates TLS+with a hybrid post-quantum key exchange. This page explains why a+fleet that exists today has to care about quantum computers, what the+new algorithms are, where the industry stands, and exactly which parts+of shirudo use post-quantum and which remain classical.++Problem+-------++RSA, Diffie-Hellman and elliptic-curve cryptography rest on factoring+and discrete logarithms. Shor's algorithm solves both efficiently on a+large enough quantum computer, so such a machine would recover private+keys from public ones. Hash functions and symmetric ciphers fare far+better: the best known quantum attack on them, Grover's search, at most+halves their bit strength, which SHA-256 and AES-256 absorb.++No such computer exists today, and nobody knows when one will. Two+properties of a fleet make that uncertainty a present problem.++Recorded traffic can be decrypted later. An adversary who stores a+TLS session today can recover its keys once a quantum computer exists,+if the key exchange was classical. NIST calls this "harvest now,+decrypt later". Registry passwords and the kernel activity a target+exports can stay sensitive for years.++Trust anchors outlive their algorithms. A target verifies every upatch+against keys enrolled at provisioning, and a device in the field may+run for a decade. If those keys are classical, a future adversary who+can derive the private key from the certificate can sign loaders every+such target accepts. NIST's transition report makes the same point for+code signing on devices whose verification code cannot be updated+after manufacture [#ir8547]_. Swapping the algorithm later means+re-provisioning every target, and NIST estimates that a cryptographic+transition takes 10 to 20 years.++NIST standards+--------------++NIST published three post-quantum standards on August 13, 2024:++ML-KEM (FIPS 203)+ A key-encapsulation mechanism built on module lattices. One side+ publishes an encapsulation key, the other returns a ciphertext, and+ both derive the same shared secret. Parameter sets ML-KEM-512, -768+ and -1024 target NIST security categories 1, 3 and 5.++ML-DSA (FIPS 204)+ A lattice-based signature scheme. ML-DSA-44, -65 and -87 target+ categories 2, 3 and 5. ML-DSA-87 has a 2592-byte public key and a+ 4627-byte signature, against 64 bytes for an ECDSA P-256 signature.++SLH-DSA (FIPS 205)+ A stateless hash-based signature scheme whose security rests only+ on its hash function. Its signatures take 7856 to 49856 bytes, and+ signing is slower. shirudo does not use it.++Hybrid key exchange+-------------------++A new algorithm has had less scrutiny than X25519. TLS 1.3 therefore+deploys ML-KEM in hybrid groups. In ``X25519MLKEM768`` the client sends+an ML-KEM-768 encapsulation key together with an X25519 share, and the+server answers with a ciphertext and its own share. Both shared secrets,+concatenated, feed the TLS key schedule, so an attacker has to break+both to recover the session keys. RFC 10024 defines this group+(code point ``0x11EC``) and ``SecP256r1MLKEM768`` and+``SecP384r1MLKEM1024`` [#rfc10024]_.++Hybrid key exchange protects confidentiality. The server still proves+its identity with a classical certificate signature, which an attacker+would have to forge during the handshake, so that part can move later.++Where the industry is+---------------------++- NIST will deprecate quantum-vulnerable public-key algorithms after+ 2030 and disallow them under its standards after 2035, and requires+ the most sensitive federal systems to adopt post-quantum key+ establishment by the end of 2030 and signatures by the end of 2031+ [#ir8547]_.+- The NSA's CNSA 2.0 suite for national security systems selects+ ML-KEM-1024 and ML-DSA-87, with LMS and XMSS for firmware signing,+ and schedules software and firmware signing to use only CNSA 2.0+ algorithms by 2030 [#cnsa]_.+- OpenSSL 3.5, released on April 8, 2025 and supported until April+ 2030, implements ML-KEM, ML-DSA and SLH-DSA, prefers hybrid groups,+ and sends ``X25519MLKEM768`` and ``X25519`` key shares by default+ [#openssl]_.+- Chrome, Firefox on the desktop, and Apple's iOS, iPadOS and macOS 26+ enable hybrid key exchange by default. Cloudflare reported in October+ 2025 that most human-initiated traffic to its network used it+ [#cloudflare]_.+- Linux 7.0 added ML-DSA verification to the kernel's crypto library and+ ML-DSA-44, -65 and -87 keys for module signing+ (``CONFIG_MODULE_SIG_KEY_TYPE_MLDSA_87`` and its siblings). For+ ML-DSA in PKCS#7 with signed attributes, the kernel accepts only a+ SHA-512 message digest (``crypto/asymmetric_keys/public_key.c``).+- Google announced in March 2026 that Android 17 brings ML-DSA to+ Android Verified Boot, the Keystore (ML-DSA-65 and ML-DSA-87) and APK+ signing, and starts moving remote attestation to post-quantum+ certificate chains [#android]_.++What shirudo signs+------------------++``shirudo genkey`` creates only ML-DSA-87 keys, and the signer in+``shirudo-build`` refuses any other key. We chose the largest parameter+set because the key is a trust anchor that has to outlive several+hardware generations. Every signature is a detached CMS (PKCS#7)+signature. OpenSSL 3.x cannot sign ML-DSA in CMS without signed+attributes, so with it the CMS carries them over a SHA-512 digest, the+only digest the kernel accepts for ML-DSA in that form. OpenSSL 4 signs+the content directly. The kernel needs ``CONFIG_CRYPTO_MLDSA`` to+verify either form.++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Object+ - Verified by+ * - Signed loaders and unload directives+ - The kernel at ``BPF_PROG_LOAD``, against the ``.bpf`` keyring+ * - Config image roots, the 64 hex characters of the root hash+ - The kernel's dm-verity signature check, against the+ ``.dm-verity`` keyring and the kernel's own trusted keys+ * - Vouches for additional signing certificates+ - shirudo, against the enrolled trust set+ * - Repository indexes+ - shirudo, against the repository certificate in the signed config+ * - upatch tree publications+ - shirudo, against the runtime image's ``keys/cert.der``++``init``'s pre-flight check refuses a certificate in the trust set it+reads whose key is not ML-DSA-87, and ``shirudo keys vouch`` refuses to+vouch for or with any other key. shirudo identifies certificates by the+SHA-256 of their public key. Payload digests, OCI digests, the+measurement register, the TPM PCR bank and the dm-verity hash trees use+SHA-256.++Transport+---------++Every HTTPS client in shirudo, for registries, config image downloads+and OTLP export, requires TLS 1.3 and offers only ``X25519MLKEM768``+and ``SecP256r1MLKEM768``. A server that supports neither fails the+handshake.++``tls.classical_hosts`` lists exact DNS names for which shirudo also+offers ``X25519`` and ``secp256r1``, for servers that do not support+hybrid groups yet. Wildcards and IP addresses are refused, a redirect+must reach a listed host itself, and shirudo logs a warning when such a+connection negotiates a classical group. On a target the list comes+from the runtime image's ``etc/shirudo/shirudo.conf``, on the operator+host from ``/etc/shirudo/shirudo.conf``.++What stays classical+--------------------++- The TPM keys. The attestation key is ECDSA P-256 with SHA-256, the+ endorsement key shirudo accepts is RSA-2048 or ECC P-256, credential+ activation uses RSA-OAEP or ECDH P-256 with AES-128-CFB and+ HMAC-SHA256, and the NV writer key, created at each boot, is+ RSA-3072. TPM evidence and the register's write authorization rest on+ classical assumptions.+- TLS server authentication. Registries and collectors present WebPKI+ certificates, usually RSA or ECDSA.+- Kernel keys outside shirudo's keyrings. The dm-verity check also+ accepts config signatures from the kernel's built-in trusted keys and,+ depending on the kernel configuration, its secondary and platform+ keyrings. Distribution keys there are usually RSA or ECDSA.++Limits+------++shirudo requires ML-DSA-87 when it creates a key, when it signs, when+it vouches and in ``init``'s pre-flight check, but not everywhere it+verifies a signature.+Index and tree signatures are verified with whatever key the configured+certificate holds, and no step refuses a classical repository+certificate.++Certificate validity periods are not enforced. shirudo's own checks+skip them, and its signatures carry no signing time for the kernel to+compare. A key stops being trusted when a signed config revokes it, not+when its certificate expires.++``BPM_OCI_SCHEME=http`` turns TLS off for registry access, and+``map_export.otel_insecure`` turns off certificate verification for the+OTLP collector. See :doc:`oci` and the :doc:`/security/threat-model`.++References+----------++.. [#ir8547] NIST IR 8547, `Transition to Post-Quantum Cryptography+ Standards <https://csrc.nist.gov/pubs/ir/8547/final>`__, October 2026.+.. [#rfc10024] `RFC 10024 <https://www.rfc-editor.org/info/rfc10024>`__,+ Post-Quantum Traditional (PQ/T) Hybrid Key Agreement Mechanisms for+ TLS 1.3.+.. [#cnsa] NSA, `Commercial National Security Algorithm Suite 2.0+ <https://media.defense.gov/2025/May/30/2003728741/-1/-1/0/CSA_CNSA_2.0_ALGORITHMS.PDF>`__+ and the `CNSA 2.0 FAQ+ <https://media.defense.gov/2022/Sep/07/2003071836/-1/-1/1/CSI_CNSA_2.0_FAQ_.PDF>`__.+.. [#openssl] OpenSSL, `3.5 release notes+ <https://openssl-library.org/news/openssl-3.5-notes/>`__ and+ `release table <https://openssl-library.org/source/>`__.+.. [#cloudflare] Cloudflare, `State of the post-quantum Internet in 2025+ <https://blog.cloudflare.com/pq-2025/>`__.+.. [#android] Google, `Security for the Quantum Era: Implementing+ Post-Quantum Cryptography in Android+ <https://blog.google/security/security-for-the-quantum-era-implementing-post-quantum-cryptography-in-android/>`__.++The standards are `FIPS 203 <https://csrc.nist.gov/pubs/fips/203/final>`__,+`FIPS 204 <https://csrc.nist.gov/pubs/fips/204/final>`__ and+`FIPS 205 <https://csrc.nist.gov/pubs/fips/205/final>`__.++Related+-------++- :doc:`/security/cryptography`+- :doc:`bpf-signing`+- :doc:`dm-verity`+- :doc:`tpm`+- :doc:`oci`+- :doc:`/operate/keys`+- :doc:`/reference/formats/configuration`diff --git a/Documentation/concepts/background/tpm.rst b/Documentation/concepts/background/tpm.rstnew file mode 100644index 00000000..c11219d8--- /dev/null+++ b/Documentation/concepts/background/tpm.rst@@ -0,0 +1,522 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++TPM 2.0 and how shirudo uses it+===============================++A target's TPM 2.0 does two jobs for shirudo. It holds a per-boot+measurement register that records every change to the target's BPF+state, and it signs evidence about that register and the boot PCRs, so+that an operator can check a target without taking its word for+anything. This page explains the parts of TPM 2.0 those jobs rely on+and, for each, what shirudo does with it. The event formats and the+eventlog are in :doc:`/internals/measurement-register`, the+verification procedure in :doc:`/operate/attest`.++Every target needs a TPM 2.0 with an active SHA-256 PCR bank. There is+no unmeasured mode. The operator host never talks to a TPM: it+computes and checks everything in software. Table 1 lists the TPM+objects shirudo uses.++.. list-table:: Table 1. TPM objects shirudo uses+ :header-rows: 1+ :widths: 22 30 48++ * - Object+ - Kind+ - Purpose+ * - Measurement register+ - NV extend index ``0x01818E00``, owner hierarchy+ - Records ``init``, upatch loads and unloads, tree operations and+ key revocations. Clears at every TPM reset and TPM restart.+ * - NV writer key+ - RSA-3072 primary key, owner hierarchy+ - Authorizes each extension of the register. A new key every+ host boot.+ * - Attestation key+ - ECC NIST P-256 primary key, endorsement hierarchy+ - Signs quotes and NV certifications. The same key for the life+ of the TPM's endorsement seed.+ * - Endorsement key+ - RSA 2048 or ECC NIST P-256 primary key, endorsement hierarchy+ - Ties the attestation key to a certified TPM through credential+ activation.+ * - PCR 9+ - SHA-256 bank+ - Carries the register's anchor.+ * - Config PCR+ - SHA-256 bank, chosen by ``config.pcr``+ - Records config image activations, see+ :doc:`/internals/config-images`.++Roots of trust+--------------++A TPM is a small security processor separate from the main CPU: a+discrete chip, a firmware TPM in the processor's secure environment,+or a virtual TPM that a hypervisor or ``swtpm`` provides to a virtual+machine. It keeps keys and registers in shielded memory that only its+own commands can reach, and it never releases a private key it+generated.++The TCG specification names three roots of trust that a trusted+platform needs. The root of trust for measurement is the first code+that runs after reset; it measures the next stage and starts the chain+that :doc:`boot` describes. The TPM is the root of trust for storage,+because it keeps measurements and keys out of reach of software, and+the root of trust for reporting, because it signs statements about+what it holds. shirudo trusts the TPM in both roles. The software path+between shirudo and the TPM is a different matter, which the limits at+the end of this page cover.++Hierarchies and seeds+---------------------++TPM 2.0 groups its keys into hierarchies. Each hierarchy has a secret+seed that never leaves the TPM and its own authorization:++- The platform hierarchy belongs to the firmware. Its seed is the+ platform primary seed, and its authorization is not available to the+ operating system.+- The storage, or owner, hierarchy belongs to the machine's owner. Its+ seed is the storage primary seed, its authorization the owner+ authorization. ``TPM2_Clear`` replaces the seed, which invalidates+ every key derived from it.+- The endorsement hierarchy carries the TPM's identity. Its seed, the+ endorsement primary seed, is created at manufacturing and changes+ only through ``TPM2_ChangeEPS`` under platform authorization. Its own+ authorization is the endorsement authorization.+- The null hierarchy has a seed that the TPM replaces at every reset.+ Its keys last until the next reset.++shirudo uses the owner hierarchy for the measurement register and the+NV writer key, and the endorsement hierarchy for the attestation key+and the endorsement key. It never uses the platform or null+hierarchies. When the TPM has an owner authorization, shirudo takes it+from ``tpm.owner_auth`` in its authenticated configuration. The+endorsement authorization must be empty: shirudo has no setting for+it.++Primary keys from templates+---------------------------++A TPM can hold only a few keys at a time, so TPM 2.0 lets software+derive keys again instead of storing them. ``TPM2_CreatePrimary``+takes a hierarchy and a template, the public area of the key: its+algorithm and size, attributes, policy, and a ``unique`` field the+caller may fill with any bytes. The TPM derives the key from the+hierarchy's seed and the template. The same seed and the same template+give the same key every time, so the key needs no persistent slot.+Software creates it when it needs it and flushes it afterwards.++A key's Name is its name algorithm followed by the hash of its public+area. The Name commits to the public key and to every attribute, so+two parties that agree on a Name agree on the key and on what the TPM+allows it to do.++shirudo keeps no persistent objects in the TPM. Each command creates+the keys it needs and flushes them before it exits. The attestation+key's template is fixed, so its Name stays the same as long as the+endorsement seed does, and an operator can pin it once at enrollment.+The NV writer key's ``unique`` field is 32 random bytes that ``init``+draws at every host boot, so every boot has its own writer key.+``init`` freezes those bytes and the resulting public modulus in+shirudo's identity map, a BPF map nothing can change for the rest of+the boot. Every later command creates the key again from the frozen+bytes and refuses one whose modulus differs. A ``TPM2_Clear`` replaces+the owner seed, so the key no longer matches and extensions fail+closed.++Endorsement key and certificate+-------------------------------++The endorsement key (EK) is the TPM's identity. It is a primary key in+the endorsement hierarchy created from a template that the TCG+defines, so anyone who knows the template knows which key a given TPM+derives. The manufacturer creates the key at production, signs a+certificate for it and stores the certificate in the TPM's NV memory:+the RSA 2048 certificate at NV index ``0x01C00002``, the ECC NIST+P-256 one at ``0x01C0000A``. A verifier that trusts the manufacturer's+certificate authority can tell that an EK belongs to a genuine TPM.++The EK is a restricted decryption key, and its policy,+``TPM2_PolicySecret`` on the endorsement hierarchy, requires the+endorsement authorization to use it. It cannot sign. It decrypts+secrets that were encrypted to it, which is how credential activation,+described below, proves where another key lives.++``shirudo attest`` reads the EK certificate, the ECC one first, and+creates the EK of the certificate's type from the TCG default+template, or the ECC EK when the TPM holds no certificate. The evidence+carries the EK's public area and the certificate. ``shirudo attest+challenge`` checks that the public area is the TCG default template+under the endorsement policy and that the certificate describes that+key. With ``--ek-ca`` it also checks that the certificate chains to+the issuers given. Otherwise the operator pins the EK with+``--ek-name``, or accepts it unvouched with ``--trust-presented-ek``.++Attestation keys+----------------++A key that signs whatever a caller asks would make a quote worthless,+because software could have it sign a quote it made up. A restricted+signing key avoids this. The TPM signs with it only structures the TPM+built itself, such as quotes and certifications, which start with the+value ``TPM_GENERATED_VALUE`` (``0xFF544347``), and it refuses to sign+outside data that could pass for one. A structure that starts with+that value and carries a valid signature by a restricted key came from+the TPM that holds the key.++shirudo's attestation key (AK) is an ECC NIST P-256 primary key in the+endorsement hierarchy that signs with ECDSA and SHA-256. Its attributes+are ``fixedTPM``, ``fixedParent``, ``sensitiveDataOrigin``,+``userWithAuth``, ``restricted`` and ``sign``, and it has no+authorization value and no policy. ``init`` records its Name in the+identity map. Before each write to the register, shirudo creates the+AK again and compares its Name with the recorded one, which detects a+different TPM behind the device path. ``attest verify`` checks that+the AK's public area has these attributes, that the Name matches the+public area and, with ``--ak-name``, that it is the key pinned at+enrollment.++PCRs, banks and extension+-------------------------++A PCR holds a digest that software can only extend: the TPM replaces+the value with the hash of the old value and the new digest. A TPM+keeps one bank of PCRs per hash algorithm, typically SHA-1 and+SHA-256, and an extension names a digest for each bank it changes. A+PC Client TPM has 24 PCRs per bank. A TPM reset, or a TPM restart+after hibernation, returns them to their initial values. Apart from a+few PCRs that are resettable on purpose, such as PCR 23 for+applications, nothing else does. Any process that can send commands+to the TPM can read the PCRs and extend the ones the operating system+uses. :doc:`boot` lists who extends which PCR during a boot.++shirudo works in the SHA-256 bank only, and ``init`` refuses a TPM+whose SHA-256 bank lacks PCR 9 or PCR 11. ``init`` reads PCRs 9 and 11+when it binds the register and extends PCR 9 with the register's+anchor. Config image activation extends the config PCR.+``shirudo attest`` quotes PCRs 0 to 7, 9 and 11 to 15 by default, and+the config PCR as well when a config image is active.++NV indices and the extend type+------------------------------++Besides PCRs, a TPM has NV indices: storage locations that an owner+defines with ``TPM2_NV_DefineSpace``. Each has a handle, a size,+attributes, an authorization value and a policy. Their types include+ordinary data, counters, bit fields and extend indices. An extend+index behaves like a PCR: ``TPM2_NV_Extend`` sets it to the hash of+the old value and the new data. The first extension after the index+is defined starts from a zero digest and sets the attribute+``TPMA_NV_WRITTEN``.++The attributes decide who may read and write an index and when it+clears. With ``TPMA_NV_ORDERLY`` the TPM keeps the value in RAM and+saves it only at an orderly shutdown. Together with+``TPMA_NV_CLEAR_STCLEAR`` the index loses its value and+``TPMA_NV_WRITTEN`` at every TPM reset and TPM restart, so it starts+over with each boot, like a PCR.++An index's Name is the hash of its public area: handle, name+algorithm, attributes, policy and size. ``TPMA_NV_WRITTEN`` is one of+the attributes, so the Name changes at the first write. Unlike a PCR,+an index can be deleted with ``TPM2_NV_UndefineSpace`` and defined+again by anyone who satisfies the owner authorization. A recreated+index starts empty. This is why systemd and shirudo record an+index's Name in a PCR, which cannot be deleted.++shirudo's register is the index ``0x01818E00``, which a build can+change with ``SHIRUDO_NV_INDEX``. It holds one SHA-256 digest and has+the attributes ``0x0E060048``: ``TPM2_NT_EXTEND``,+``TPMA_NV_POLICYWRITE``, ``TPMA_NV_OWNERREAD``, ``TPMA_NV_AUTHREAD``,+``TPMA_NV_NO_DA``, ``TPMA_NV_ORDERLY`` and ``TPMA_NV_CLEAR_STCLEAR``.+Its authorization value is empty, so anyone can read it, and only a+policy session can write it. It is an NV index rather than a PCR+because a typical Linux system has no PCR left over, and PCR 23 can be+reset by any application.++Authorization and sessions+--------------------------++Every command that uses a protected entity carries an authorization,+in one of three forms.++A password authorization carries the entity's authorization value in+the command, in plaintext. Anything that sees the command sees the+password.++An HMAC session proves knowledge of the authorization value without+sending it: the caller computes an HMAC over the command and over+nonces from both sides, and the TPM answers with an HMAC over its+response. A session is salted when the caller encrypts a random salt to+a TPM key it trusts. Only that TPM can recover the salt, so only it can+compute the session key and the HMACs on its responses. A session is+bound when it mixes in the authorization value of a chosen entity. A+session that is neither has no session key. Sessions can also encrypt+the first parameter of commands and responses.++A policy session authorizes by conditions instead of a secret. The+caller runs policy assertions on the session, and each one that holds+extends the session's policy digest. The TPM allows the command only+when the final digest equals the entity's policy. The assertions+shirudo uses are:++- ``TPM2_PolicyPCR``: the selected PCRs hold the values whose hash the+ policy contains.+- ``TPM2_PolicyNvWritten``: the index has, or has not, been written.+- ``TPM2_PolicyOR``: the digest so far equals one of the listed branch+ digests.+- ``TPM2_PolicySigned``: a key with a given Name signed the hash of+ the session's TPM nonce, an expiration, a command parameter hash+ (cpHash) and a policy reference. The nonce ties the signature to this+ session, and the cpHash restricts it to one command with exactly+ these parameters.+- ``TPM2_PolicyCommandCode``: the session may authorize only this+ command.+- ``TPM2_PolicySecret``: the caller satisfies another entity's+ authorization. The EK's policy uses it.++``TPM2_PolicyGetDigest`` returns the session's digest so far, which+lets a caller compare it with the digest it computed.++shirudo uses password authorizations and policy sessions, and no HMAC+sessions. Its policy sessions are unsalted and unbound and encrypt no+parameters. The owner authorization, when set, travels as a password.++Register binding+----------------++The register has to record what shirudo did and nothing else. Root on+the target must not be able to add events of its own, delete the+register and start a fresh history, or bind the register later from a+state it chose. An NV index alone stops none of this: root can define+an index, write it and delete it. We combine the policy assertions+above, the boot phases that :doc:`boot` describes and an LSM hook.++Figure 1 shows how ``init`` binds the register from the initrd.++.. figure:: /images/background-tpm-register.svg+ :alt: PCR 9 and PCR 11 values enter the write policy, the policy+ defines the NV index, and the index's written Name is+ extended into PCR 9 as the anchor.++ Figure 1. Binding the register: (1) read PCRs 9 and 11, (2) define+ the index with the write policy, (3) write the first event through+ the init branch, (4) extend PCR 9 with the anchor.++1. ``init`` reads PCRs 9 and 11. It computes the write policy:+ ``TPM2_PolicyOR`` of a written branch, ``TPM2_PolicyNvWritten(YES)``,+ and an init branch, ``TPM2_PolicyNvWritten(NO)`` followed by+ ``TPM2_PolicyPCR`` over PCRs 9 and 11 at the values it read; then+ ``TPM2_PolicySigned`` by the NV writer key with the policy+ reference ``shirudo-nv-writer-v1``; then+ ``TPM2_PolicyCommandCode`` for ``TPM2_NV_Extend``. It also computes+ the index's Names before and after the first write.+2. It defines the index with that policy, replacing any index at the+ handle that is written or has another Name, and refuses with+ ``EPROTO`` if the Name the TPM reports differs from the computed+ one.+3. It extends the index with the init event through the init branch.+ The TPM evaluates each assertion, the writer key signs the session+ nonce and the cpHash of this ``TPM2_NV_Extend``, and+ ``TPM2_PolicyGetDigest`` confirms that the session reached the+ computed policy. The index is now written and has its written Name.+4. It extends PCR 9 with the SHA-256 of+ ``nvpcr-init:shirudo:0x1818e00:<written-name>``, systemd's anchor+ format, where ``<written-name>`` is the index's written Name in+ hex.++After step 4, PCR 9 no longer holds the value the init branch+requires, and once systemd measures ``leave-initrd``, PCR 11 does not+either. Nothing can satisfy the init branch again before the next TPM+reset, so an index that is deleted and recreated under the same policy+can never be written. An index recreated under another policy has+another Name, which matches neither the anchor in PCR 9 nor the record+``init`` kept.++Every later extension goes through the written branch, which also+requires the writer key's signature over the session nonce and the+cpHash of that one command. Before it extends, shirudo checks that the+live index carries the Name and policy ``init`` recorded, that the TPM+reports the recorded reset count, and that the writer key it creates+from the frozen bytes has the recorded modulus.++The signature alone does not keep other processes out. The bytes the+writer key derives from are not a secret, so any process that recreates+the key could ask the TPM to sign. An LSM hook in the kernel keeps+them out. The companion kernel patch+``kernel/0002-tpm-Let-LSMs-inspect-userspace-commands.patch`` adds an+LSM hook, ``tpm_command``, that sees every command written to+``/dev/tpm0`` or ``/dev/tpmrm0`` before the driver sends or queues it,+whichever process holds the descriptor. shirudo's ``lsm/tpm_command``+program refuses ``TPM2_NV_Extend`` of the frozen index to any task+without runtime authority. It also refuses, to every task, a command+too short to carry a command code and a ``TPM2_NV_Extend`` too short to+name its index. Each refusal counts as ``TpmExtend``. All other+commands pass, including extensions of other NV indices, signing and+PCR extensions.++The construction follows systemd's NvPCRs, which :doc:`boot`+introduces: the same index type, the two-branch policy and the+``nvpcr-init`` anchor. It differs in three ways. systemd's written+branch needs no further authorization, so anyone can append to an+NvPCR; shirudo requires a signed, command-bound authorization and the+LSM check on every write, because its events assert that an operation+happened. systemd binds the init branch to PCR 11 through a signed PCR+policy from the UKI, or through a plain ``TPM2_PolicyPCR`` on PCR 11+where none exists; shirudo binds it with a plain ``TPM2_PolicyPCR``+over PCRs 9 and 11, so the register's Name changes with the initrd and+the UKI, and the operator pins both values with ``--expect-bind-pcr``.+And the register is not a ``.nvpcr`` definition: systemd neither+initializes nor extends it, and its anchor appears in shirudo's+eventlog, not in systemd's measurement log.++Quotes and NV certification+---------------------------++``TPM2_Quote`` signs a ``TPMS_ATTEST`` structure with a restricted+key. The structure carries ``TPM_GENERATED_VALUE``, the qualified Name+of the signing key, the caller's nonce, the TPM's clock information+and firmware version, the PCR selection and the digest of the selected+PCR values. It proves that the TPM held those values when it signed,+and the nonce proves that it signed after the verifier asked.+``TPM2_NV_Certify`` signs the same kind of structure for an NV index,+with the index's Name, an offset and the contents.++``shirudo attest`` reads the selected PCRs, quotes them with the+verifier's nonce and keeps the quote only when its digest covers the+values it read, retrying up to three times. It certifies the+register's 32 bytes at offset 0 with the same nonce. The evidence+document also carries the public areas of the AK and EK, this boot's+eventlog records, the config history, the firmware and systemd event+logs and the EK certificate.++Only the quote and the certification are signed by the TPM. The rest+of the document is the target's own account, which ``attest verify``+checks against the signed values. In particular, it recomputes the+register's Name from the PCR values and the writer key that the init+record names. A register bound under other PCR values or with another+writer key has another Name and fails. :doc:`/operate/attest` lists+the checks and the options that pin each value.++Credential activation+---------------------++A signature by an AK proves nothing about where the AK lives until its+Name is tied to a TPM the verifier trusts. The EK certificate+identifies a TPM, but the EK cannot sign. Credential activation+connects the two.++``TPM2_MakeCredential`` needs no TPM; anyone can compute it in software+from the EK's public key. It encrypts a secret so that only the TPM+holding that EK can recover it, and only for a key with a given Name.+``TPM2_ActivateCredential`` takes the EK and a loaded key. The TPM+recovers a seed with the EK, checks an HMAC over the loaded key's+Name, and releases the secret only when the Name matches.++``shirudo attest challenge`` computes the credential on the operator+host. It draws a random 32-byte credential and a seed, which it wraps+with RSA-OAEP under the label ``IDENTITY`` for an RSA EK or derives+from an ephemeral ECDH agreement on P-256 for an ECC EK. From the seed+it derives an AES-128-CFB key and an HMAC key with the TPM's key+derivation function. On the target, ``shirudo attest --challenge``+satisfies the EK's policy with ``TPM2_PolicySecret`` and runs+``TPM2_ActivateCredential``, and the evidence carries the recovered+value. ``attest verify --expect-credential`` compares it. Together with+the attribute checks on the AK, this shows that the key that signed+the evidence is a restricted key fixed in the TPM that holds the EK.++Reset count and clock+---------------------++A TPM keeps a clock and two counters. The reset count increases at+every TPM reset, which a reboot causes. The restart count increases at+a TPM restart, after hibernation, and at a TPM resume, after sleep, and+returns to zero at a TPM reset. ``TPM2_ReadClock`` reads them, and+every quote and certification carries them. For keys outside the+endorsement and platform hierarchies the TPM obfuscates the counts in+signed structures. shirudo's AK is in the endorsement hierarchy, so the+evidence carries the real values.++``init`` records the reset count in its eventlog record, and uses it+to decide whether it has already bound the register in this TPM+period. An extension refuses when the TPM's reset count is not the+recorded one. ``attest verify`` checks that the quote and the+certification carry the same reset count and that it is the one the+init record names. Config activation records both counts.++Device interface+----------------++Linux exposes each TPM as two character devices. ``/dev/tpm0`` is the+raw device. Only one process can have it open at a time, and that+process sees the TPM's real handles and must manage its few slots for+objects and sessions itself. ``/dev/tpmrm0`` goes through the kernel's+resource manager. Any number of processes can open it, and the kernel+swaps objects and sessions in and out so that each open file sees only+its own. The kernel's own TPM users, such as IMA and trusted keys,+reach the TPM without either device.++shirudo talks to the TPM through the tpm2-tss library and the TCTI+named by ``tpm.tcti`` in its authenticated configuration,+``device:/dev/tpmrm0`` by default. While an authenticated image is+active it accepts only a ``device:`` TCTI, so its commands pass through+the character device and the ``tpm_command`` hook, and it ignores the+``SHIRUDO_TPM_TCTI`` environment variable.++Limits+------++The :doc:`/security/threat-model` gives the full analysis of each of+these.++- The transport is not authenticated. shirudo opens the device by path+ in the caller's mount namespace, and its sessions are unsalted and+ unbound, so no TPM response carries proof of its origin. The AK Name+ comparison detects a different TPM but not a device that replays the+ public Name. A root process that substitutes the device can keep+ shirudo's extensions from reaching the real register.+- The owner authorization travels as a password to whatever device is+ at the path, and root on the target can read it from the runtime+ image.+- The ``tpm_command`` guard covers ``TPM2_NV_Extend`` of the register+ only. ``TPM2_NV_UndefineSpace`` with the owner authorization and+ ``TPM2_PCR_Extend`` of PCR 9 or the config PCR remain open to root.+ They cannot rewrite the history, but they stop further extensions,+ fail ``--strict-anchor`` or block config commands until the next+ boot.+- The guard sees commands written to the TPM character devices.+ Kernel-internal TPM use and direct access to the TPM's bus are+ outside it, and every executable in the runtime image runs with+ runtime authority and can extend the register.+- A TPM restart clears the register but not the reset count. ``init``+ then refuses to bind the register again, and extensions fail with+ ``tpm_error`` until the next reboot.+- The algorithms are classical: ECDSA P-256 for the AK, RSA-3072 for+ the writer key, RSA 2048 or P-256 for the EK. Version 185 of the+ TPM 2.0 library specification adds ML-DSA and ML-KEM, and shirudo+ does not use them. See :doc:`pqc`.+- An EK is only as trustworthy as its certificate chain or the+ enrollment pin. Virtual TPMs usually have no EK certificate.+- ``attest verify`` warns but proceeds without ``--ak-name``, so the+ operator has to pin the AK on every verification.++Related+-------++- :doc:`boot` for measured boot, PCR 11 phases and NvPCRs.+- :doc:`/internals/measurement-register` for events and the eventlog.+- :doc:`/operate/attest` to attest a target.+- :doc:`/security/threat-model` for the residual risks.+- `TPM 2.0 Library specification+ <https://trustedcomputinggroup.org/resource/tpm-library-specification/>`__+- `TCG EK Credential Profile+ <https://trustedcomputinggroup.org/resource/http-trustedcomputinggroup-org-wp-content-uploads-tcg-ek-credential-profile/>`__+- `TPM2 PCR Measurements Made by systemd+ <https://systemd.io/TPM2_PCR_MEASUREMENTS/>`__diff --git a/Documentation/concepts/background/xattrs.rst b/Documentation/concepts/background/xattrs.rstnew file mode 100644index 00000000..9241989a--- /dev/null+++ b/Documentation/concepts/background/xattrs.rst@@ -0,0 +1,151 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++Extended attributes+===================++A security policy often has to mark files: this one belongs to the+policy, that one may be executed. Owner and mode bits cannot carry such+a mark, and a list of paths breaks as soon as a file is renamed or a+directory is bind-mounted elsewhere. Extended attributes attach the mark+to the inode itself. This page explains them, how security modules use+them, and how shirudo's seal does.++Names and namespaces+--------------------++An extended attribute (xattr) is a name and a value stored with an+inode. Userspace reads and writes them with ``getxattr(2)``,+``setxattr(2)``, ``listxattr(2)`` and ``removexattr(2)``. Every name+starts with a namespace prefix, and the namespace decides who may access+it:++``user.``+ Ordinary file permissions apply: reading needs read permission on+ the file, writing needs write permission. Only regular files,+ directories and sockets take them, and on a sticky directory only+ its owner or a privileged task may write them.++``trusted.``+ Reading and writing both need ``CAP_SYS_ADMIN``.++``security.``+ Reserved for security modules. The file system layer does not+ restrict reading. Writing needs ``CAP_SYS_ADMIN`` in the file system's+ user namespace, unless a security module takes over that check for+ its own names, and every write also passes the ``inode_setxattr``+ hooks of all active LSMs.++``system.``+ Used by the kernel itself, for POSIX ACLs for example. The file+ system decides access.++How security modules label inodes+---------------------------------++An LSM that keeps per-file state stores it as a ``security.`` xattr:+SELinux uses ``security.selinux``, IMA ``security.ima``, file+capabilities ``security.capability``. The label travels with the inode+through renames and bind mounts.++A label is most useful when an inode carries it from the moment it+exists. When a file system creates an inode, it calls the+``inode_init_security`` hook. Each LSM may fill reserved slots with the+xattrs the new inode should carry, and the file system writes them as+part of the same operation that creates the inode. A file system without+that support passes no slots, and the inode starts unlabelled.++Later changes go through ``setxattr(2)`` and ``removexattr(2)``. The+``inode_setxattr`` and ``inode_removexattr`` hooks run before the change+and can refuse it. The ``inode_post_setxattr`` and+``inode_post_removexattr`` hooks run after it.++security.bpf. namespace and its kfuncs+--------------------------------------++BPF LSM programs (see :doc:`bpf-lsm`) can work with xattrs through+kfuncs:++``bpf_get_file_xattr()`` and ``bpf_get_dentry_xattr()``+ Read an xattr whose name starts with ``user.`` or ``security.bpf.``.+ They first check that the current task may read the inode+ (``inode_permission()`` with ``MAY_READ``) and return its error if+ not. Both may sleep, so only sleepable programs call them.++``bpf_set_dentry_xattr()`` and ``bpf_remove_dentry_xattr()``+ Write or remove a ``security.bpf.`` xattr, after a check that the+ current task may write the inode. Only sleepable LSM programs may+ call them.++``bpf_inode_init_xattr()``+ Fills one of the slots of the ``inode_init_security`` hook with a+ ``security.bpf.`` xattr, so that a new inode is created with it. Only+ a program on that hook may call it, and the BPF LSM reserves two+ slots per inode.++Userspace can also write ``security.bpf.`` names with ``setxattr(2)``,+under the rules of the ``security.`` namespace.++File system support+-------------------++Whether a file system stores ``security.`` xattrs depends on the file+system and its configuration. ext4 stores them with+``CONFIG_EXT4_FS_SECURITY``. tmpfs stores ``security.``, ``trusted.``+and ``user.`` names with ``CONFIG_TMPFS_XATTR``. bpffs stores+``security.`` and ``trusted.`` names. On a file system without support,+the calls fail with ``EOPNOTSUPP``.++overlayfs needs care. Before the first write to a file from a lower+layer, overlayfs copies the file up into the upper layer, and the copy+takes the lower file's xattrs with it, labels included. The write then+changes the copy, and the original stays as it was.++How shirudo uses xattrs+-----------------------++shirudo's seal marks writable state with the xattr+``security.bpf.shirudo``. Its value is a fixed 64-character string, the+same on every target; the seal treats any inode that carries a label+under that name as protected. ``shirudo init`` labels the state tree+under ``/var/lib/shirudo`` on its first run, and ``/run/shirudo`` on+every boot. From then on, the seal's ``lsm/inode_init_security``+program labels every new inode created in a marked directory, with+``bpf_inode_init_xattr()``.++The seal's sleepable programs read the label with+``bpf_get_file_xattr()`` and ``bpf_get_dentry_xattr()``. A labelled inode+may be opened for writing, removed, renamed, changed in its attributes or+xattrs only by a task with runtime authority. Only such a task may set+the label itself; anyone else's attempt counts as ``SealLabel``, and+other xattr changes on a labelled inode as ``SealXattr``. The label marks+what is protected; it never grants authority to the task that carries+or copies it. The seal also refuses an overlay copy-up of a marked inode+(``SealCopyUp``). See :doc:`/internals/seal`.++The second xattr, ``security.bpf.shirudo.payload``, sits on each upatch+directory in the private bpffs, ``/run/shirudo/bpffs/upatches/<name>``.+``shirudo upatch load`` writes the 32-byte SHA-256 of the payload there.+``shirudo upatch unload`` reads it and refuses with ``payload_mismatch``+when it differs from the digest the signed unload directive names, or+cannot be read. shirudo's ``lsm/inode_setxattr`` and+``lsm/inode_removexattr`` programs refuse xattr changes in the private+bpffs to every task without runtime authority (``PinXattr``). See+:doc:`/reference/files` for the paths.++Limits+------++The read kfuncs check the calling task's read permission even for+``security.bpf.`` names. When another LSM, or file permissions, deny that+task read access, the seal sees no label and allows the operation; the+file system's own permission checks then decide. The threat model lists+this under threats to resolve: :doc:`/security/threat-model`.++The seal caches the label of directories in inode storage, which is lost+when a directory leaves the inode cache. A file system without+``security.`` xattrs cannot carry the label at all.diff --git a/Documentation/concepts/comparisons.rst b/Documentation/concepts/comparisons.rstnew file mode 100644index 00000000..01d449d8--- /dev/null+++ b/Documentation/concepts/comparisons.rst@@ -0,0 +1,222 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++How shirudo compares+====================++shirudo combines mechanisms that also exist on their own: signed BPF,+the BPF LSM, kernel keyrings, dm-verity and TPM measurement. Each of the+approaches below solves part of the problem shirudo addresses: change+what a running kernel does without a reboot, keep control of which code+runs, and be able to prove it later. For each, this page says what it+does, what it leaves open, and whether shirudo complements it, builds on+it or takes its place.++Kernel live patching+--------------------++Kernel live patching redirects calls of a kernel function to a+replacement function. The kernel's livepatch subsystem installs the+redirection through ftrace and switches tasks to the new code one by one+under a consistency model, and a patch can attach extra data to existing+structures through shadow variables. A live patch is a kernel module,+built from a source patch with kpatch-build or with ``klp-build`` from+the kernel tree's ``scripts/livepatch/``.++A live patch can replace any function that ftrace can trace, so it can+carry the fix itself. It is native kernel code: no verifier checks it, it+is built for one kernel build, and who may load it is decided by module+signature enforcement and lockdown. The livepatch subsystem does not+measure the patches it applies into the TPM, though IMA can measure+module loads.++shirudo complements live patching. An upatch cannot replace a function+body. It can refuse a call before the function runs, at an LSM hook, a+``security_*`` function, a system call entry or a function marked for+error injection, and it can observe or filter+(:doc:`/upatches/attach-kinds`). In exchange, the BPF verifier checks+every program, CO-RE lets one artifact load on more than one kernel+build, and each load and unload is measured. A target can run both:+shirudo does not gate module loading (:doc:`/operate/interoperability`).+Used together, an upatch blocks a vulnerable path until a live patch or a+fixed kernel is in place, and a signed unload directive removes it then.++IMA and IPE+-----------++IMA measures files when the kernel executes, maps or loads them, as+modules, firmware or kexec images among others, into a PCR and a+measurement list. IMA appraisal checks those files against a hash or a+signature, kept in their ``security.ima`` attribute or appended to the+file. IPE is an LSM that decides on the same kinds of operations by an+immutable property of where a file comes from: the initramfs, a+dm-verity device with a given root hash or a signed one, or an fs-verity+digest or signature.++Both work on files. Neither IMA's policy functions, listed in+``Documentation/ABI/testing/ima_policy`` of the kernel tree, nor IPE's+operations include a BPF program load. A BPF program reaches the kernel+as bytes in a ``bpf()`` call, not as a file the kernel reads, so a+system that runs only verified executables can still load any BPF+program its root asks for. The kernel's BPF signing documentation names+IPE as an LSM that could enforce signed BPF in the future.++shirudo complements both. It covers ``bpf()``, which they do not. For+its own executable it uses the idea behind IPE's ``dmverity_roothash``+property: only an exec of a file on the dm-verity device whose root hash+the UKI pinned gives a process shirudo's authority+(:doc:`/internals/seal`). IMA can run on the same target. shirudo+measures into its own register, anchored in PCR 9, not into IMA's list+(:doc:`/concepts/measurement-register`).++Policy engines on the BPF LSM+-----------------------------++The BPF LSM, first proposed as kernel runtime security instrumentation+(KRSI), lets privileged users attach BPF programs to LSM hooks and so+implement access control and audit policies at runtime. Engines built+on BPF add policy management on top. Tetragon, for example, describes+itself as eBPF-based security observability and runtime enforcement:+tracing policies, as Kubernetes custom resources, name kprobes,+tracepoints or uprobes, filter events in the kernel and act on them, by+overriding a return value or sending a signal. Policies load at startup+from flags, or at runtime through Kubernetes or a command-line client.++The BPF LSM is a mechanism. It refuses nothing until programs attach,+and it does not decide on its own which other programs may load or who+may detach them. An engine's protection of itself depends on what its+own policy covers, and its agent, which takes policy changes at runtime,+is part of what a host must trust.++shirudo is a BPF LSM policy too, with a fixed purpose: it governs+``bpf()`` itself, so that only signed loaders install BPF, and it guards+its own links, maps and state. It takes no policy at runtime. Every+change is a signed artifact that a one-shot command loads and the+register records. An engine that loads its own programs cannot run on+an enforcing target. Its hooks and its logic can be written as upatches+with the ``lsm``, ``fentry`` or ``kprobe`` attach kinds, and a policy+change then becomes a signed build.++Signed BPF and BPF tokens+-------------------------++The kernel verifies the signature of a BPF loader program, over its+instructions and the metadata map it installs, against a keyring, and+records the verdict on the program. On its own it requires nothing: an+unsigned program loads as before, and an LSM has to refuse what it does+not want (:doc:`/concepts/background/bpf-signing`).++BPF tokens delegate part of ``bpf()`` to a user namespace. A bpffs+instance mounted with ``delegate_cmds=``, ``delegate_maps=``,+``delegate_progs=`` and ``delegate_attachs=`` lets a process in that+namespace create a token and use the delegated commands, map types,+program types and attach types, with capabilities checked in that+namespace. A token cannot be created in the initial user namespace.+Tokens decide who may use which part of ``bpf()``, not which code runs.++shirudo builds on signing. It is the LSM that acts on the verdict: a+load from userspace passes only when the kernel verified it against the+``.bpf`` keyring that ``init`` enrolled, sealed and froze. Around that+it adds the enrollment of trusted keys, the guards for its own objects,+delivery and measurement. It refuses ``BPF_TOKEN_CREATE``, so tokens+give nothing on an enforcing target.++dm-verity and measured boot+---------------------------++dm-verity checks every block read from a device against a hash tree+whose root hash is trusted, and the kernel can require a signature on+that root hash (:doc:`/concepts/background/dm-verity`). In a measured+boot, the firmware, the boot loader and systemd extend TPM PCRs with+what they load, so that a quote shows what booted+(:doc:`/concepts/background/boot`).++Both describe what was on disk and what started. A BPF program enters+the kernel later, through a system call from any process with the+privilege, with no read from a verified device in between, and nothing+in the boot measurements records it. A kernel and an initrd that+attested correctly can run any BPF program minutes later.++shirudo builds on both. The signed UKI, measured into PCR 11, pins the+root hash of the runtime image. The runtime and config images are+dm-verity devices, and the kernel verifies the config image's signature.+``init`` binds the measurement register under PCR 9 and PCR 11 and+anchors it in PCR 9, and every upatch state change extends it. The+register carries measured boot past the boot, into the BPF state of the+running kernel.++Security agents with daemons+----------------------------++A traditional security agent is a long-running privileged process on+each host. It keeps a channel to a management service, receives policy+and code over it, applies them and reports back. Its kernel parts, if it+has any, live as long as the process holds them.++The daemon and its channel are part of the host's trusted computing+base and of its attack surface. Root can stop the process. What it+reports is its own account unless hardware vouches for it.++For delivering and enforcing BPF on a target, shirudo takes this+model's place. The target runs no daemon and listens on no socket.+Enforcement stays in links pinned in a private bpffs after ``init``+exits. Packages arrive by pull, from timers. The status keepalive is the+target's own, unauthenticated account, and only TPM-signed evidence that+the operator verifies off the target is proof+(:doc:`/concepts/operator-and-target`). shirudo has no inventory,+rollout orchestration or remote response; those stay with the+infrastructure that already runs the fleet. Its own limits are in+:doc:`/security/threat-model`: root can run every command of the+runtime binary (R2), and telemetry has no proof of origin (R17).++Summary+-------++.. list-table::+ :header-rows: 1+ :widths: 24 38 38++ * - Approach+ - Covers+ - shirudo+ * - Kernel live patching+ - Replacing kernel functions, with native code in a module+ - Complements: refuses or observes with verified BPF, measured+ * - IMA and IPE+ - Files the kernel executes, maps or loads+ - Complements: covers ``bpf()``+ * - Policy engines on the BPF LSM+ - Policies that change at runtime, through an agent+ - Takes the place of the engine's loader. Policies become signed+ upatches+ * - Signed BPF and BPF tokens+ - A verdict on a loader's origin, and delegation of privilege+ - Builds on signing. Refuses tokens+ * - dm-verity and measured boot+ - What was on disk and what booted+ - Builds on both, and measures the BPF state after boot+ * - Agents with daemons+ - Policy and code over a management channel+ - Takes the agent's place for BPF delivery, without a daemon++Related+-------++- :doc:`/concepts/operator-and-target`+- :doc:`/concepts/upatches-and-packages`+- :doc:`/operate/interoperability`+- :doc:`/security/threat-model`+- `Livepatch <https://docs.kernel.org/livepatch/livepatch.html>`__ and+ `Integrity Policy Enforcement+ <https://docs.kernel.org/admin-guide/LSM/ipe.html>`__ in the kernel+ documentation+- `LSM BPF Programs <https://docs.kernel.org/bpf/prog_lsm.html>`__ and+ the LWN article `Kernel runtime security instrumentation+ <https://lwn.net/Articles/798157/>`__+- `kpatch <https://github.com/dynup/kpatch>`__+- `Tetragon tracing policies+ <https://tetragon.io/docs/concepts/tracing-policy/>`__diff --git a/Documentation/concepts/glossary.rst b/Documentation/concepts/glossary.rstnew file mode 100644index 00000000..6e4d6c67--- /dev/null+++ b/Documentation/concepts/glossary.rst@@ -0,0 +1,464 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: All readers++Glossary+========++The terms the shirudo documentation uses, each with the page that explains+it.++.. glossary::+ :sorted:++ anchor+ The SHA-256 of the string ``nvpcr-init:shirudo:0x<handle>:<name>``,+ with the measurement register's NV handle and TPM name, which+ ``init`` extends into PCR 9 right after it binds the register. It+ ties the register to the measured boot and closes the register's+ first-write branch until the next TPM reset. ``shirudo attest+ verify`` checks that PCR 9 carries it. See+ :doc:`/concepts/measurement-register`.++ arena+ A BPF map of type ``BPF_MAP_TYPE_ARENA``, a memory region from which+ BPF programs allocate records directly. An upatch that accumulates+ records keeps them in one arena, which its serializer reads as one+ consistent snapshot and can reset between exports.+ ``upatches/kernel-obs/obs_table.h`` is the template for a+ double-buffered arena table. See+ :doc:`/upatches/maps-arenas-serializers`.++ attach metadata+ The signed ``UPGM`` section of a load artifact that tells shirudo+ how to attach each program: its role, its attach kind and, for+ kprobes and uprobes, the site. It is signed because the site of a+ kprobe, uprobe, ``cgroup_skb`` or ``netfilter`` program is chosen+ when the link is created, not by the program's instructions. After+ attaching, shirudo compares each link with it and refuses with+ ``attach_scope_mismatch`` on a difference. See+ :doc:`/concepts/upatches-and-packages`.++ attestation key+ The TPM key that signs evidence: a restricted ECDSA P-256 signing+ key, created as a primary under the endorsement hierarchy from a+ fixed template, so the same TPM always yields the same key.+ ``shirudo attest`` creates it for each run and flushes it+ afterwards. The operator pins its name when enrolling a target and+ passes it to ``shirudo attest verify --ak-name``. See+ :doc:`/concepts/measurement-register`.++ Beefile+ The definition of a bpm package: a file in a subset of TOML, in the+ package directory, that names the package and lists its upatch+ sources, read-only data generators, extra files and tree selectors.+ ``shirudo bpm build`` reads ``Beefile`` in the package directory, or+ the file that ``-f`` names. See :doc:`/upatches/beefile`.++ BPF keyring+ The kernel's ``.bpf`` keyring, which the kernel uses for a signed+ BPF program whose load names ``KEY_SPEC_BPF_KEYRING``. Booted with+ ``bpf.keyring_unsealed=1``, it starts open; ``init`` enrolls the+ trusted set and seals it, and ``lsm/key_permission`` keeps tasks+ without runtime authority from removing keys. ``lsm/bpf_prog_load``+ admits a load from userspace only when the kernel verified its+ signature against this keyring. See+ :doc:`/concepts/background/keyrings`.++ bootstrap settings+ The settings ``init`` needs before it trusts a config image. The+ initrd's ``/etc/shirudo/shirudo.conf`` names the runtime image and+ its root hash (``runtime.image``, ``runtime.root_hash``). The+ runtime image's ``etc/shirudo/shirudo.conf`` names the config image,+ its verification certificate and its PCR (``config.image``,+ ``config.verification_key``, ``config.pcr``) and holds the TPM+ settings; no config image can change them. See+ :doc:`/internals/config-images`.++ bpm package+ A versioned ``.bee`` file that ``shirudo bpm build`` makes from a+ Beefile: a gzip-compressed tar archive with the Beefile, the+ package's upatches and unload directives, its ``README.md``, the+ signing certificate and a record of the build environment. The+ package carries no signature of its own. A repository's signed index+ lists its digest, and each upatch inside is signed. See+ :doc:`/concepts/upatches-and-packages`.++ challenge+ The credential that ``shirudo attest challenge`` makes on the+ operator host for a target's endorsement key and the pinned+ attestation key name. The target's TPM recovers it with ``shirudo+ attest --challenge=<path>`` only when both keys are in that TPM, and+ ``shirudo attest verify --expect-credential`` checks the recovered+ value. It shows that the attestation key sits in the TPM the+ endorsement key identifies. See :doc:`/operate/attest`.++ config image+ A dm-verity image, mounted read-only and ``noexec`` at+ ``/run/shirudo/config``, that carries what an operator changes+ during operation: repositories and their certificates, the tree+ subscription, node labels, vouched and revoked certificates, and+ export settings. Its root hash is signed, and the kernel checks the+ signature against its trusted keys, which include the sealed+ ``.dm-verity`` keyring. ``shirudo image update`` activates a new+ config image without a reboot and measures it into a dedicated PCR.+ See :doc:`/internals/config-images`.++ decoder+ A Lua function shipped inside an upatch that turns a snapshot of one+ map into OTLP log records or metrics. The program declares it with+ a ``struct shirudo_decoder_manifest`` in ``.rodata``,+ ``shirudo-build`` embeds the source in the signed ``DCDB`` section,+ and ``shirudo upatch map`` runs it under LuaJIT. See+ :doc:`/upatches/decoders`.++ endorsement key+ A key that identifies a TPM, derived from its endorsement seed with+ a template the TCG fixes, and often described by a certificate from+ the TPM's manufacturer. shirudo uses it for credential activation,+ which ties the attestation key to this TPM, and checks the+ certificate's chain when the operator passes ``--ek-ca``. The+ evidence carries its public part and, when the TPM holds one, its+ certificate. See :doc:`/concepts/background/tpm`.++ enforcement programs+ The BPF LSM programs embedded in the ``shirudo`` binary, built from+ ``bpf/bpf2.c`` (``bpf()`` admission, keyrings, the private bpffs,+ mounts, devices and the TPM) and ``bpf/seal.c`` (the seal and the+ task marks). ``init`` loads them before their admission gates+ attach, so they are the one BPF code that does not pass the signed+ loader path; in production the authenticated initrd vouches for+ them. Their links are pinned in the private bpffs. See+ :doc:`/internals/enforcement`.++ eventlog+ The file ``/var/lib/shirudo/eventlog``, with one JSON line for every+ extend of the measurement register: the event digest, its type, the+ boot ID and the fields the digest covers. shirudo only appends to it+ and keeps the records of every boot. A verifier trusts it only as+ far as this boot's records replay to the value the TPM certifies.+ See :doc:`/reference/formats/eventlog`.++ evidence+ The JSON document, of kind ``shirudo-attestation``, that ``shirudo+ attest --nonce=<hex>`` writes on a target. It carries a TPM quote+ over the selected PCRs and a TPM certification of the measurement+ register, both signed by the attestation key over the nonce,+ together with the attestation and endorsement keys, this boot's+ eventlog records and the boot measurement logs. ``shirudo attest+ verify`` checks it on the operator host. See :doc:`/operate/attest`.++ failure category+ A name for why an operation failed, such as ``tampered``,+ ``signature_rejected`` or ``payload_mismatch``. ``shirudo upatch+ load`` and ``unload`` print it and write it, with the phase the+ operation reached, into the ``--report`` document. ``tampered``+ means refresh the state and decide again, never retry the same+ input. See :doc:`/reference/failure-categories`.++ identity map+ A one-entry BPF array map, pinned at+ ``/run/shirudo/bpffs/identity``, in which ``init`` records what the+ enforcement programs compare against: the devices of the private+ bpffs and of ``/run/shirudo``, the ``.bpf`` keyring and the enrolled key+ serials, the runtime image's root hash, the NV index and its writer+ key, the attestation key's name and the ``.dm-verity`` keyring.+ ``init`` freezes it before the admission gates attach, so userspace+ cannot change it afterwards. See :doc:`/internals/enforcement`.++ init record+ The eventlog record of type ``init`` that ``shirudo init`` writes+ when it binds the measurement register. It carries the ``init``+ event's inputs, the values of PCRs 9 and 11 before the binding,+ whether the initrd made the binding, the register's TPM name, the+ anchor, the TPM reset count and the writer key's public part. In the+ initrd, ``init`` writes it to ``/run/shirudo/eventlog.pending``, and+ the root file system's run adopts it. See+ :doc:`/internals/measurement-register`.++ keepalive+ An OTLP log record named ``shirudo.keepalive`` that carries a+ target's status. ``shirudo-keepalive.timer`` runs ``shirudo status+ --otel --include-system`` about every five seconds, which sends one+ when an OTLP endpoint is configured. A missing keepalive tells a+ collector that a target stopped reporting; a present one is still+ the target's own account. See :doc:`/operate/telemetry`.++ load artifact+ A ``.upatch`` file that installs an upatch: a header with the name+ and the payload digest, the signed loader's instructions, the+ loader's data with the signed sections, and a CMS signature over the+ instructions followed by the data. ``shirudo build`` writes it, and+ ``shirudo upatch load`` loads it. See+ :doc:`/reference/formats/upatch-format`.++ map export+ The periodic export of upatch map contents.+ ``shirudo-map-export.timer`` runs ``shirudo upatch map --all`` about+ every five seconds, which reads the maps of every loaded upatch,+ runs their serializers and decoders, and sends the records to the+ destinations that the config image's ``map_export`` settings name.+ See :doc:`/operate/telemetry`.++ measurement register+ The TPM NV extend index, ``0x01818E00`` by default, that records+ every change to a target's BPF state during one boot. Each extend+ needs a signature from the per-boot writer key, and+ ``lsm/tpm_command`` keeps tasks without runtime authority from+ submitting one. It clears at every TPM reset, so its value depends+ only on the trusted certificates, the restored set, the tree+ position and the events since boot. See+ :doc:`/concepts/measurement-register`.++ metadata map+ The array map ``__loader.map`` that holds a signed loader's data+ during a load. shirudo creates it exclusive to the loader, by the+ SHA-256 of the loader's instructions, fills and freezes it, and+ passes it with the loader to ``BPF_PROG_LOAD``. The kernel verifies+ the signature over the instructions followed by the map's frozen+ contents. See :doc:`/internals/signed-loader`.++ NV extend index+ A TPM non-volatile index of type ``TPM2_NT_EXTEND``, which a write+ extends like a PCR instead of overwriting. shirudo's measurement+ register is one, with ``TPMA_NV_CLEAR_STCLEAR`` set so that it+ clears at every TPM reset, following systemd's NvPCRs. See+ :doc:`/concepts/background/tpm`.++ NV writer key+ An RSA-3072 key that ``init`` creates inside the TPM at every boot,+ and whose signature the measurement register's write policy+ requires for every extend. The identity map holds its public part+ and the input that recreates it, and each command recreates the key+ to sign one exact extend command. The key is no secret;+ ``lsm/tpm_command`` is what keeps other tasks from extending. See+ :doc:`/internals/measurement-register`.++ operator+ The role that holds the private ML-DSA-87 signing key, builds and+ signs upatches, publishes packages and verifies evidence. The+ operator is stateless: it writes only the key pair and the files+ the caller names, and it never opens a TPM or a kernel keyring. See+ :doc:`/concepts/operator-and-target`.++ operator host+ The machine where the operator's commands run and the signing key is+ kept. It needs the ``shirudo-build`` helper and clang, and no TPM.+ Its integrity is outside what shirudo protects. See+ :doc:`/concepts/operator-and-target`.++ payload digest+ SHA-256 over a load artifact's loader instructions followed by its+ data, stored as ``payload_sha256`` in the header. The target+ recomputes it before loading and refuses a mismatch. From then on it+ identifies the upatch: in the ``security.bpf.shirudo.payload``+ attribute on the pin directory, in the measurement events and in+ the unload directive that removes it. See+ :doc:`/concepts/upatches-and-packages`.++ pin+ A file in a BPF file system that keeps a BPF object, such as a link+ or a map, alive after the process that created it exits. shirudo's+ commands are one-shot, so every link and map that must stay is+ pinned in the private bpffs. Removing a pin detaches a link once+ nothing else holds it. See :doc:`/concepts/background/bpf`.++ predict+ ``shirudo attest predict``, which computes on the operator host the+ register values a target must hold: the set digest, the ``init``+ event, the register at boot and, with ``--event``, the register+ after later events. It uses the target's own functions, applied to+ the certificates and artifacts the operator names. See+ :doc:`/reference/cli/attest-predict`.++ private bpffs+ The BPF file system instance that ``init`` mounts at+ ``/run/shirudo/bpffs`` with mode ``0700``. It holds the pins of the+ enforcement links, the identity map, the tamper counters and every+ upatch's links and maps. BPF LSM hooks refuse unlink, rename and+ opening a pin there to tasks without runtime authority, and refuse+ every caller the unmount, move or remount of the mount ``init``+ made. See :doc:`/internals/enforcement`.++ projection root+ A hash chain over the upatch tree operations a target applied, kept+ in its tree state. The next boot's ``init`` event includes it, so+ the predicted register covers the tree, and ``shirudo attest predict+ --tree-root`` takes it as input. See+ :doc:`/concepts/upatches-and-packages`.++ repository+ A named OCI registry endpoint together with the certificate that+ signs its index. On a target, repositories come from the config+ image's ``etc/shirudo/bpm/registries.d/``, and ``shirudo bpm install+ <repository>/<package>`` installs from one. See+ :doc:`/operate/deliver-packages`.++ revocation+ Withdrawing trust from a signing key through a signed config image+ whose ``keys/revoked/`` directory names the key's certificate. When+ ``shirudo image update`` activates such a config, shirudo unlinks the+ key from the ``.bpf`` keyring, measures a key revocation event, and+ unloads and purges every upatch the key signed. ``shirudo keys+ revoke`` refuses and points to this path. See :doc:`/operate/keys`.++ runtime authority+ The right that a task mark grants: to run the ``bpf()`` commands,+ descriptor accesses, pin changes, sealed-state writes, keyring+ changes and TPM extends that the enforcement programs reserve for+ shirudo. It never replaces a signature, since a program load from+ userspace needs a verified signature whoever asks. See+ :doc:`/concepts/operator-and-target`.++ runtime image+ The dm-verity image, mounted read-only at ``/run/shirudo/runtime``,+ that carries the ``shirudo`` executable, the initial BPF certificate+ ``keys/cert.der``, the config verification certificate and the+ bootstrap settings. The UKI's initrd names its root hash, so the+ measured boot covers it. Every executable on it gains runtime+ authority when it runs. See :doc:`/internals/config-images`.++ seal+ The BPF LSM programs from ``bpf/seal.c`` that protect shirudo's+ writable state and processes. They refuse writes, unlinks, renames,+ attribute changes and new entries on labeled inodes under+ ``/var/lib/shirudo`` to tasks without runtime authority, and keep+ other tasks from tracing a marked task. They do not revoke writable+ descriptors or mappings that existed before. See+ :doc:`/internals/seal`.++ seal label+ The extended attribute ``security.bpf.shirudo`` with a fixed+ 64-character value that marks an inode the seal protects. ``init``+ labels shirudo's writable state, and a new inode under a labeled+ directory inherits the label. The label marks a target, not an+ authority, so copying it onto a binary grants nothing. See+ :doc:`/internals/seal`.++ selector+ The condition on an upatch tree operation: lists of architectures,+ kernel release prefixes, kernel build IDs, kernel configuration+ values and node labels. ``shirudo bpm tree sync`` evaluates it on+ the target and applies only matching operations, and a+ non-matching operation is skipped for good. See+ :doc:`/upatches/publishing`.++ serializer+ A ``SEC("syscall")`` program in an upatch, named+ ``shirudo_serialize__<map>``, that renders one map into the+ upatch's ``shirudo_ser`` output map in chunks of 4096 bytes.+ ``shirudo upatch map`` runs it with ``BPF_PROG_TEST_RUN``, which+ gives one consistent snapshot of an arena and lets the serializer+ reset what it exported. See :doc:`/upatches/maps-arenas-serializers`.++ ``shirudo-build``+ The operator-only helper that the core ``shirudo`` binary executes+ for ``build``, ``bpm build``, ``bpm push``, ``bpm tree append``,+ ``bpm config update``, ``image build``, ``image verify`` and ``keys+ vouch``. It links the signer, runs clang and runs ``veritysetup``.+ The operator package installs it and the target package does not.+ See :doc:`/concepts/operator-and-target`.++ ``SHIRUDO_VERSION_ID``+ A build identity that ``shirudo version`` prints: SHA-256 over the+ source revision and a digest of the build configuration files. It+ does not hash the binary, so builds of one source for x86-64, arm64+ and riscv64 share it. ``shirudo upatch load+ --expect-version-id=<id>`` refuses with ``version_mismatch`` when+ the target's differs. See :doc:`/reference/cli/version`.++ signed index+ The JSON document at ``shirudo/bpm-index:stable`` in a registry that+ lists each package's name, version, manifest digest and package+ digest, with a detached CMS signature. ``shirudo bpm push`` updates+ it and refuses to list a version again with different content, and+ ``shirudo bpm repo update`` verifies it against the repository's+ certificate. See :doc:`/reference/formats/bpm-formats`.++ signed loader+ A BPF program of type ``BPF_PROG_TYPE_SYSCALL``, generated by+ libbpf's ``gen_loader``, that creates an upatch's maps and loads its+ programs from inside the kernel. The operator signs its instructions+ followed by its data, and the kernel checks that signature at+ ``BPF_PROG_LOAD`` against the ``.bpf`` keyring. After ``init``, it+ is the only way BPF from userspace enters the kernel. See+ :doc:`/internals/signed-loader`.++ tamper counter+ A counter for one point at which the enforcement programs refuse a+ caller, such as ``BpfCommand``, ``PinUnlink`` or ``ObjGet``. The+ counters live in a map pinned at ``/run/shirudo/bpffs/tamper`` that+ only the enforcement programs increment, and ``shirudo status``+ reports them. Not every refusal has a counter. See+ :doc:`/security/tamper-counters`.++ target+ A Linux machine with a TPM 2.0 that runs shirudo from an+ authenticated runtime image, enforces signed BPF in its kernel and+ measures every change into its TPM. It holds public certificates+ only, runs no daemon and pulls packages on timers. See+ :doc:`/concepts/operator-and-target`.++ task mark+ A per-task record in BPF task storage that the seal sets when a task+ successfully executes a file from the runtime image. A forked child+ inherits it, a successful exec of any other file clears it, and a+ failed exec leaves it unchanged. The enforcement programs consult it+ instead of the task's path or user. See :doc:`/internals/seal`.++ tree publication+ One generation of an upatch tree: a JSON document with the tree ID,+ the generation number, the digest of the manifest it replaces and+ the ordered operations, published with a detached CMS signature+ under a tag of the tree repository, ``stable`` by default. ``shirudo+ bpm tree append`` publishes the next generation, and targets verify+ it against the runtime image's certificate. See+ :doc:`/reference/formats/bpm-formats`.++ trusted set+ The certificates a target enrolls in the ``.bpf`` keyring at boot:+ the runtime image's ``keys/cert.der``, and every certificate under+ the config image's ``keys/trusted/`` whose vouch verifies under a+ member, less those the config revokes. It holds at most 16+ certificates, and the ``init`` event covers its digest. See+ :doc:`/operate/keys`.++ unload directive+ A signed ``.upatch`` with the unload flag set that removes one+ upatch. Its signed sections name the upatch and the payload digest+ it must have. The target has the kernel verify the directive's+ loader without running it, and refuses with ``payload_mismatch``+ when the digest differs from the pin's. See+ :doc:`/concepts/upatches-and-packages`.++ upatch+ A signed BPF object, one or more programs with their maps and attach+ metadata, that a target loads, pins, archives and measures as one+ unit. It ships as a load artifact and leaves through an unload+ directive. See :doc:`/upatches/concepts`.++ upatch tree+ A signed, append-only, ordered list of operations, each adding or+ deleting one upatch on the targets its selector matches. Targets+ subscribe through their config image, and ``shirudo bpm tree sync``+ applies new matching operations in sequence and measures each. See+ :doc:`/concepts/upatches-and-packages`.++ verdict+ The one-word result of a check. ``shirudo status`` reports an+ overall status of ``ok``, ``degraded``, ``reboot-pending``,+ ``init-pending``, ``lsm-off`` or ``tampered``, and ``OK``, ``WARN``+ or ``ALERT`` for each condition. ``shirudo attest verify`` ends with+ ``verdict: ok`` or ``verdict: FAIL``. See :doc:`/operate/read-status`.++ vouch+ A detached CMS signature by a trusted key over the prefix+ ``shirudo-key-vouch``, its terminating NUL and another certificate's+ DER. ``shirudo keys vouch`` makes one, and a config image ships it+ beside that certificate under ``keys/trusted/``, which admits the+ certificate to the trusted set at the next boot. A vouch carries no+ date, so it stays valid after its signer is revoked. See+ :doc:`/operate/keys`.diff --git a/Documentation/concepts/index.rst b/Documentation/concepts/index.rstnew file mode 100644index 00000000..49c50631--- /dev/null+++ b/Documentation/concepts/index.rst@@ -0,0 +1,24 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++Concepts+========++These pages explain the ideas the rest of the documentation relies on.+The background pages introduce the Linux and platform mechanisms that+shirudo builds on, for readers who have not worked with them. The pages+after them explain shirudo's own model: the operator and target roles,+the objects an operator ships to targets, and the measurement register+that records what a target runs. The glossary defines each term with a+link to the page that explains it.++.. toctree::+ :titlesonly:++ background/index+ operator-and-target+ upatches-and-packages+ measurement-register+ comparisons+ glossarydiff --git a/Documentation/concepts/measurement-register.rst b/Documentation/concepts/measurement-register.rstnew file mode 100644index 00000000..18654f51--- /dev/null+++ b/Documentation/concepts/measurement-register.rst@@ -0,0 +1,247 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++Measurement register+====================++Every change to a target's BPF state is recorded in a register inside the+target's TPM, and the TPM signs that record on request. This page explains+why the record lives in a per-boot TPM register, what it records, what the+eventlog beside it is for, and what attestation proves and what it does+not. :doc:`/internals/measurement-register` describes the register's+attributes, policy and evidence format in full.++Why the TPM+-----------++A target reports its own state through ``shirudo status``. That report is+the target's word. On a compromised target, root controls the files and+processes that produce it, and a status that says ``ok`` is what an+attacker would arrange.++An operator needs a record that root cannot rewrite afterwards, and a+signature on it that root cannot forge. A TPM provides both. A value it+holds can only be extended, never set, and it signs reports with keys that+never leave it. :doc:`/concepts/background/tpm` explains these operations.++Why not a PCR+-------------++The obvious place for the record is a PCR. On a typical Linux system the+firmware, the boot loader, systemd and IMA already measure into the PCRs,+and the one meant for applications, PCR 23, can be reset. A PCR also+accepts an extend from any process that can talk to the TPM, so it would+record events shirudo never made.++We use an NV extend index instead, the construction systemd uses for its+NvPCRs. It is a slot in the TPM's non-volatile memory that behaves like a+PCR: a write replaces its value with SHA-256 over the old value followed+by the event, and the value clears at every TPM reset. Its default handle+is ``0x01818E00``.++Why per boot+------------++BPF programs do not survive a reboot. At every boot, ``init`` loads the+archived upatches again and starts the register from zero, so the register+describes this boot's kernel and nothing older.++A per-boot register has a second benefit. Its value is a function of four+inputs: the trusted certificates, the upatch set restored at boot, the+upatch tree's projection root, and the events since boot. The operator+computes it with ``shirudo attest predict`` from files it already has, and+needs no history from the target.++Who can write it+----------------++A register is only as good as its writers. If any process could extend+it, root could record a load that never happened, and a correct value+would prove nothing.++The index's write policy requires a signature from a writer key for every+extend. ``init`` creates that key inside the TPM at boot, and the private+part never leaves the TPM. Each signature covers one exact extend command,+so it cannot be reused for another event. The first write of a boot is+possible only while PCRs 9 and 11 still hold the values ``init`` read when+it computed the policy. In production, ``init`` binds the register from+the initrd, before systemd moves PCR 11 on leaving it.++The writer key is not a secret, because any process can ask the TPM to+sign with it. What stops root is a BPF LSM program on the kernel's+``tpm_command`` hook: it refuses an ``NV_Extend`` of shirudo's index to+every task without runtime authority. That hook comes from a kernel patch+shirudo carries (:doc:`/internals/kernel-patches`).++Right after binding, ``init`` extends PCR 9 with an anchor, the SHA-256 of+``nvpcr-init:shirudo:0x1818e00:<name>`` for the default index, where+``<name>`` is the index's TPM name. The anchor ties the index to the measured boot, and it moves PCR+9 away from the value the first-write branch needs, so that branch cannot+be satisfied again until the next TPM reset.++What gets recorded+------------------++Each event is SHA-256 over a domain tag followed by the event's fields.+The tags keep an event of one kind from being read as another. Table 1+lists the events.++.. list-table:: Table 1. Register events+ :header-rows: 1+ :widths: 18 42 40++ * - Event+ - When+ - Covers+ * - ``init``+ - Once per boot, when ``init`` binds the register+ - The trusted certificates, the restored upatch set and the tree's+ projection root+ * - upatch load+ - After a load is attached, pinned and archived+ - The payload digest and the upatch name+ * - upatch unload+ - Before an unload removes the pins+ - The payload digest and the upatch name+ * - tree operation+ - After ``bpm tree sync`` applied an operation+ - The operation's sequence number and digest+ * - key revocation+ - When ``shirudo image update`` activates a config that revokes an+ enrolled key, followed by an unload event for each loaded upatch+ that key signed+ - The revoked certificate's digest++A revocation applied at boot is not an event of its own. The ``init``+event covers the certificates that remain trusted.++Boot restore adds exactly one event, the ``init`` event, however many+upatches it restores, and a second run of ``init`` in the same boot adds+none. A state-changing command refuses with ``tampered`` when the register+is not the one ``init`` bound, or when it differs from an+``--expect-chain`` value the caller passed.++A load is measured after it is attached and archived, and undone when+the extend fails. A load process stopped between the attach and the extend+leaves the upatch attached without an event until the next boot, whose+``init`` event covers the archive. An unload is measured before the pins+go, so an interrupted unload leaves a register that records more than+happened. :doc:`/reference/formats/eventlog` lists the fields of each+event.++Eventlog+--------++The register holds one digest. The eventlog,+``/var/lib/shirudo/eventlog``, explains it: one JSON line per extend, with+the event digest, its type, the boot ID and the fields the digest covers.+shirudo appends to it and never rewrites it, it keeps the records of every+boot, and the seal protects it like the rest of ``/var/lib/shirudo``. In+the initrd, ``init`` writes its record to ``/run/shirudo/eventlog.pending``,+and the root file system's run adopts it.++The eventlog is not trusted on its own. A verifier folds this boot's+records from zero and compares the result with the register the TPM+certified. A record changed afterwards either breaks that replay or+carries a digest its own fields do not produce, and verification fails in+both cases.++Register and log advance together. A load or unload that would push the+eventlog past the ``eventlog.max_bytes`` setting refuses with+``eventlog_full`` before it changes anything.++Config image activations are measured separately, into a static PCR that+the runtime image's bootstrap settings select. :doc:`/internals/config-images`+explains that measurement.++Attestation+-----------++To read the register without trusting the target, the operator chooses a+fresh nonce and runs ``shirudo attest --nonce=<hex>`` on the target. The+TPM produces two signed statements: a quote over a set of PCRs, by default+0 to 7, 9 and 11 to 15, and a certification of the register's name and+value. It signs both with its attestation key, a restricted signing key+that it derives from its endorsement seed with a fixed template, so the+same TPM always yields the same key. The command adds this boot's+eventlog records and the TPM's endorsement key, and writes the evidence+document.++The operator records the attestation key's name once, when it enrolls the+target. Credential activation, ``shirudo attest challenge`` on the+operator host and ``shirudo attest --challenge`` on the target, shows that+the key sits in the same TPM as the endorsement key. With ``--ek-ca``, the+endorsement certificate's chain ties that TPM to its manufacturer.++``shirudo attest verify`` then checks, on the operator host and without a+TPM:++- that the evidence answers the operator's nonce;+- the signatures, and that the attestation key is the pinned one;+- that the certified register has the name a register bound under+ shirudo's policy must have, given the PCR values recorded at binding;+- that this boot's records replay to the certified value, and that each+ digest follows from its record's fields;+- that PCR 9 carries the anchor;+- with the certificates and artifacts, that the ``init`` event covers+ them, and with an expected value, that the register equals it.++:doc:`/operate/attest` shows the procedure.++What attestation proves+~~~~~~~~~~~~~~~~~~~~~~~++With a pinned attestation key, an endorsement key the operator trusts, a+fresh nonce and an expected state, a passing verification shows this: the+TPM, after the nonce was chosen, held a register that ``init`` bound under+shirudo's policy during this boot, whose records explain its value, and+whose value is the one the operator's own certificates and artifacts+produce. Only tasks with runtime authority can extend the register, and+shirudo extends it on every change, so the register describes the BPF+state that shirudo's commands established since boot.++What attestation does not prove+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++- It does not show that an upatch is correct, only which upatches were+ loaded.+- It covers what shirudo measured. A compromised kernel, or code running+ in a task with runtime authority, can change BPF state or extend the+ register without the events meaning what they say. The kernel and+ shirudo are trusted.+- ``shirudo attest verify`` passes weaker checks than the ones above when+ the operator omits options. Without ``--ak-name`` it only warns that the+ signer is not pinned. Without ``--cert`` or ``--expect-chain`` it checks+ no expected state, and ``verdict: ok`` then means that the evidence is+ consistent with itself. ``--allow-runtime-events`` accepts any events+ after boot that replay. ``--require-initrd`` reads the target's own+ record, and pinning PCR 11 with ``--expect-bind-pcr`` is what shows that+ the binding happened in the initrd. The :doc:`/security/threat-model`+ lists these among the threats to resolve.+- It says nothing about earlier boots, because the register clears at+ every TPM reset.+- The evidence is signed with ECDSA on P-256, a classical algorithm,+ because TPMs implement no post-quantum signature. The artifacts it+ describes are signed with ML-DSA-87.+- ``shirudo status`` and the telemetry a target exports are not evidence.+ Both are the target's own account, read through the target's own+ software.++Root with the TPM's owner authorization, which is empty on many TPMs, can+undefine the index. From then on every extend fails with ``tpm_error`` or+``tampered``, and verification fails. This denies service, but it cannot+produce a register that verification accepts.++Related+-------++- :doc:`/internals/measurement-register` for the policy, the binding and+ the evidence format.+- :doc:`/operate/attest` for enrolling and verifying targets.+- :doc:`/security/threat-model` for the residual risks of the+ measurement.+- :doc:`/concepts/background/boot` for PCRs 9 and 11 in a measured boot.diff --git a/Documentation/concepts/operator-and-target.rst b/Documentation/concepts/operator-and-target.rstnew file mode 100644index 00000000..3db367b5--- /dev/null+++ b/Documentation/concepts/operator-and-target.rst@@ -0,0 +1,224 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++Operator and target+===================++Every shirudo deployment has two roles. The operator decides which BPF+code a target may run, and the target enforces that decision. One binary serves both, and+what is on a machine decides its role: a machine with the private signing+key acts as an operator, and a machine whose kernel enrolled shirudo's+certificates and attached its enforcement acts as a target. ``shirudo+status`` prints the roles it detects. A development host can hold both.++Why the roles are separate+--------------------------++The main adversary on a target is root without the signing key: a+compromised administrator account, a container escape, an implant. Root can+read any file, so any key stored on a target is root's key. If the target+held the signing key, root could sign its own BPF, and the kernel's+signature check would admit it. We therefore keep the key on a separate+operator host and give targets only public certificates.++The obvious way to connect the two is a management service that pushes+signed code to every target. That service needs a listener on each target,+credentials to reach it, and an inventory of the fleet, and each of those is+something to attack and something to trust. The design has no such+service. The operator publishes to an OCI registry, and each target pulls+and verifies on its own.++Operator+--------++The operator host holds the private signing key, ``signing_key.pem``, and+its certificate, ``cert.der``. ``shirudo genkey`` creates both, with an+ML-DSA-87 key, in the keys directory: ``--keys-dir``, else+``SHIRUDO_KEYS_DIR``, else ``/var/lib/shirudo/keys``. The operator signs+upatches and unload directives, package indexes and tree publications,+config image roots and vouches for further keys, all with ML-DSA-87.++The operator also verifies. ``shirudo attest verify``, ``shirudo attest+predict`` and ``shirudo attest challenge`` work offline on the operator+host, from files. The operator never opens a TPM and never touches a+kernel keyring. :doc:`/operate/keys` covers the custody of the key.++shirudo-build helper+~~~~~~~~~~~~~~~~~~~~++The code that signs artifacts is not in the core ``shirudo`` binary.+Every operator command except ``genkey`` and the offline ``attest``+commands executes a separate helper, ``shirudo-build``: ``build``, ``bpm+build``, ``bpm push``, ``bpm tree append``, ``bpm config update``, ``image+build``, ``image verify`` and ``keys vouch``. The helper links the+signer, runs clang to compile BPF and runs ``veritysetup`` to build and+check images. The core binary finds it through ``SHIRUDO_BUILD``, then+the installed path under ``libexec``, then ``PATH``.++The operator package installs the helper and the target package does not.+On a target the operator commands fail with exit status 127, and neither a+signer nor a compiler driver is code that root could reach there.++Stateless operator+~~~~~~~~~~~~~~~~~~++The operator writes only the key pair and the files the caller names:+artifacts, packages, images, challenges and reports. It keeps no cache, no+inventory of targets and no record of what it published.++Everything a check needs comes from the caller. To verify a target, the+operator names the certificates, the artifacts that should be installed+and, when events happened after boot, the expected register value, which+``shirudo attest predict`` computes from the same inputs. The registry+holds what was published, and each target's TPM holds what was installed.+An operator host can therefore be rebuilt from the key and the artifacts,+and every expectation a verification applies is on its command line rather+than in a local file.++Target+------++A target is a Linux machine with a TPM 2.0 that runs the core binary from+an authenticated image, enforces signatures in its kernel and keeps a+measurement of its BPF state. It never holds the private signing key.+Table 1 lists what it does hold.++.. list-table:: Table 1. State on a target+ :header-rows: 1+ :widths: 40 30 30++ * - What+ - Where+ - Protected by+ * - The ``shirudo`` executable, the initial BPF certificate, the config+ verification certificate and the bootstrap settings+ - Runtime image, mounted at ``/run/shirudo/runtime``+ - dm-verity, with the root hash taken from the initrd in the UKI+ * - Repositories and their certificates, the tree subscription, node+ labels, vouched and revoked certificates, export settings+ - Config image, mounted at ``/run/shirudo/config``+ - dm-verity, with a signed root hash+ * - The trusted certificates+ - The kernel's ``.bpf`` keyring+ - Sealed by ``init``, and ``lsm/key_permission``+ * - Enforcement links, the identity map, the tamper counters, upatch+ links and maps+ - The private bpffs at ``/run/shirudo/bpffs``+ - BPF LSM hooks on unlink, rename, mount and descriptor access+ * - Archived upatches, the eventlog, package and tree state, cached+ images, the config activation journal+ - ``/var/lib/shirudo``+ - Seal labels+ * - The measurement register+ - An NV index in the TPM+ - The index's write policy and ``lsm/tpm_command``++Runtime and config images+~~~~~~~~~~~~~~~~~~~~~~~~~++Two dm-verity images carry what root must not be able to change. The+kernel checks every block it reads from them against a root hash, so a+changed byte fails the read (:doc:`/concepts/background/dm-verity`).++The runtime image holds the executable and what it must trust before+anything else: the initial BPF certificate, the certificate that verifies+config images, and the bootstrap settings that name the config image and+its measurement PCR. The UKI's initrd carries the runtime image's root+hash, so the measured boot covers it.++The config image holds what an operator changes during operation. Its+root hash is signed, and the kernel checks the signature against the+``.dm-verity`` keyring, into which ``init`` enrolls the runtime image's+config certificate before sealing it. ``shirudo image update`` activates a+new config image without a reboot and measures it into a separate PCR.+The kernel also accepts a config signed by a key in its built-in trusted+keyring and, depending on its configuration, in the secondary or platform+keyring; the :doc:`/security/threat-model` lists this among the threats to+resolve.++Neither image replaces the host's root file system. Both are read-only,+and the config image is mounted ``noexec``. :doc:`/internals/config-images`+describes their layout, activation and measurement.++Runtime authority and task marks+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Root can run any program, so the enforcement programs cannot recognize+shirudo by its path, its name or its user. We tie authority to provenance+instead. A task gains the task mark only through a successful exec of a+file on the authenticated runtime image: ``bprm_check_security`` stages+the decision and ``bprm_committed_creds`` commits it once the exec has+succeeded. A forked child inherits its parent's mark, a successful exec of+any other file clears it, and a failed exec leaves it unchanged. The exec+of a runtime file is refused when the task is being traced or runs under+seccomp, so neither a debugger nor a filter installed beforehand controls+the new process.++Runtime authority is what the mark grants. The BPF LSM programs require+it for the ``bpf()`` commands that create, update or freeze maps, run+programs, attach links and pin objects, and for every map or link+descriptor, whether taken by pin, by ID or by opening a pin in the private+bpffs. They require it to change pins, to write, rename or relabel sealed+state under ``/var/lib/shirudo``, to change the keys in the ``.bpf`` and+``.dm-verity`` keyrings, and to extend shirudo's register in the TPM.+Other tasks cannot trace a marked task or open a perf event on it.++A program load from userspace needs a verified signature in addition,+whatever the caller's mark. Runtime authority lets shirudo create, attach+and pin what a signed loader produced. It never lets any process load code+the operator did not sign.++The mark authorizes a process, not a person. Root can still run the+runtime binary, and that process acts with authority within what its+commands do: ``shirudo upatch map`` run by root reads upatch maps, and+without ``--peek`` it drains a serializer-backed map. Every executable on+the runtime image gets the same authority, so the image must hold only+what is meant to have it, and no shells, interpreters or debuggers.+:doc:`/internals/seal` explains the marks and labels in detail.++Agentless target+~~~~~~~~~~~~~~~~++A target runs no daemon and listens on no socket. Every operation is a+one-shot command, started by root or by a systemd unit, that does its work+and exits: ``init`` at boot from the initrd and again from the root file+system, package and tree updates every minute, and map export and status+keepalives every five seconds.+:doc:`/reference/systemd-units` lists the units and timers.++What must outlive a command is pinned in the private bpffs, and what must+outlive the boot is archived under ``/var/lib/shirudo`` and restored by+``init``. We accept the cost of this design, which is latency: a target+learns of a new package at its next timer run, and nothing on it reacts+between runs. In return there is no long-running process for root to+attack, no socket for the network to reach, and less code in the target's+trusted computing base.++Limits+------++The separation protects the key only while the operator host is+trustworthy. An adversary who holds the signing key can sign BPF that+every target accepts, and the design treats that adversary as the+operator.++A registry cannot forge what the operator signed, but it can withhold new+publications or serve older signed ones. A target accepts any upatch whose+signature verifies against its trusted set, including an old one.++Signers are added only at boot. A live config activation can revoke a+key, but a new signer enters the ``.bpf`` keyring only when ``init``+enrolls the trusted set. :doc:`/operate/keys` describes what can change+when.++Related+-------++- :doc:`/start/how-it-works` for the path of one upatch between the roles.+- :doc:`/internals/architecture` for the components and their code.+- :doc:`/security/security-model` for the trust boundaries.+- :doc:`/reference/cli/index` for the commands of each role.diff --git a/Documentation/concepts/upatches-and-packages.rst b/Documentation/concepts/upatches-and-packages.rstnew file mode 100644index 00000000..f8b712f6--- /dev/null+++ b/Documentation/concepts/upatches-and-packages.rst@@ -0,0 +1,252 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++upatches, directives and packages+=================================++An operator ships BPF code to targets as a small set of objects. The+upatch is the unit the target loads, and its unload directive is the unit+that removes it. A package bundles related upatches into one versioned+file, a repository's signed index lists the packages it serves, and the+upatch tree says which target applies which upatch, in which order. This+page explains what each object is, who signs it, what the target checks+before it acts on it, and how the objects relate. Table 1 at the end+summarizes them.++upatches+--------++An upatch is one BPF object, built and signed as a unit: one or more+programs, their maps, and the metadata that says where each program+attaches. The target loads, pins, archives and measures it as a whole.++Every upatch has a name, by default the base name of its source file. A+name consists of letters, digits, ``.``, ``_`` and ``-``, does not start+with a dot, and has at most 255 characters. It names the pin directory+under ``/run/shirudo/bpffs/upatches/``, the archived copy+``/var/lib/shirudo/upatches/<name>.upatch`` that ``init`` restores at boot,+and the events in the measurement register.++Load artifacts+~~~~~~~~~~~~~~++A load artifact is the ``.upatch`` file that installs an upatch. It holds+a fixed header, the instructions of a signed loader, the loader's data,+and a CMS signature over the instructions followed by the data. The data+carries what the loader installs: the payload programs and the map+definitions. :doc:`/concepts/background/bpf-signing` explains why the+signature covers a loader and not the BPF object itself.++The data also carries the sections the target reads for itself: ``NAME``+with the upatch's name, ``UPGM`` with the attach metadata and, when the+programs declare decoders, ``DCDB`` with their Lua sources. Because these+sections sit inside the signed data, the kernel's signature check covers+them as well. A section outside the signed data could be changed on the+way without the signature noticing.++The header repeats the name and holds the payload digest: SHA-256 over the+loader instructions followed by the data. The target recomputes the digest+and compares the header's name with the signed one, and refuses an+artifact on any difference. The payload digest is the upatch's identity+from then on. shirudo records it on the pin directory as the+``security.bpf.shirudo.payload`` extended attribute, measures it with the+name into the register, and an unload directive must name it.+:doc:`/reference/formats/upatch-format` gives the byte layout.++Signed attach metadata+~~~~~~~~~~~~~~~~~~~~~~++The signature covers the payload programs' instructions, but instructions+do not always say where a program runs. For ``fentry``, ``fexit``,+``fmod_ret``, ``lsm`` and ``tp_btf`` programs the attach target is part of+the loaded program. For a kprobe, a uprobe, a ``cgroup_skb`` or a+``netfilter`` program, the site is chosen when shirudo creates the link:+the kernel symbol and offset, the binary and its file offsets, the cgroup+or the network namespace. A site taken from an unsigned file, or from the+caller, would let root run the operator's signed code where the operator+never meant it to run.++The attach metadata therefore travels as a signed section. Each program+entry carries a role, an attach kind and, for kprobes, the symbol and+offset. Uprobe entries add the target binary's path, its GNU build ID and+the probe offsets. After attaching, shirudo compares the link the kernel+reports with the metadata and refuses with ``attach_scope_mismatch`` when+they differ. :doc:`/upatches/attach-kinds` lists the kinds and the check+for each.++The role says what shirudo does with a program. An attach program is+attached and pinned. A serializer, named ``shirudo_serialize__<map>``, is+pinned and run by ``shirudo upatch map`` to read one of the upatch's maps.+A test-run program is run once at load, after the attachments, and a+negative return fails the load. :doc:`/upatches/maps-arenas-serializers`+covers serializers.++Unload directives+~~~~~~~~~~~~~~~~~++An unload directive is the signed instruction to remove one upatch. It+uses the same container with the unload flag set. Its loader comes from+shirudo's fixed unload template, and its signed sections are ``NAME``, the+upatch to remove, and ``UNLD``, the payload digest that upatch must have.+The operator builds it with ``shirudo build --unload``, giving the name+and the payload digest of the upatch to remove.++A plain ``unload <name>`` command would not do, because root can run+shirudo's commands on a target. Removing a mitigation must take the same+key as installing one. ``shirudo upatch unload`` therefore loads the+directive's loader so that the kernel checks its signature, and never runs+it. shirudo then compares the signed digest with the attribute on the pin+directory. Equal digests let the unload go ahead, different ones refuse+with ``payload_mismatch``, and a missing pin is reported as+``already_unloaded``. The digest ties a directive to one build of the+upatch, so a directive made for an old version does not remove a newer+one with the same name.++The detach itself happens in shirudo's userspace after the check, because+a loader running in the kernel cannot detach a link or remove a pin. The+:doc:`/security/threat-model` records what that leaves open.++Packages+--------++A package groups upatches that belong together into one versioned file.+Its definition is a Beefile, a file in a subset of TOML in the package+directory. The Beefile names the package and lists its upatch sources,+optional generators for read-only data, extra files to ship and, per+upatch, the selector it gets when published to an upatch tree.+:doc:`/upatches/beefile` describes every key.++``shirudo bpm build`` builds and signs every upatch the Beefile lists,+together with its unload directive, and writes ``<name>-<version>.bee``.+The package is a gzip-compressed tar archive that holds the Beefile, the+artifacts and directives under ``upatches/``, the package's ``README.md``+when it has one, the signing certificate ``cert.der``, a+``build-environment.json`` and the extra files.++A package carries no signature of its own. A repository's signed index+lists its digest, and every upatch inside carries its own signature, which+the kernel checks at load. A package installed from a direct ``oci://``+reference bypasses the index, and then only the upatch signatures protect+it.++Repositories and signed indexes+-------------------------------++A repository is an OCI registry that a target knows by name, together+with the certificate that signs its index. On a target, repository+definitions and their certificates come from the config image, and local+changes to them are refused. :doc:`/concepts/background/oci` explains the+registry protocol.++``shirudo bpm push`` uploads a package as an OCI artifact. Given the+signing key, it also adds the package to the registry's index at+``shirudo/bpm-index:stable``: a JSON document that lists each package's+name, version, manifest digest and package digest, with a detached CMS+signature in a second layer. ``push`` refuses to list a version again+with different content, so a version published through the index does not+change. A push without the signing key uploads the package without+touching the index.++On the target, ``shirudo bpm repo update`` fetches the index, verifies the+signature against the repository's certificate and keeps the verified+copy in sealed state. ``shirudo bpm install`` and ``shirudo bpm upgrade``+choose versions from that copy, and check the manifest and package digests+they download against it before unpacking. ``upgrade`` removes the+installed version's upatches through their directives, loads the new+version's upatches, and restores the old set when a load fails.+:doc:`/operate/deliver-packages` shows the commands.++upatch tree+-----------++An index says which versions exist. It does not say which target should+run what, or in which order. The upatch tree does.++The tree is an append-only, ordered list of operations. Each operation+adds or deletes one upatch and carries a selector over the target's+architecture, kernel release prefix, kernel build ID, kernel configuration+values and node labels. ``shirudo bpm tree append`` pushes each upatch as+an OCI manifest of its own and publishes the next generation of the list,+the tree publication, as a JSON document with a detached CMS signature.+Each generation names the one it replaces.++A target subscribes to a tree through its config image. ``shirudo bpm+tree sync`` verifies the publication against the runtime image's+certificate, evaluates each new operation's selector on the target, and+applies the matching operations in sequence order. Each applied operation+loads or unloads the upatch and is then measured as a tree operation+event. An operation whose selector does not match is passed over for good:+the target's position moves beyond it, and a later kernel or label change+does not bring it back.++The target keeps a projection root, a hash chain over the operations it+applied, and the next boot's init event includes it. The register value+an operator predicts therefore covers the tree as well as the archived+upatches. :doc:`/upatches/publishing` shows how to publish to a tree, and+:doc:`/reference/formats/bpm-formats` gives the document formats.++How the objects relate+----------------------++Each object carries its own protection, and the target checks it before+acting on it. Table 1 lists what the operator signs, where the target+checks it, and what the measurement register records.++.. list-table:: Table 1. Shipped objects and their checks+ :header-rows: 1+ :widths: 18 24 34 24++ * - Object+ - Signed by the operator as+ - Checked on the target by+ - Recorded in the register as+ * - Load artifact+ - CMS signature over the loader instructions and data+ - The kernel at ``BPF_PROG_LOAD``, against the ``.bpf`` keyring+ - An ``upatch_load`` event+ * - Unload directive+ - The same+ - The kernel at ``BPF_PROG_LOAD``, then the payload digest against+ the pin's attribute+ - An ``upatch_unload`` event+ * - Package+ - Not signed as a whole+ - Its digests against the signed index, then each upatch as above+ - The events of its upatches+ * - Signed index+ - Detached CMS signature+ - ``bpm repo update``, against the repository certificate from the+ config image+ - Not recorded+ * - Tree publication+ - Detached CMS signature+ - ``bpm tree sync``, against the runtime image's certificate+ - A ``tree_op`` event per applied operation, after the upatch's own+ event++Limits+------++A signature proves who built an upatch and that nobody changed it. It+says nothing about whether the upatch is correct. The kernel's verifier+checks memory safety, and the rest is the author's responsibility.++A signature does not expire. A target accepts any artifact that verifies+against its trusted set, including an older build that a registry serves+again, and nothing enforces a minimum version.++A directive is bound to a name and a payload digest, not to the key that+signed the load. Any key in the trusted set can sign a directive that+removes any upatch.++Related+-------++- :doc:`/start/how-it-works` for the path of one upatch.+- :doc:`/upatches/concepts` for authoring upatches.+- :doc:`/concepts/measurement-register` for the events.+- :doc:`/internals/signed-loader` for the load in detail.diff --git a/Documentation/conf.py b/Documentation/conf.pynew file mode 100644index 00000000..477d62a4--- /dev/null+++ b/Documentation/conf.py@@ -0,0 +1,38 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# Sphinx configuration for the shirudo documentation.++import os+import sys++sys.path.insert(0, os.path.join(os.path.dirname(__file__), "_ext"))++project = "shirudo"+author = "Authors of shirudo"+copyright = "2026, Authors of shirudo"++extensions = ["myst_parser", "shirudo_docs"]+source_suffix = {".rst": "restructuredtext"}+root_doc = "index"+exclude_patterns = ["output", "_ext", "_themes", "logos"]+language = "en"+nitpicky = True+highlight_language = "none"++html_theme = "shirudo"+html_theme_path = ["_themes"]+html_title = "shirudo documentation"+html_static_path = ["logos"]+html_favicon = "_themes/shirudo/favicon.svg"+html_sidebars = {"**": []}+html_copy_source = False+html_show_sourcelink = False+html_show_sphinx = False+html_domain_indices = False+html_use_index = False+html_permalinks_icon = "#"+html_context = {+ "repository": "https://github.com/shirudo-dev/shirudo",+ "branch": "main",+}diff --git a/Documentation/config-images.rst b/Documentation/config-images.rstdeleted file mode 100644index 80506b49..00000000--- a/Documentation/config-images.rst+++ /dev/null@@ -1,540 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--Executable and configuration images-===================================--Shirudo puts its executable and configuration on separate read-only dm-verity-filesystems. The host root filesystem stays in place. Writable Shirudo state-keeps its xattr protection. BPF upatches still use signed loaders verified by-the kernel BPF keyring, including when config itself has a valid signature.-There is one target policy; authenticated bootstrap settings are required.--The executable image is fixed for the boot. Configuration updates install-another signed immutable image while the system runs. They do not write-through dm-verity or modify the active filesystem in place. Each update-transfers the complete image and its verification data. Reusing blocks and-rollback prevention are deferred.---1) Filesystems and trust---------------------------The target uses these mounts and directories::-- / host root filesystem- /run/shirudo/runtime executable image: ro,nodev,nosuid- /run/shirudo/config config image: ro,nodev,nosuid,noexec- /run/shirudo/bpffs protected BPF objects- /var/lib/shirudo protected writable state--The runtime image contains the fully static target binary, bootstrap-``shirudo.conf``, initial BPF trust anchors and the-config verification certificate. Every executable on this image has the-same eligibility for Shirudo authority. Do not include shells, debuggers-or general-purpose interpreters unless that authority is intended.--The UKI authenticates the runtime image's expected dm-verity root hash.-After mounting that image, Shirudo reads the config verification-certificate from it. Config signatures cover exactly the 64 lowercase-ASCII hex bytes of the dm-verity root hash, without a newline. The kernel-verifies that signature using its dm-verity trust path, including built-in-trusted keys. The private signing key remains on the operator. A config cannot replace this verification-certificate, initial BPF trust anchors, executable authority or TPM-settings. Rotating the config verification certificate requires a new-runtime image and UKI followed by reboot.--The static target runs directly from the runtime image. It needs no ELF-interpreter or shared libraries at startup. Additional dynamic executables-supplied by the operator bring their interpreter and libraries into the-image. Executable mappings from outside the image are denied.--The authenticated bootstrap configuration selects the initial cached config-prefix, the verification certificate and a reserved static TPM PCR. For-example, a deployment that has reserved PCR 14 uses::-- config.image = /var/lib/shirudo/images/initial- config.verification_key = /run/shirudo/runtime/etc/shirudo/config-cert.der- config.pcr = 14--PCR 14 is an example, not a universal allocation. The deployment must ensure-that its firmware, bootloader and other OS software do not use the selected-PCR. Image mode accepts static SHA-256 PCRs 0 through 15 except PCRs 9-and 11, which the existing upatch register uses. Unsupported PCR reads fail-initialization. Resettable PCRs are refused. A config update or environment-override cannot change the selection.--The UKI's bootstrap configuration names the runtime cache prefix and its-expected 64-character root hash::-- runtime.image = /var/lib/shirudo/images/runtime- runtime.root_hash = <expected SHA-256 root hash>--An image pathname is a location, not an authentication mechanism. Boot-checks the expected runtime hash; config activation checks the signature-and the actual kernel mapping.---2) What configuration contains---------------------------------A configuration source directory contains the existing updateable inputs-under their image-relative paths:--* ``etc/shirudo/shirudo.conf``: eventlog limits and map-export settings.-* ``etc/shirudo/bpm/registries.d/`` and ``etc/shirudo/bpm/keys/``:- repository definitions and verification certificates.-* ``etc/shirudo/bpm/upatch-tree.conf``: the tree subscription.-* ``etc/shirudo/node.labels``: labels used by tree selectors.-* ``keys/trusted/``: additional BPF certificates and vouch signatures.-* ``keys/revoked/``: revocation records.--Repository ``key_file`` paths are resolved under the held config-image root.-Use an image-relative path such as ``etc/shirudo/bpm/keys/repo.der`` or the-conventional ``/etc/shirudo/bpm/keys/repo.der`` spelling; both name the-certificate inside the image. Other absolute paths and traversal are refused.-Tree publications are verified against the runtime image's initial BPF-certificate. Repository indexes use their configured repository certificate.--The initial BPF certificate, TPM configuration and-``tls.classical_hosts`` policy belong in the runtime image's-``etc/shirudo/shirudo.conf``. For example::-- tls.classical_hosts = ghcr.io,quay.io--The target reads this policy from the immutable runtime image; operator-commands read it from the root-managed host config. The updateable config-image cannot set or change ``tls.classical_hosts``. More generally, attempts-to override settings owned by the runtime bootstrap are rejected. Shirudo-rejects these and other invalid config images before extending the config-PCR.-Config images must not contain symbolic links or special files.--Writable state still includes downloaded upatch archives, repository-indexes, package caches, installed state, pending tree operations, locks,-telemetry output and the eventlog. Image mode adds complete-image caches-under ``/var/lib/shirudo/images`` and the activation journal and config-measurement log under ``/var/lib/shirudo/config-update``.--No persistent certificate-enrollment catalog is added. Complete revocation-coverage across reissued certificates with the same public key has not been-established by this implementation; do not infer it from a matching fingerprint-alone.--The existing ``security.bpf.shirudo`` seal protects writable state. The-runtime and config filesystems need no seal xattr writes. bpffs keeps its-separate object and payload protections.---3) Build and verify images-----------------------------Run image generation on the operator. The Bash scripts require GNU coreutils,-``mkfs.ext4`` from-``e2fsprogs``, the standard ``veritysetup`` executable (``cryptsetup-bin``-on Debian/Ubuntu, ``cryptsetup`` on Fedora/RHEL) and the operator-only-build helper::-- tools/gen-image/shirudo-gen-image --source config-root --output config \- --keys-dir operator-keys \- --builder tools/shirudo-build/shirudo-build--The source directory becomes the config image root. The four outputs are::-- config.img ext4 filesystem- config.verity standard verity superblock followed by the hash tree- config.roothash 64 lowercase ASCII hex bytes, without a newline- config.p7s detached ML-DSA-87 CMS signature--All four files share a prefix. Existing output files are refused. The-operator can also sign an already prepared 4096-byte-aligned ext4 image::-- shirudo image build filesystem.img -o config --keys-dir operator-keys--Generate the runtime image with its static executable and public assets::-- tools/gen-image/shirudo-gen-runtime --binary ./shirudo-target \- --bootstrap-conf bootstrap.conf --cert initial-bpf-cert.der \- --config-cert config-signing-cert.der --output runtime \- --keys-dir operator-keys \- --builder tools/shirudo-build/shirudo-build--Use trusted native input binaries. Dynamic executable inspection runs-their ELF interpreter on the operator. Never put private keys in either image.--The Bash builder runs standard ``veritysetup format`` with format version 1,-SHA-256, 4096-byte data and hash blocks and a 32-byte salt. The standard-superblock starts at offset zero and the hash tree starts at block one.-The C helper signs the root's exact ASCII representation. ``--kind config|runtime``-is a packaging hint, not a signed format field or an authority decision.-Shirudo has no custom hash-tree builder.-The scripts share argument and output checks in ``common.sh`` and keep the-systemd service template in a separate file. ``make install-operator`` installs-them under ``libexec/shirudo/gen-image/``. Generation happens in a temporary-directory beside the requested output. The builder verifies the image before-publishing any files and refuses to replace existing output files.---Verify a staged bundle offline on the operator without activating it::-- shirudo image verify config --cert config-signing-cert.der--This command dispatches to ``shirudo-build``. The helper authenticates the-root signature with the supplied certificate, validates the standard-superblock and exact file sizes, then runs ``veritysetup verify``. This-operator check does not select the target kernel's trust policy.-It requires the operator helper and ``veritysetup``, but no root, TPM or-active device-mapper mapping. It is not a target-side health command.--Target operations use linked code and kernel APIs. After authenticating-runtime root from the UKI, or asking the kernel to authenticate the config-root signature, the target creates or validates a strict read-only mapping-and reads the whole data device through the kernel. It validates the-standard superblock and exact backing-file sizes. These checks precede-candidate parsing and PCR extension, including for reused mappings. Integrity failures and incomplete reads refuse preparation.-The target never shells out to ``veritysetup``, ``dmsetup`` or a filesystem-builder and does not implement a userspace hash-tree verifier.---4) Boot and live updates---------------------------Boot follows the systemd initrd flow in the initrd guide. The authenticated-initrd first verifies the runtime and selected config to determine the-boot-enrolled signer set. Image boot requires-``dm_verity.keyring_unsealed=1``: the trusted initrd enrolls the config-verification certificate in the dedicated ``.dm-verity`` keyring and seals-it before handing control to the host. Enrollment and sealing address the-kernel ring through ``KEY_SPEC_DM_VERITY_KEYRING``; there is no search of-``/proc/keys`` or fallback to a user-created keyring. Built-in kernel trust remains part-of config-root verification. The initrd also enrolls and seals the BPF-keyring, attaches the guards, mounts-the runtime under guard protection and completes measured config activation.-The runtime bootstrap settings select the config verification key and PCR.-After switch-root, services and CLI commands execute the static binary at-``/run/shirudo/runtime/usr/bin/shirudo`` directly. The generator prints-that invocation and can write a service override with ``--unit-output``.-The ``shirudo`` commands below denote that configured runtime invocation;-substitute the command and arguments for its final ``init`` when invoking-the generated command directly.--Image mode needs writable ``/var/lib/shirudo`` available during the initrd-run: the image cache and pending activation record must be durable before a-PCR extension. If that directory resides on a separate filesystem, mount-it under the initrd's system root before Shirudo starts. A separate state-filesystem is not required.-The mounts under ``/run`` survive switch-root.--Boot verifies the selected cached config, validates its mapping and-contents, records a BOOT measurement and applies the selected BPF trust-set and archived upatches. Missing or invalid images fail initialization.-The current installed config and the first installed config use the same-signature verification path. Repeating init within the same TPM boot does not append another config-event.--The target's live update command accepts a local complete bundle prefix or-an HTTPS prefix::-- shirudo image update /path/to/config- shirudo image update https://config.example/shirudo/config- shirudo image status--The update sequence is::-- take the operation lock- -> fetch the bundle and authenticate its root and backing files- -> prepare a strict read-only candidate mapping and read every data block- -> mount and validate the candidate contents- -> save and fsync the pending activation record- -> extend the selected PCR- -> save the measurement record- -> finish authorized key changes and mount replacement- -> save completed state--Each operation reads through a held directory FD for the selected config.-The operation lock prevents a command from mixing old and new settings.-Old references can finish, but new commands use the active image. The-runtime image and host root filesystem remain unchanged during config-updates.--Additional BPF signing keys still need valid vouches under the existing-BPF trust rules. The config signature alone cannot authorize BPF code.-Before measuring, Shirudo validates the full vouch graph and every-revocation record. Revocation filenames are canonical lowercase public-key-fingerprints with a ``.der`` suffix; their certificate must match the-fingerprint. Unknown entries, malformed records and unvouched signers are-refused. The selected config must retain at least one unrevoked authorized-BPF signer; an all-revoked set is refused by this implementation.-BPF signing keys are enrolled at boot before the existing reject-all-keyring restriction is installed. Live config activation cannot enroll new-keys into that sealed keyring. A candidate containing a signer absent from-the live keyring is refused before measurement. It is not activated as a-pending enrollment. A new signing key must be supplied through the config-selected for boot and requires reboot and vouch verification; no kernel-keyring changes are included. This requires boot-time provisioning: there-is no live command to queue a new signer for a future boot. An existing-activation record selects its cached bundle prefix ahead of the initial-``config.image`` setting. Changing that setting alone does not override an-existing selection, and deleting the journal is not a supported update-procedure.--The selected trust configuration is covered by the config PCR event.-Omitting a certificate from a replacement image does not-revoke a key already enrolled this boot; include an explicit revocation-record. Vouch verification follows the historical chain rooted in the-runtime image's initial certificate. Revoking a signer for BPF loading does-not invalidate its earlier vouches or remove that immutable chain anchor.--Revocations arrive only through signed config images. The image-mode-target has no local revocation command or writable revocation override.-``keys add``, ``keys revoke`` and ``bpm key add`` refuse local mutations-with guidance for signed config updates or boot-time enrollment. The same-applies to ``bpm config register add``, ``remove`` and ``rm``: put repository-definitions and public certificates in the signed config, then activate it.-Command help and read-only inspection remain available. ``status``,-``config`` and ``keys show`` report the authenticated inputs; ``config``-prints effective settings and does not write them. Upatch load/unload,-package install/upgrade/uninstall, repository refresh, tree sync, map export-and attestation remain target operations under the active image policy.-Operator build, publish and vouch commands remain operator operations.--Signed upatch load and unload checks continue to apply. Signed config-revocations reuse the existing key unlink, measured key-revoke and live-upatch unload operations. Startup removes archives signed by revoked keys-before restoring upatches. There is no separate purge journal or same-boot-purge recovery.---5) Measurements and interrupted activation---------------------------------------------The config event digest binds the event kind and binary root hash::-- SHA256("shirudo-config-root-v1\0" || big_endian_u32(BOOT_or_UPDATE)- || root_hash_32_bytes)--BOOT is 1 and UPDATE is 2. The TPM extends this digest into the reserved-SHA-256 config PCR. Returning to a previously selected root produces an-UPDATE event; requesting the current root is a no-op. Each new boot records-a fresh BOOT event. The config log is separate from the upatch NV register.--The verified bundle and pending selection become durable before extension-or activation. Failures before that point leave the active config usable.-Once pending, any interruption, including an ambiguous TPM response,-requires a manual reboot before Shirudo can resume state changes. The node-keeps running: Shirudo never triggers a reboot. The operator chooses when-to reboot. State-changing operations and config attestation refuse;-there is no ``image recover`` command or same-boot extension retry.--At the next trusted boot, initialization selects and verifies the cached-pending config, records a fresh BOOT event, applies its revocations before-upatch restoration and completes only after startup succeeds. Missing files-or invalid signatures stop initialization. The previous boot's extension-is not replayed, and an older config is not silently selected as fallback.-The pending record retains the selected prefix/root and boot identity;-it does not persist per-effect phases or predicted PCR before/after values.--Direct TPM-command measurement spoofing remains separate work. Genuine-operations are measured and their history is replayed, but a PCR alone-does not prove activation against an attacker able to issue measurement-commands. The separate upatch NV register requires a signed write and blocks-untrusted extension commands to its index. That guard does not cover-config PCR extensions.-No IMA integration is added, and signatures do not prevent rollback.--Attestation includes the config PCR even if ``--pcrs`` omits it. The-``config`` object contains ``schema: 1``, ``pcr``, ``reset_count``,-``restart_count``, ``initial_pcr`` and an ``events`` array. Each event holds-``sequence``, ``kind`` and ``root_hash``. The current boot's history derives-the terminal root and PCR; duplicated terminal fields are not needed.-The operator verifies its intended root with::-- shirudo attest verify --evidence=evidence.json --nonce=<fresh nonce> \- --ak-name=<enrolled AK name> --expect-chain=<expected upatch chain> \- --expect-config-root=<approved config root hash> --expect-config-pcr=14--Both config expectation flags are required to approve a root. The verifier-checks BOOT/UPDATE order, sequence and boot identity, derives each digest-and replays it from ``initial_pcr`` to the PCR covered by the TPM quote.-Without an expected root it reports consistency and explicitly notes that-operator approval was not supplied. Pending state cannot produce healthy-config evidence. This remains subject to the direct-writer limitation.---6) Enforcement and tests---------------------------The binary embeds one BPF object pair: ``bpf/bpf2.c`` and ``bpf/seal.c``.-Initialization always loads both. ``bpf/admission.h`` supplies BPF command,-signature, keyring and bpffs checks. ``bpf/seal.h`` supplies writable-state-xattr checks, label inheritance and ptrace/perf checks. The device and task-helpers live in ``bpf/verity_policy.h``.--The seal label marks a protected writable target. It never grants the caller-write access. Runtime and config files use dm-verity, while writable state-continues to use seal xattrs. Caller authority comes from runtime exec.--Shirudo marks tasks after successful exec from the approved runtime-device, inherits the mark on fork and re-evaluates it on every successful-exec. Exec outside the runtime clears authority. Failed exec preserves-the running image's mark. Changing ``mm->exe_file`` cannot grant authority.-Runtime exec checks for an existing tracer or seccomp filter. The existing-perf allocation check denies targets already marked trusted, but is not-serialized with the exec transition. The separate `perf/exec investigation-<https://github.com/shirudo-dev/shirudo/issues/11>`__ records that source-derived race and the limitation-of an earlier proposed exec-time snapshot check. Neither has a runtime-reproduction in this work.-Do not add a systemd syscall filter to the runtime-invocation: caller-controlled seccomp could otherwise spoof the kernel-enforcement query used to detect hidden bpffs pins.--The LSM observes dm-verity metadata through the existing-``bdev_setintegrity`` hook. Lookup checks the block-device pointer, device-number and disk sequence. The runtime root must match the authenticated-bootstrap value. A config root must match the expected root staged by the-trusted task creating that mapping. An unrelated mapping made by a trusted-task is not a config device.--Expected roots live in task storage. The hook reads the preparing-task's entry and consumes it when the kernel reports the matching root.-Creation clears it on every exit and reports an error if cleanup fails. A-remaining valid entry blocks another preparation until cleared or task exit.-The same helper covers boot activation, temporary download verification and-live config activation. Initial trusted boot validates the key set before-installing the guards, then recreates those mappings under enforcement.-Untrusted tasks cannot modify the expectation map through BPF or a writable-FD.-The free hook attempts to delete the device record,-but upstream dispatch can skip that notification. Device identity checks-and cleanup are distinct concerns.--Image mode requires a kernel without 32-bit compatibility support, as-listed in the `kernel requirements <requirements.rst>`__.-The ``file_ioctl`` and ``file_ioctl_compat`` hooks deny mutating-DM-control commands from untrusted callers, including commands on old or-inherited FDs. The restriction covers all DM devices in image mode, so-ordinary untrusted volume-management tools cannot mutate unrelated DM-mappings either. Read-only control queries remain available, and trusted-image tasks retain control access. Shirudo creates strict mappings, but the-upstream metadata hook does not expose every verification option. Existing-mount hooks reject direct operations on the bpffs, and ``sb_umount``-refuses an unmount that would take the bpffs mount init made with it, by-subtree or by propagation (residual risk 3 in the threat model).-The image mount hooks do not cover every mount attribute change or-unmount of a parent mount above the runtime and config images. Legacy ``mount(MS_MOVE)`` can relocate an image;-the separate `mount-move investigation <https://github.com/shirudo-dev/shirudo/issues/12>`__ records-the VM result and the same source-check gap in the baseline bpffs policy.-A changed pathname does not change device-bound executable authority.-No additional LSM hooks are required.--Process-memory protection remains necessary: dm-verity protects backing-files, not writable mappings, ptrace or process-memory writes. Trusted-processes reject untrusted executable mappings, anonymous executable-memory and transitions that introduce executable pages from writable-memory.--Writable state retains the xattr seal, with image task authority used to-authorize the caller. New inodes receive their parent's label during the-creation transaction when a cached parent mark is present. Shirudo's writers-hold the parent directory open while creating; they apply a fallback label-when needed. Cached marks can be absent after directory-inode eviction, and-link or rename can introduce an existing unlabelled inode. The seal does not-exclude every foreign entry or revoke previously opened writable descriptors-and shared mappings. The `threat model <threat-model.rst>`__ describes these-current limits; the separate `directory-entry investigation-<https://github.com/shirudo-dev/shirudo/issues/13>`__ records the earlier baseline.--The enforcement hooks are present at bpf-next commit-``0867b7bfa9de65674c6e599fa21b762b71011b14``. Direct access to the kernel-``.dm-verity`` keyring additionally requires patch 1/3 of the bpf-next v2-series ``keys: Add well known IDs for fs-verity/dm-verity keys``. The test--kernel build applies the local copy under ``kernel/``.-Shirudo also requires the signed-BPF kernel interfaces listed in-`requirements <requirements.rst>`__.--The operator tests exercise standard superblocks, exact root encoding,-``veritysetup`` formatting and offline verification, signature failures,-durable pending selections, interrupted activation and fresh-boot history.-The libtpms cases use actual PCR commands in addition to injected callbacks.-Host fault injection and the VM interruption check are separate evidence;-neither proves behavior under every hardware failure.---The target tamperproof tests exercise executable authority, fork and exec,-executable mappings, direct and inherited DM controls, mount namespaces,-ptrace, ``/proc/<pid>/mem``, ``process_vm_writev`` and perf observers.-Observer tests do not establish that concurrent perf attachment is excluded.-The target suite runs against an image-backed installation. The final-interruption case leaves pending state and ends the VM run; it does not-initiate a reboot. A skipped required fixture fails the run.---7) Run the target suite--------------------------The standard harness builds and signs fixtures on the operator and deploys-only public artifacts. Run the suite with::-- sudo make -C testing functional--Each family of target tests boots a VM of its own from the same bundle, so-no family sees state another left behind; ``make -C testing-functional/image`` runs the image family alone, and ``make -j`` runs several-side by side.--The harness requires dracut, initrd boot and all seal hooks. It rejects-``TEST_VM_INITRD=0`` and ``TEST_VM_SKIP_SEAL=1``. The only accepted value of-the old ``TEST_VM_MODE`` setting is ``verity``; no selection is needed.-CI uses this same required suite and reports its failures.--The guest boots with ``config-boot-keys``. The runtime fixture includes an-authority probe and an interrupted-activation helper; these test executables-have full authority and must never ship in a deployment runtime.--The suite checks signed upatch load and unload, foreign signature rejection,-TPM replay, uprobes, map and arena serialization, tree updates, OTLP services,-keyring controls, runtime exec authority, executable mappings, device controls,-process observers, hidden bpffs, signed config updates and measured revocation.-After the final interrupted update it checks that changes and attestation-refuse while the node continues running.--Required image fixtures and helpers are failures when absent. A target-test that skips as a whole fails its family. Within a family the tests run-in number order, and for the image family the order matters: the-boot-signer assertions run before the config changes, revocation removes a-signer for the remainder of the boot, and the interruption case runs last-because it leaves the activation pending. Use a fresh test VM and state-for another run.--For an already provisioned disposable image-mode VM, install the complete-public fixture set and cache every config bundle under-``/var/lib/shirudo/images``, then run::-- export SHIRUDO_BIN="$PWD/testing/helper/image-shirudo"- export SHIRUDO_TEST_FIXTURES_DIR=/path/to/public-upatch-fixtures- export SHIRUDO_TEST_KEY_FIXTURES=/path/to/public-image-fixtures- export SHIRUDO_TEST_RESULTS=/root/test-results/verity- sh testing/run-target-tests.sh image--``testing/vm/image-fixtures.sh --keys-dir <operator-keys>---output <new-directory>`` builds the signed config and revocation fixtures;-only its ``public/`` directory belongs on the target. The standard host-bundle also packages the runtime and static test helpers. The-``image-shirudo`` test wrapper executes the runtime binary directly.-Production services use the invocation-emitted by ``shirudo-gen-runtime``.--For built-in kernel trust coverage, the operator may supply-``TEST_VM_BUILTIN_SIGNING_KEY`` and ``TEST_VM_BUILTIN_SIGNING_CERT`` while-building the host bundle. Use the private key corresponding to a certificate-already built into the test kernel. The fixture builder uses that host key-in place and exports only its public certificate and signed image files.-The test checks that this certificate differs from the initrd-enrolled-config certificate, then activates its signed image. Without this input,-that individual case is explicitly skipped; no key or kernel is generated.--The runner saves individual suite logs and config evidence in its results-directory, under the VM result share for a standard run. These commands-describe coverage to execute; validation results and limitations belong in-run does not establish that either complete suite passed.diff --git a/Documentation/coding-style.rst b/Documentation/contribute/coding-style.rstsimilarity index 100%rename from Documentation/coding-style.rstrename to Documentation/contribute/coding-style.rstdiff --git a/Documentation/contributing.rst b/Documentation/contribute/contributing.rstsimilarity index 61%rename from Documentation/contributing.rstrename to Documentation/contribute/contributing.rstindex 638274c7..30bd203f 100644--- a/Documentation/contributing.rst+++ b/Documentation/contribute/contributing.rst@@ -1,66 +1,71 @@-.. SPDX-License-Identifier: BSD-2-Clause-.. Copyright (c) 2026 Authors of shirudo+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo-==============-Contributing-==============+:page-type: How-to+:audience: shirudo contributors++Commits and sign-off+====================shirudo follows the Linux kernel's development conventions for commits:-the coding style in `coding-style <coding-style.rst>`__, a kernel-style commit message,+the coding style in :doc:`coding-style`, a kernel-style commit message,a mandatory ``Signed-off-by:`` line, and the same set of attribution-tags. This page states the parts of that process that apply here; the+tags. This page states the parts of that process that apply here. Thekernel's ``Documentation/process/submitting-patches.rst`` is thereference for anything not covered.Participation in the project is governed by the Code of Conduct in-``CODE_OF_CONDUCT.md`` at the repository root; conduct concerns go to+``CODE_OF_CONDUCT.md`` at the repository root. Conduct concerns go toCommit messages-===============+---------------The kernel's ``submitting-patches.rst`` ("Describe your changes") and-``maintainer-tip.rst`` ("Changelog") set the standard; the rules below+``maintainer-tip.rst`` ("Changelog") set the standard. The rules beloware theirs, applied here.The subject line is ``area: imperative summary`` in at most about 70characters, where ``area`` names the part of the tree being changed(``bpm:``, ``packaging:``, ``docs:``, ``tree:``, ``build:`` and so on).-The body, wrapped at 75 columns, is the permanent record read by-reviewers now and by whoever bisects to the commit years later, so it-is written for them:--* Describe the problem first. Whether the change is a one-line fix or- a new feature, something motivated it; say what, and convince the- reader it is worth fixing. The diff already shows *what* changed;- the message exists to record *why*.-* Describe the user-visible impact: the crash, the refused load, the- wrong report, the invariant that was violated. Quote the actual- error or log line when there is one.-* Then describe what the change does about it, in plain English, so+``check-style.sh`` refuses a subject longer than 75 characters. The+body, wrapped at 75 columns, is the permanent record read by reviewers+now and by whoever bisects to the commit years later, so write it for+them:++- Describe the problem first. Whether the change is a one-line fix or a+ feature, something motivated it. Say what, and convince the reader it+ is worth fixing. The diff already shows what changed. The message+ exists to record why.+- Describe the user-visible impact: the crash, the refused load, the+ wrong report, the invariant that was violated. Quote the actual error+ or log line when there is one.+- Then describe what the change does about it, in plain English, sothe reviewer can check that the code does what was intended. Mentionalternatives that were tried and rejected, and the costs of the onechosen.-* Quantify claims: a performance, size or latency improvement comes- with numbers; a heuristic comes with its trade-off.-* Use the imperative mood ("make X do Y", "refuse Z"), as if giving an+- Quantify claims: a performance, size or latency improvement comes+ with numbers, a heuristic with its trade-off.+- Use the imperative mood ("make X do Y", "refuse Z"), as if giving anorder to the code base. Not "this patch", not "I changed", not "wemodify". Write in abstract terms about the code, not as a story ofwhat the author did.-* Structure it as short paragraphs in the order context, problem,+- Structure it as short paragraphs in the order context, problem,solution. If the explanation is getting long, the commit is probably- doing more than one thing; split it.-* Refer to other commits by at least twelve hash characters plus the+ doing more than one thing. Split it.+- Refer to other commits by at least twelve hash characters plus thesubject in parentheses, so the reference stays readable without arepository at hand.-* Make it self-contained. Links to reports or discussions are welcome+- Make it self-contained. Links to reports or discussions are welcome(``Link:``, ``Closes:``), but the message must make sense withoutfollowing them.-* Short and to the point. Leave out what the diff says, repeat nothing- from the subject, and never use emojis.+- Keep it short and to the point. Leave out what the diff says, repeat+ nothing from the subject, and never use emojis.An example of the form, from the kernel (commit 43a1e3744548 by Linus-Torvalds, ``security/keys: fix missed RCU read section on lookup``)::+Torvalds, ``security/keys: fix missed RCU read section on lookup``,+with the ``Cc:`` lines of its trailer left out)::security/keys: fix missed RCU read section on lookup@@ -81,10 +86,10 @@ Torvalds, ``security/keys: fix missed RCU read section on lookup``)::Three paragraphs: who found what and why it is a real bug, why it wentunnoticed, and which of the possible fixes was chosen and why. Nothing-about which lines moved; the diff shows that.+about which lines moved. The diff shows that.Sign your work-==============+--------------Every commit carries a ``Signed-off-by:`` line, with no exception. Thesign-off certifies the Developer's Certificate of Origin, reproduced@@ -120,36 +125,48 @@ If you can certify that, add::Signed-off-by: Random J Developer <[email protected]>-using a known identity; anonymous or pseudonymous sign-offs are not+using a known identity. Anonymous or pseudonymous sign-offs are notaccepted, and neither is an address nobody answers at: a GitHub noreplyaddress, the address a coding agent writes with, or anything called``[bot]`` is rejected as the author, in a ``Signed-off-by:`` and in a``Co-developed-by:``. ``git commit -s`` and ``git revert -s`` add theline for you.-A commit without a valid sign-off is not merged, and a maintainer who++A commit without a valid sign-off is not merged. A maintainer whoapplies a commit adds their own sign-off after the author's, so thechain of ``Signed-off-by:`` lines records the real route the change-took. The first sign-off is the author's; the last is the person who-submits the commit. ``.github/scripts/check-dco.sh`` verifies that-every commit in a range has a one-line subject, a body that says more-than its tags and its author's sign-off from a real address, and CI-runs it on every pull request as the ``DCO`` check.+took. The first sign-off is the author's. The last is the person who+submits the commit.++``.github/scripts/check-dco.sh`` checks every commit in a range except+merge commits:++- The subject is one line, followed by a blank line.+- The body says more than its tags.+- The commit has a ``Signed-off-by:`` from its author, spelled exactly+ like that and in the form ``Name <address>``.+- No author, sign-off or ``Co-developed-by:`` names an identity that+ contains ``noreply``, ``no-reply`` or ``[bot]``, in any case.++CI runs it on every pull request and every push to ``main``, in the+``DCO`` workflow.Only a person can certify the DCO. Coding agents and other automated-tools must never add a ``Signed-off-by:`` line; the human who reviews+tools must never add a ``Signed-off-by:`` line. The human who reviewsand submits the work signs it off and takes responsibility for it.Tags-====+-----The tags below are used exactly as in the kernel. All of them go in-the trailer block together with the sign-offs, one per line.+The tags below are used exactly as in the kernel. All of them go in the+trailer block together with the sign-offs, one per line.``Co-developed-by:``Attributes co-authorship when several people worked on one commit.Every ``Co-developed-by:`` is immediately followed by the``Signed-off-by:`` of that co-author, and the sign-offs keep the- chronological order of the work; the submitter's sign-off is last::+ chronological order of the work. The submitter's sign-off is+ last::Co-developed-by: First Co-Author <[email protected]>Signed-off-by: First Co-Author <[email protected]>@@ -161,7 +178,7 @@ the trailer block together with the sign-offs, one per line.Fixes: 1234567890ab ("bpm: publish signed indexes from C")- Use it on every bug fix whose origin is known; it is how the fix is+ Use it on every bug fix whose origin is known. It is how the fix istraced back and how release branches decide what to pick up.``Reported-by:``@@ -174,8 +191,8 @@ the trailer block together with the sign-offs, one per line.Credits the person whose idea the change implements.``Tested-by:``- Records that the named person tested the commit successfully in some- environment. Say where when it matters, with a ``# suffix``::+ Records that the named person tested the commit successfully in+ some environment. Say where when it matters, with a ``# suffix``::Tested-by: Alice Example <[email protected]> # arm64, swtpm@@ -190,44 +207,52 @@ the trailer block together with the sign-offs, one per line.Lists people who had the chance to comment.``Reported-by:``, ``Suggested-by:`` and ``Cc:`` may be added when the-person acted in public; every other tag needs that person's explicit-permission. When a later version of a change differs substantially, drop-the ``Tested-by:``, ``Reviewed-by:`` and ``Acked-by:`` tags it had+person acted in public. Every other tag needs that person's explicit+permission. When a later version of a change differs substantially,+drop the ``Tested-by:``, ``Reviewed-by:`` and ``Acked-by:`` tags it hadcollected and say so in the cover text, so a tag never vouches for codeits author has not seen.Before sending-==============--* Build both profiles and the helper (``make``, ``make shirudo-build``)- and run ``make tests``, which CI runs too; ``make -C testing- functional/<family>`` runs the families the change touches while you- work on it. Run ``make tests VM=0 SANITIZE=address,undefined`` when the- change touches memory handling or binary formats; CI runs the same- sweep.-* Run ``make -C Documentation html-docs`` when the change touches ``Documentation/``;- every document must render clean under docutils' strict mode.-* Run ``.github/scripts/check-spdx.sh`` when the change adds a file:- every source carries an SPDX tag in the kernel's form for its type,+--------------++:doc:`developer-guide` shows how to run each of these locally.++- Build the operator binary, the helper and the target binary+ (``make``, ``make shirudo-build``, ``make target``) and run ``make+ tests``, which CI runs too. ``make -C testing functional/<family>``+ runs the families the change touches while you work on it. Run+ ``make tests VM=0 SANITIZE=address,undefined`` from a clean tree when+ the change touches memory handling or binary formats. CI runs the+ same sweep. See :doc:`testing`.+- Run ``make -C Documentation html`` when the change touches+ ``Documentation/``. The build turns every Sphinx warning into an+ error. See :doc:`writing-docs`.+- Run ``.github/scripts/check-spdx.sh`` when the change adds a file.+ Every source carries an SPDX tag in the kernel's form for its type,``BSD-2-Clause`` for userspace and ``GPL-2.0 OR BSD-2-Clause`` foreverything compiled into a BPF object, the headers it includes andthe decoders a package ships. Run``.github/scripts/check-dco.sh origin/main..HEAD`` on the commits. CIruns both.-* Run ``.github/scripts/check-style.sh origin/main..HEAD`` on the- commits: it runs the kernel's ``checkpatch.pl`` in strict mode over+- Run ``.github/scripts/check-style.sh origin/main..HEAD`` on the+ commits. It runs the kernel's ``checkpatch.pl`` in strict mode overthe C each commit touches, at its default limit of 100 columns, andover its message, with the checks that have no meaning in userspace- switched off, each listed in the script with its reason, and it- rejects a block comment whose text starts on the ``/*`` line, the- netdev form. ``--diff`` checks the uncommitted changes, ``--files``+ switched off, each listed in the script with its reason. It also+ refuses a block comment whose text starts on the ``/*`` line (the+ netdev form), the C library's integer names such as ``uint32_t``,+ ``unsigned int`` and its kin in userspace, ``strtoul()``, ``atoi()``+ and their kin, ``strcpy()`` and its kin, and ``sprintf()`` and its+ kin outside the files the script names, and a subject longer than 75+ characters. ``--diff`` checks the uncommitted changes, ``--files``whole files and ``--types`` lists what stays enabled. CI runs it as- the ``Checkpatch`` check.-* Keep each commit to one logical change that builds and passes on its+ the ``Checkpatch`` job of the ``Lint`` workflow.+- Keep each commit to one logical change that builds and passes on itsown, so the history bisects. CI builds every commit of a pull request- on its own as the ``Build every commit`` check;+ on its own in the ``Build every commit`` workflow.``.github/scripts/build-commits.sh origin/main..HEAD`` does the samelocally.-* Read `threat-model <threat-model.rst>`__ before changing anything on a+- Read :doc:`/security/threat-model` before changing anything on asecurity-relevant path, and say in the commit message which invariantthe change preserves or extends.diff --git a/Documentation/contribute/developer-guide.rst b/Documentation/contribute/developer-guide.rstnew file mode 100644index 00000000..e5fc46a6--- /dev/null+++ b/Documentation/contribute/developer-guide.rst@@ -0,0 +1,471 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: shirudo contributors++Work from a checkout+====================++This page takes you from a clone of the repository to the operator+binary, the operator-only helper and the static target binary, shows+where the parts of the tree live and how to run the checks CI runs+before you send a change. :doc:`testing` covers the tests and the test+VM.++Before you begin+----------------++- A Linux host on x86-64, arm64 or riscv64. The test VM runs on x86-64+ and arm64 hosts only.+- A C compiler, GNU make, ``pkg-config``, ``python3`` and a current+ ``clang`` and ``llvm`` with the BPF target. CI installs clang 20 on+ its Ubuntu runners because clang 18 lacks the BPF address-space casts+ that arena upatches need.+- The development files that ``Makefile.config`` probes for with+ ``pkg-config``:++ .. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Module+ - Debian or Ubuntu package+ * - ``libcrypto >= 3.5``, ``libssl >= 3.5``+ - ``libssl-dev`` from OpenSSL 3.5 or newer+ * - ``tss2-esys >= 4.0``, ``tss2-tctildr``+ - ``libtss2-dev``+ * - ``libelf``+ - ``libelf-dev``+ * - ``zlib``+ - ``zlib1g-dev``+ * - ``libcurl >= 7.75``+ - ``libcurl4-openssl-dev``+ * - ``luajit``+ - ``libluajit-5.1-dev``++- The ``openssl`` command from OpenSSL 3.5 or newer. The build probe+ runs ``openssl list -public-key-algorithms`` and refuses a version+ without ML-DSA.+- The BTF of a kernel that has the signed-loader ABI, see+ :ref:`dev-vmlinux`.++The probe stops with ``shirudo: missing prerequisite:`` and an install+hint for each module it cannot find. It writes what it found to+``config.mk``, which ``make distclean`` removes.++Install OpenSSL 3.5+-------------------++The build probe's hint names Ubuntu 26.04 and Fedora 43 as the first+releases that ship OpenSSL 3.5. Ubuntu 24.04 ships 3.0. On an older+distribution, build OpenSSL into a prefix of its own the way+``.github/scripts/vm-toolchain.sh`` does for CI:++1. Download and unpack the release:++ .. code-block:: console++ $ curl -fsSLO https://github.com/openssl/openssl/releases/download/openssl-3.5.9/openssl-3.5.9.tar.gz+ $ tar -xf openssl-3.5.9.tar.gz && cd openssl-3.5.9++ Compare the archive with the SHA-256 that ``vm-toolchain.sh`` pins+ before you build it.++2. Configure and install it under ``<prefix>``, a directory of your+ choice:++ .. code-block:: console++ $ ./Configure --prefix=<prefix> --openssldir=/etc/ssl --libdir=lib no-docs no-tests+ $ make -j"$(nproc)" && make install_sw++3. Put it first for every shell you build or test in:++ .. code-block:: console++ $ export PATH=<prefix>/bin:$PATH+ $ export PKG_CONFIG_PATH=<prefix>/lib/pkgconfig+ $ export LD_LIBRARY_PATH=<prefix>/lib++4. Verify that the command knows ML-DSA:++ .. code-block:: console++ $ openssl list -public-key-algorithms | grep -i ml-dsa++``sudo`` drops ``LD_LIBRARY_PATH`` and replaces ``PATH``. When you run+a make target as root, pass both on, as ``.github/scripts/tests.sh``+does:++.. code-block:: console++ $ sudo -E env PATH="$PATH" LD_LIBRARY_PATH="$LD_LIBRARY_PATH" make tests++.. _dev-vmlinux:++Select the kernel BTF+---------------------++The BPF objects that shirudo embeds compile against+``vendor/linux/vmlinux.h``. ``shirudo build`` run in the checkout root+uses the same header unless ``--vmlinux`` names another. The build+generates that header from BTF with ``tools/gen-vmlinux-h`` and never+commits it. The embedded+admission program reads the signature verdict the kernel records in+``prog->aux->sig``, so the header must come from a kernel with the+signed-loader ABI. A header generated from the BTF of a kernel without+that ABI fails the BPF build.++The build takes the first of these sources:++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Source+ - When+ * - ``BPF_VMLINUX_H=<path>``+ - Copies a prepared ``vmlinux.h``.+ * - ``BPF_VMLINUX_BTF=<path>``+ - Generates the header from a BTF file or an ELF file with a+ ``.BTF`` section.+ * - ``artifacts/bpf-next-kernel-debs/vmlinux.btf``+ - The BTF of the test kernel, when ``make -C testing kernel`` has+ built it.+ * - ``/sys/kernel/btf/vmlinux``+ - The running kernel.++``vendor/linux/.vmlinux-btf-source`` records the source used. When you+select another one, the next build regenerates the header.++1. Build the test kernel, which also writes its BTF. :doc:`testing`+ describes the kernel build:++ .. code-block:: console++ $ make -C testing kernel++2. Or name the BTF of the kernel you build for:++ .. code-block:: console++ $ make BPF_VMLINUX_BTF=<path-to-btf>++3. Verify which source the header came from:++ .. code-block:: console++ $ cat vendor/linux/.vmlinux-btf-source++Build the operator binary+-------------------------++1. Build ``shirudo`` in the checkout root:++ .. code-block:: console++ $ make++2. Verify the build:++ .. code-block:: console++ $ ./shirudo version++The build compiles the vendored libbpf, generates ``vmlinux.h``,+compiles the userspace objects and the BPF objects under ``bpf/``,+embeds the BPF objects into ``util/loader.o`` and links. These make+variables change it:++.. list-table::+ :header-rows: 1+ :widths: 32 68++ * - Variable+ - Effect+ * - ``V=1``+ - Prints the full command lines.+ * - ``WERROR=0``+ - Lets a compiler newer than the tree finish the build. A warning+ fails every build by default, the BPF objects and the vendored+ libbpf included. Fix the warning instead of keeping this set.+ * - ``SHIRUDO_DEBUG=0``+ - Leaves out ``-g``.+ * - ``SANITIZE=address,undefined``+ - Instruments the host binaries and the test helpers with ASan and+ UBSan. See :doc:`testing`.++Build the shirudo-build helper+------------------------------++The core binary never compiles or signs. ``shirudo build``, ``shirudo+image build``, ``shirudo image verify``, ``shirudo keys vouch`` and the+operator ``bpm`` subcommands (``build``, ``push``, ``tree append`` and+``config update``) execute the separate ``shirudo-build`` helper, which+is the only binary that links the signer.++1. Build the helper:++ .. code-block:: console++ $ make shirudo-build++2. Point the core binary at it:++ .. code-block:: console++ $ export SHIRUDO_BUILD=$PWD/tools/shirudo-build/shirudo-build+ $ export PATH=$PWD:$PATH++3. Verify that the operator subcommands resolve. ``shirudo bpm --help``+ lists ``build`` and ``push`` only when the helper resolves:++ .. code-block:: console++ $ shirudo bpm --help++The core binary takes the helper from ``SHIRUDO_BUILD``, then from+``$(libexecdir)/shirudo/shirudo-build``, the path compiled in, then+from ``PATH``. Set ``SHIRUDO_BUILD`` rather than relying on ``PATH``:+an operator package installed on the same host provides the compiled-in+path, which takes precedence over ``PATH``.++``bpm build`` compiles with the package directory as its working+directory. To build a package with a checkout's ``vmlinux.h`` and BPF+headers, give the package directory ``vendor`` and ``bpf`` symbolic+links to the checkout's, as ``t7005`` and ``testing/end2end/host.sh``+do.++Build the target binary+-----------------------++The target binary is a fully static PIE. It links static archives of+OpenSSL, libcurl and tpm2-tss that ``make target-deps`` builds from+source, and the distribution's static ``libelf``, ``zlib``, ``zstd``+and LuaJIT archives.++1. Install the static archives and the tools the tpm2-tss build needs.+ CI installs ``autoconf``, ``autoconf-archive``, ``automake``,+ ``libtool``, ``libltdl-dev`` and ``libzstd-dev`` for this on Ubuntu.++2. Build the dependencies and the binary:++ .. code-block:: console++ $ make target++ ``make target`` runs ``make target-deps`` first. It builds OpenSSL+ 3.5.9, libcurl 8.18.0 and tpm2-tss 4.2.0 under ``build/target-deps``+ and stages every archive in ``build/target-deps/lib``.++3. Verify that the result is a static PIE without an interpreter,+ shared dependencies or library search paths:++ .. code-block:: console++ $ sh .github/scripts/check-static-target.sh shirudo-target++To use dependencies built elsewhere, set ``TARGET_DEPS_PREBUILT=1`` and+point ``SHIRUDO_TARGET_PKG_CONFIG_PATH`` and+``SHIRUDO_TARGET_STATIC_LIBDIR`` at them. ``make target-deps-clean``+removes ``build/target-deps``.++Refresh the vendored libbpf+---------------------------++``vendor/libbpf`` holds libbpf, its BPF-side headers and the BPF UAPI+headers. No kernel tree is needed to build. Refresh the copy only when+a change needs a newer libbpf or UAPI:++.. code-block:: console++ $ make bpf-deps KERNEL_SRC=<kernel-tree>++``<kernel-tree>`` is a kernel checkout. Without ``KERNEL_SRC``,+``tools/bpf-deps/bpf-deps.sh`` makes a shallow clone of bpf-next.++Other make targets+------------------++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Command+ - Result+ * - ``make install``+ - Installs the operator binary and the bash completion under+ ``prefix``, ``/usr/local`` by default.+ * - ``make install-target``+ - Installs the static target binary as ``shirudo``, the units and+ timers, the dracut module and ``shirudo-gen-initrd``.+ * - ``make install-operator``+ - Installs the operator binary, the helper under+ ``$(libexecdir)/shirudo``, the image scripts, ``vmlinux.h`` and+ the BPF headers.+ * - ``DESTDIR=<dir>``, ``prefix=<dir>``, ``bindir=<dir>``,+ ``libexecdir=<dir>``, ``systemdunitdir=<dir>``+ - Override the install paths. The unit and dracut directories are+ absolute by default and do not follow ``prefix``.+ * - ``make -C packaging bindeb-pkg``, ``binrpm-pkg``, ``bintar-pkg``+ - Build the distribution packages from ``make clean``.+ ``PKG_ROLES=operator`` builds the operator package alone. See+ :doc:`/start/install`.+ * - ``make docs``+ - Renders the documentation and serves it on+ ``http://127.0.0.1:8000``. See :doc:`writing-docs`.+ * - ``make clean``, ``make distclean``+ - Remove the build products, and with ``distclean`` also+ ``config.mk``, the target dependencies and the vendored libbpf+ build.+ * - ``make help``, ``make -C testing help``+ - List the targets.++Project layout+--------------++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Path+ - Contents+ * - ``shirudo.c``+ - The command dispatch table.+ * - ``builtin-*.c``, ``builtin.h``+ - One file per top-level command: ``attest``, ``bpm``, ``build``,+ ``config``, ``genkey``, ``image``, ``init``, ``keys``,+ ``status``, ``upatch`` and ``version``.+ * - ``util/``+ - The userspace library both binaries link. ``util/sign.c`` is+ linked into ``shirudo-build`` only.+ * - ``bpf/``+ - The embedded BPF programs: ``bpf2.c`` (admission, mount, image+ and device guards), ``seal.c`` (the seal), ``unload.c`` (the+ signed unload directive) and their headers.+ * - ``bpf/lib/``+ - Headers shared with upatches: decoders, identity, serializers,+ tamper counters and common helpers.+ * - ``include/shirudo/``, ``include/shirudo_enforcement.h``+ - Integer types, string and number helpers, the ``.upatch``+ container layout, TPM types and the enforcement definitions+ shared between userspace and BPF.+ * - ``tools/shirudo-build/``+ - The operator-only helper: compile, sign, unload directives,+ image signing, ``keys vouch``, ``bpm build``, ``push``,+ ``tree append`` and ``config update``.+ * - ``tools/gen-image/``+ - ``shirudo-gen-image``, ``shirudo-gen-runtime`` and+ ``shirudo-gen-verity``, which make the runtime and config images,+ their shared ``common.sh`` and the runtime unit templates.+ * - ``tools/gen-initrd/``+ - The dracut module, the initrd generator and the installer.+ * - ``tools/gen-vmlinux-h/``+ - The ``vmlinux.h`` generator.+ * - ``tools/bpf-deps/``+ - The script that refreshes ``vendor/libbpf``.+ * - ``vendor/libbpf/``+ - Vendored libbpf and BPF UAPI headers.+ * - ``vendor/linux/``+ - The generated ``vmlinux.h``. Not tracked.+ * - ``kernel/``+ - Kernel patches the test kernel build applies. See+ :doc:`/internals/kernel-patches`.+ * - ``upatches/``+ - The shipped packages, ``kernel-obs`` and ``kernel-cve``, each+ with its Beefile.+ * - ``systemd/``+ - Unit and timer templates for the target.+ * - ``completion/``+ - The bash completion. Command names come from+ ``shirudo --list-cmds``. Option lists are maintained by hand.+ * - ``packaging/``+ - The tar, deb and rpm packaging.+ * - ``testing/``+ - Unit, functional, end-to-end and fuzz tests, the test VM and+ their helpers. See :doc:`testing`.+ * - ``Documentation/``+ - This documentation.+ * - ``.github/``+ - The CI workflows and the scripts they run.+ * - ``Makefile``, ``Makefile.shirudo``, ``Makefile.config``,+ ``Makefile.target-deps``, ``Makefile.version``+ - The entry points, the build graph, the prerequisite probes, the+ target dependency build and version discovery.+ * - ``build/``, ``artifacts/``+ - Generated: build products, the test VM state and the test+ kernels. Not tracked.++``shirudo --list-cmds`` prints the top-level commands.++Run the CI checks locally+-------------------------++CI runs these scripts from ``.github/scripts/``. Each takes the+arguments of ``git rev-list``, such as ``origin/main..HEAD``, and checks+the commit at ``HEAD`` alone without them.++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Script+ - Checks+ * - ``check-dco.sh <range>``+ - A one-line subject, a body beyond the tags and the author's+ ``Signed-off-by:``. See :doc:`contributing`.+ * - ``check-style.sh <range>``+ - The kernel's ``checkpatch.pl`` in strict mode over the C each+ commit touches and over its message, plus the project rules.+ ``--diff`` checks uncommitted changes and ``--files`` whole+ files.+ * - ``check-spdx.sh``+ - The SPDX tag of every tracked source. Takes no range.+ * - ``build-commits.sh <range>``+ - Builds every commit on its own: ``make``, ``make+ shirudo-build`` and ``make -C testing test-helpers``. It+ refuses to start with uncommitted changes and checks out each+ commit in the working tree.+ * - ``check-static-target.sh <binary>``+ - That a target binary is a static PIE.+ * - ``tests.sh setup|run``+ - Prepares a CI runner as the VM host and runs ``make tests``.+ Meant for CI runners, which are discarded afterwards.++``check-style.sh`` fetches the kernel's ``checkpatch.pl`` at a pinned+tag into ``build/checkpatch/`` and verifies its SHA-256. Set+``CHECKPATCH=<path>`` to use a kernel tree's+``scripts/checkpatch.pl`` instead, for example without network access.++Before you send a change:++1. Run the checks over your commits:++ .. code-block:: console++ $ .github/scripts/check-dco.sh origin/main..HEAD+ $ .github/scripts/check-style.sh origin/main..HEAD+ $ .github/scripts/check-spdx.sh+ $ .github/scripts/build-commits.sh origin/main..HEAD++2. Run the tests the change touches, and ``make tests`` before you+ send. See :doc:`testing`.++3. Render the documentation if you changed it:++ .. code-block:: console++ $ make -C Documentation html++4. Verify that every script printed its summary line and exited 0, for+ example ``DCO: 3 commits checked`` and ``style: 3 commits checked``.++Next steps+----------++- :doc:`testing` to run and write tests.+- :doc:`contributing` for the commit message and the sign-off.+- :doc:`coding-style` for the C code.+- :doc:`/reference/cli/index` for the commands.diff --git a/Documentation/contribute/index.rst b/Documentation/contribute/index.rstnew file mode 100644index 00000000..3003182f--- /dev/null+++ b/Documentation/contribute/index.rst@@ -0,0 +1,26 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++Contribute+==========++These pages are for developers who change shirudo itself: its code, its+tests, its build and this documentation. Start with+:doc:`/contribute/developer-guide` to build from a clone, then+:doc:`/contribute/testing` to run the tests in the test VM that plays a+target. :doc:`/contribute/test-coverage` shows what the tests cover and+what they do not. Before you send a change, read+:doc:`/contribute/contributing` and :doc:`/contribute/coding-style`, and+read :doc:`/security/threat-model` first when the change touches a+security-relevant path.++.. toctree::+ :titlesonly:++ developer-guide+ testing+ test-coverage+ coding-style+ contributing+ writing-docsdiff --git a/Documentation/contribute/test-coverage.rst b/Documentation/contribute/test-coverage.rstnew file mode 100644index 00000000..c63e827d--- /dev/null+++ b/Documentation/contribute/test-coverage.rst@@ -0,0 +1,808 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: shirudo contributors++Test coverage+=============++This page lists what the tests under ``testing/`` cover, by family, by+area and by threat, and what no test covers. A test is named by its+number here, and by its file name without ``.sh`` in the family+tables. :doc:`testing` explains the families, the numbering and how to+run them.++Families+--------++Operator tests (``t?0??``) run on the build host. Target tests+(``t?1??``) run as root in a VM the family boots, against a target+initialized from the initrd with the dm-verity runtime image and a+signed config image.++``ci-checks`` (0)+~~~~~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 36 64++ * - Test+ - Covers+ * - ``t0001-check-dco``+ - ``check-dco.sh``: subject, body and sign-off, the identities it+ rejects, the author the sign-off must match, merge commits+ * - ``t0002-check-spdx``+ - ``check-spdx.sh``: tag form by file type, the two expressions,+ the dual license of BPF sources and package files, vendored+ licenses, and the tree itself+ * - ``t0003-check-style``+ - ``check-style.sh``: checkpatch at 100 columns, the block-comment+ opener, the subject length, the integer, parser, copy and+ format rules+ * - ``t0004-ci-commit-range``+ - ``ci-commit-range.sh``: the ranges for a pull request, a push and+ a force push+ * - ``t0005-gen-sbom``+ - ``gen-sbom.sh``: the SPDX documents of a target and an operator+ package, and the archives it refuses to leave out++``build`` (1)+~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 36 64++ * - Test+ - Covers+ * - ``t1001-build-dispatch``+ - Helper resolution: ``SHIRUDO_BUILD``, ``PATH`` and a missing+ helper+ * - ``t1002-command-surface``+ - Removed fleet-management commands are absent and rejected+ * - ``t1003-static-target``+ - The target binary is a static PIE with OpenSSL 3.5 or newer and+ no shared TLS closure, and the operator binary is dynamic. Runs+ only where ``make target`` has built ``shirudo-target``+ * - ``t1004-target-system-libdir``+ - Where ``make target-deps`` finds the system static archives+ * - ``t1005-binrpm-pkg``+ - rpm packages: metadata, file lists, requirements and scriptlets+ * - ``t1006-gen-initrd-cli``+ - Initrd generator and installer options, the installer's+ ``--dry-run`` plan+ * - ``t1007-test-vm-cli``+ - Test VM scripts: kernel selection, host dependencies, arm64+ boot settings, the bundle stamp+ * - ``t1008-kernel-ami-config``+ - The slim kernel configuration for NitroTPM CRB, EC2, EFI and SSM++``signing`` (2)+~~~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 36 64++ * - Test+ - Covers+ * - ``t2001-genkey``+ - ML-DSA-87 only, certificate key identifiers, ``--force``+ * - ``t2002-mldsa-sign``+ - The CMS form the kernel verifies, refusal of RSA and ML-DSA-65+ keys, a one-bit change in the signed bytes+ * - ``t2003-keys-set``+ - The trusted set and its digest, revoked certificates left out,+ ``attest predict`` agreement+ * - ``t2004-keys-vouch``+ - ``keys vouch``, and ``keys add`` admitting only vouched+ certificates+ * - ``t2005-keys-signer``+ - Signer identification for a revocation purge, prediction of a+ revoke event+ * - ``t2101-keys``+ - Two enrolled certificates, a upatch signed by the second loads+ * - ``t2102-keys-add``+ - Live ``keys add`` is refused under a signed config+ * - ``t2103-keys-revoke``+ - Live ``keys revoke`` is refused under a signed config++``upatch`` (3)+~~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 36 64++ * - Test+ - Covers+ * - ``t3001-upatch-parse``+ - Malformed ``.upatch`` containers are refused, files over 16 MiB+ without mapping them+ * - ``t3002-upatch-decoders``+ - Decoder metadata, Lua sandbox limits, refusal of bytecode+ * - ``t3003-upatch-map-types``+ - Map type labels, arena maps only through a serializer+ * - ``t3004-upatch-serializer-metadata``+ - Serializer metadata and the builder's refusals+ * - ``t3005-upatch-serializer-pages``+ - Paged serializer JSON and ``upatch map`` output+ * - ``t3006-cgroup-skb-metadata``+ - ``cgroup_skb`` ingress and egress attach metadata+ * - ``t3007-uprobe-multi-metadata``+ - ``uprobe.multi`` globs to file offsets and the target's build ID+ * - ``t3008-override-metadata``+ - kprobe override and ``fmod_ret`` attach metadata+ * - ``t3009-netfilter-metadata``+ - netfilter attach metadata+ * - ``t3010-unsupported-network-sections``+ - Attach kinds the builder refuses+ * - ``t3011-string-bounds``+ - Names and the tree repository are refused rather than cut+ * - ``t3101-target-fixtures``+ - Prebuilt fixtures load and unload, foreign and own-keyring+ fixtures are refused, a map fixture exports+ * - ``t3102-upatch-arena-serializer``+ - Arena serializer pagination on a target+ * - ``t3103-version-gate``+ - ``--expect-version-id`` refuses ``version_mismatch``+ * - ``t3104-payload-mismatch``+ - An unload with the wrong payload refuses ``payload_mismatch``+ * - ``t3105-load-unload``+ - Load, the payload xattr on the pin, unload+ * - ``t3106-upatch-get``+ - ``upatch get`` source lines and JSON+ * - ``t3107-uprobe-multi``+ - A live ``uprobe.multi`` load, refusal after a build ID change+ * - ``t3108-status-many``+ - ``status --json`` with eighty loaded upatches lists all of them++``tpm`` (4)+~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 36 64++ * - Test+ - Covers+ * - ``t4001-tpm-wire``+ - Policy digests, names and attestation structures against values+ computed independently+ * - ``t4002-eventlog-pending``+ - The initrd's pending record and its adoption+ * - ``t4003-register``+ - Register lifecycle before ``init``, binding, ``attest``,+ ``verify``, ``predict`` and ``challenge``, a TPM reset. Runs in+ the register VM+ * - ``t4004-config-attest``+ - Config activation in the evidence and its verification. Runs in+ the register VM+ * - ``t4101-initrd``+ - The production configuration: ``init`` from the initrd, adoption,+ PCR 11 after the binding, pins under ``/run``+ * - ``t4102-tpm-chain``+ - Replay, measured load and unload, evidence from the VM's TPM,+ challenges with ECC and RSA endorsement keys+ * - ``t4103-nv-writer``+ - The ``tpm_command`` guard: root without authority cannot extend+ the register, through inherited and nonblocking descriptors+ too++``image`` (5)+~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 36 64++ * - Test+ - Covers+ * - ``t5001-config-image``+ - Image builder and ``veritysetup`` format, superblock and size+ checks, the ML-DSA-87 root signature, runtime acceptance by the+ exact root, the generator scripts+ * - ``t5002-image-config``+ - Settings a config may set, symbolic links and special files+ * - ``t5003-image-keys``+ - Signer set and revocation records in a config+ * - ``t5004-image-cli``+ - Local key and repository changes refused, ``config`` output,+ repository certificates inside the image, tree trust+ * - ``t5005-image-cleanup``+ - Candidate removal and its ``EBUSY`` retries+ * - ``t5006-image-bootstrap``+ - Bootstrap settings in the initrd+ * - ``t5007-config-update``+ - Activation events, the pending latch, interruption, locks,+ symbolic links in state+ * - ``t5008-text-lines``+ - Long lines and NUL bytes in settings files+ * - ``t5101-verity-boot-signers``+ - The ``.dm-verity`` keyring, boot enrollment of a vouched signer+ * - ``t5102-verity-config``+ - Config classification, corruption, live activation from A to B+ * - ``t5103-verity-cli``+ - Key and repository changes require a signed config+ * - ``t5104-verity-revocation``+ - Signed revocation unlinks the signer and purges its upatch+ * - ``t5105-verity-interruption``+ - An interruption after measurement blocks changes and attestation++``tamperproof`` (6)+~~~~~~~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 36 64++ * - Test+ - Covers+ * - ``t6001-seal-create``+ - The creation helpers label what they create under a labelled+ directory+ * - ``t6002-seal-seccomp``+ - The seal builds with either seccomp layout in ``vmlinux.h``+ * - ``t6003-tamper-points``+ - Every tamper counter has a name and a meaning+ * - ``t6004-conditions``+ - Status conditions: keyring, register, config activation+ * - ``t6005-mode-objects``+ - The embedded admission and seal objects include image+ enforcement+ * - ``t6006-harden``+ - Memory locking at startup, failing closed+ * - ``t6007-output-paths``+ - Output paths: no symbolic links, directories or devices+ * - ``t6101-mode-objects``+ - Device, memory and config-root guards are pinned+ * - ``t6102-siggate``+ - A foreign-signed upatch is refused+ * - ``t6103-lsm-deny``+ - An unsigned userspace ``BPF_PROG_LOAD`` is denied+ * - ``t6104-prog-load-keyring-gate``+ - A valid signature against a keyring of the caller's is denied+ * - ``t6105-mount-lockdown``+ - Unmount, lazy unmount, remount and mount over the bpffs+ * - ``t6106-pin-rename``+ - Renames in the bpffs+ * - ``t6107-bpf-cmd-deny``+ - ``bpf()`` commands left to shirudo or denied, opening pins,+ maps and links+ * - ``t6108-tamper-counters``+ - Counters move with refusals and root cannot reset them+ * - ``t6109-map-lockdown``+ - Map descriptors, pin reads and serializer test runs+ * - ``t6110-pr-set-mm-identity``+ - ``PR_SET_MM`` executable changes+ * - ``t6111-seal-scratch``+ - The seal against root on labelled files+ * - ``t6112-key-permission``+ - The ``.bpf`` and ``.dm-verity`` keyrings cannot be changed+ * - ``t6113-verity-authority``+ - Task authority on exec, fork and failed exec+ * - ``t6114-output-paths``+ - Output paths aimed at sealed state+ * - ``t6115-archive-restore``+ - Artifacts brought into the archive, a hidden state directory,+ ``/etc/initrd-release``+ * - ``t6116-attach-scope``+ - ``attach_scope_mismatch`` in a foreign network or cgroup+ namespace, and through a substituted PMU+ * - ``t6117-signed-metadata``+ - Edited attach metadata, name and unload target+ * - ``t6118-foreign-entries``+ - Entries root brings into sealed directories+ * - ``t6119-perf-attach``+ - ``PERF_EVENT_IOC_SET_BPF``+ * - ``t6120-umount-above``+ - Unmounts above the bpffs, by subtree and by propagation+ * - ``t6121-bpffs-entries``+ - Directories, symbolic links and hard links in the bpffs+ * - ``t6122-persist-undo``+ - A load whose archive copy fails is undone+ * - ``t6123-foreign-state-root``+ - An unlabelled state root bound over the path+ * - ``t6124-overlay-copy-up``+ - An overlay over the state root+ * - ``t6125-tpm-identity``+ - A substituted TPM device is refused by its attestation key name+ * - ``t6126-kexec``+ - ``kexec_load`` and ``kexec_file_load``+ * - ``t6127-proc-substitution``+ - Config read through a substituted ``/proc``+ * - ``t6128-register-lock``+ - The lock that keeps register and eventlog in step+ * - ``t6129-keyring-seal``+ - The exact keyring check at ``init``+ * - ``t6130-verity-devices``+ - Image mount flags, device-mapper table changes, mount changes+ * - ``t6131-verity-process``+ - ``ptrace`` and memory writes to an image-authorized task+ * - ``t6132-verity-hidden``+ - A hidden bpffs cannot make shirudo fall back to host settings+ * - ``t6133-seal-init-xattr``+ - Labels at inode creation+ * - ``t6134-seal-task``+ - ``ptrace`` and perf events on a running shirudo+ * - ``t6135-task-descriptors``+ - Descriptors through ``/proc`` and ``pidfd_getfd``+ * - ``t6136-secure-exec``+ - Secure-exec mode and no program interpreter+ * - ``t6137-traced-exec``+ - A traced task cannot exec shirudo+ * - ``t6138-upatch-integrity``+ - A mutated loader, the payload binding, links by pin or id+ * - ``t6139-serializer-runs``+ - Repeated peeks and concurrent drains++``bpm`` (7)+~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 36 64++ * - Test+ - Covers+ * - ``t7001-bpm-cli``+ - Subcommands, reference validation before network access, source+ and tree configuration lines+ * - ``t7002-bpm-info``+ - READMEs of local and OCI packages, archive integrity+ * - ``t7003-bpm-key``+ - ``bpm key`` from files and OCI references, ``bpm pull``+ * - ``t7004-bpm-repo-update``+ - The repository update unit and timer and their package+ scriptlets, as text+ * - ``t7005-bpm-publish``+ - ``bpm build``, ``bpm push`` with a signed index, ``bpm tree+ append``+ * - ``t7101-bpm-tree``+ - Tree sync with a selector+ * - ``t7102-bpm-tree-sequential``+ - Re-sync and the next generation+ * - ``t7103-bpm-tree-delete``+ - A delete operation and adding the upatch back++``otel`` (8)+~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 36 64++ * - Test+ - Covers+ * - ``t8001-otel-map``+ - OTLP mapping, retries, S3 uploads, tenant IDs, the insecure+ override+ * - ``t8002-map-export-config``+ - Map export settings+ * - ``t8003-systemd-map-export``+ - Exporter units and timers and their package scriptlets, as text+ * - ``t8004-status-otel``+ - The keepalive log record+ * - ``t8005-tls-policy``+ - TLS 1.3 with ``X25519MLKEM768`` only+ * - ``t8006-otel-transport``+ - OTLP environment variables, headers and limits+ * - ``t8101-map-export-all``+ - ``upatch map --all`` and JSON lines+ * - ``t8102-otel-backend``+ - The map-export service and timer with decoders+ * - ``t8103-otel-serialized-metric``+ - Serializer metrics, peek and drain+ * - ``t8104-export-config``+ - Precedence of config, environment and command line, a failed+ export+ * - ``t8105-export-tls``+ - CA and client certificate selection, the S3 CA++``end2end`` (9)+~~~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 36 64++ * - Test+ - Covers+ * - ``t9001-dns-observability-matrix``+ - The DNS packet builders the matrix test uses+ * - ``t9101-kernel-obs``+ - ``kernel-obs`` with eight serializers, records from real events,+ draining exports+ * - ``t9102-kernel-obs-net``+ - Socket families+ * - ``t9103-kernel-obs-priv``+ - Privilege and executable-mapping records+ * - ``t9104-kernel-obs-dns-matrix``+ - DNS over loopback+ * - ``t9105-delivery``+ - Registry, tree sync, load, export and attestation end to end++Unit suites and fuzz targets+~~~~~~~~~~~~~~~~~~~~~~~~~~~~++The unit suites in ``testing/unit/`` cover seven of the modules in+``util/``: ``chain``, ``hex``, ``json``, ``kernel_abi``,+``kernel_build_id``, ``kernel_release`` and ``string``. The other+modules are reached through the test helpers, the fuzz targets and the+binaries the functional tests run.++.. list-table::+ :header-rows: 1+ :widths: 26 74++ * - Fuzz target+ - Input+ * - ``attest``+ - Evidence as ``attest verify`` reads it, and challenges+ * - ``beefile``+ - A Beefile+ * - ``bpm-index``+ - A repository index+ * - ``bpm-package``+ - A ``.bee`` package as ``bpm install`` unpacks it+ * - ``bpm-tar``+ - The Beefile inside a package archive+ * - ``cms``+ - Certificates and detached CMS signatures+ * - ``config``+ - ``shirudo.conf``, registry sources and ``upatch-tree.conf``+ * - ``decoder``+ - Map data a Lua decoder reads+ * - ``elf``+ - The build ID of a uprobe target binary+ * - ``eventlog``+ - The eventlog and its replay+ * - ``json``+ - The JSON parser+ * - ``kconfig``+ - A kernel configuration and ``node.labels``+ * - ``kernel``+ - ``/dev/kmsg`` records, ``/proc/modules`` and kernel notes+ * - ``oci-http``+ - Registry and token server responses+ * - ``oci-manifest``+ - An OCI manifest+ * - ``oci-ref``+ - ``oci://`` references+ * - ``otel``+ - OTLP collector responses and ``OTEL_EXPORTER_OTLP_HEADERS``+ * - ``prog-metadata``+ - A load upatch's program metadata+ * - ``registry-auth``+ - The container auth file+ * - ``serializer``+ - Serializer output pages+ * - ``tpm-wire``+ - TPM structures in evidence+ * - ``tree``+ - An upatch tree publication+ * - ``tree-state``+ - The tree's ``state.json`` and eventlog+ * - ``upatch``+ - A ``.upatch`` container and its decoder table++Coverage by area+----------------++.. list-table::+ :header-rows: 1+ :widths: 26 74++ * - Area+ - Tests+ * - Signed loading+ - ``t2002``, ``t2101``, ``t3101``, ``t3105``, ``t6102``,+ ``t6117``, ``t6138``. Fuzz: ``cms``, ``upatch``,+ ``prog-metadata``+ * - Admission+ - ``t6005``, ``t6101``, ``t6102``, ``t6103``, ``t6104``,+ ``t6107``, ``t6113``+ * - BPF command policy+ - ``t6107``, ``t6108``, ``t6109``, ``t6110``, ``t6119``,+ ``t6138``. Root without runtime authority cannot open shirudo's+ maps, links or pins by pin, id or file: ``t6107``, ``t6108``,+ ``t6109``, ``t6138``+ * - Maps, links and serializers+ - ``t3003``, ``t3004``, ``t3005``, ``t3102``, ``t6109``,+ ``t6138``, ``t6139``, ``t8101``, ``t8103``+ * - Load and unload+ - ``t3101``, ``t3103``, ``t3104``, ``t3105``, ``t4102``,+ ``t6116``, ``t6122``, ``t6128``. Unit: ``kernel_abi``+ * - Attach kinds+ - Offline metadata: ``t3006``, ``t3007``, ``t3008``, ``t3009``,+ ``t3010``. Loaded on a target: fentry (fixtures), ``lsm``+ (``t9101``), ``cgroup_skb`` and netfilter (``t6116``),+ ``uprobe.multi`` (``t3107``)+ * - bpffs pins and mounts+ - ``t4101``, ``t6105``, ``t6106``, ``t6108``, ``t6120``,+ ``t6121``+ * - Seal+ - ``t6001``, ``t6002``, ``t6007``, ``t6111``, ``t6114``,+ ``t6115``, ``t6118``, ``t6123``, ``t6124``, ``t6133``+ * - Task authority+ - ``t6006``, ``t6110``, ``t6113``, ``t6131``, ``t6132``,+ ``t6134``, ``t6135``, ``t6136``, ``t6137``+ * - Keyrings+ - ``t2101``, ``t2102``, ``t2103``, ``t5101``, ``t5104``,+ ``t6004``, ``t6104``, ``t6112``, ``t6129``+ * - Signing keys and the trusted set+ - ``t2001``, ``t2002``, ``t2003``, ``t2004``, ``t2005``,+ ``t5003``+ * - TPM register+ - ``t4001``, ``t4003``, ``t4101``, ``t4102``, ``t4103``,+ ``t6125``, ``t6128``. Unit: ``chain``+ * - Attestation+ - ``t2003``, ``t2005``, ``t4003``, ``t4004``, ``t4102``,+ ``t9105``. Fuzz: ``attest``, ``tpm-wire``+ * - Eventlog+ - ``t4002``, ``t4102``, ``t5007``, ``t6114``, ``t6128``. Fuzz:+ ``eventlog``+ * - Boot and initrd+ - ``t1006``, ``t4002``, ``t4101``, ``t5006``, ``t6115``,+ ``t6126``+ * - Config images+ - ``t4004``, ``t5001`` to ``t5008``, ``t5101`` to ``t5105``,+ ``t6112``, ``t6127``, ``t6130``, ``t6132``. Fuzz: ``config``+ * - Packages and repositories+ - ``t7001``, ``t7002``, ``t7003``, ``t7004``, ``t7005``. Fuzz:+ ``beefile``, ``bpm-index``, ``bpm-package``, ``bpm-tar``,+ ``oci-http``, ``oci-manifest``, ``oci-ref``, ``registry-auth``+ * - upatch tree+ - ``t3011``, ``t5004``, ``t7005``, ``t7101``, ``t7102``,+ ``t7103``, ``t9105``. Fuzz: ``tree``, ``tree-state``,+ ``kconfig``. Unit: ``kernel_build_id``, ``kernel_release``+ * - Telemetry+ - ``t6139``, ``t8001`` to ``t8006``, ``t8101`` to ``t8105``,+ ``t9101`` to ``t9105``. Fuzz: ``otel``, ``serializer``+ * - Decoders+ - ``t3002``, ``t8102``, ``t9101``. Fuzz: ``decoder``+ * - Tamper counters+ - ``t6003``, ``t6108``, ``t6115``, ``t6118``, ``t6119``,+ ``t6120``, ``t6121``, ``t6124``, ``t6126``, ``t6135``,+ ``t6137``+ * - CLI+ - ``t1001``, ``t1002``, ``t2001``, ``t3005``, ``t3106``,+ ``t3108``, ``t5004``, ``t5103``, ``t6007``, ``t6114``,+ ``t7001``, ``t8001``+ * - Build and packaging+ - ``t0005``, ``t1003``, ``t1004``, ``t1005``, ``t1008``,+ ``t7004``, ``t8003``+ * - CI scripts+ - ``t0001`` to ``t0005``+ * - Parsers+ - ``t3001``, ``t3011``, ``t5002``, ``t5006``, ``t5008``. Unit:+ ``hex``, ``json``, ``string``. Every fuzz target++Coverage by threat+------------------++The threats are those of :doc:`/security/threat-model`.++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Threat+ - Tests+ * - T1 Loading unsigned BPF+ - ``t2002``, ``t3101``, ``t6102``, ``t6103``, ``t6104``,+ ``t6107``, ``t6108``, ``t6138``+ * - T2 Detaching or replacing enforcement+ - ``t6101``, ``t6105``, ``t6106``, ``t6107``, ``t6108``,+ ``t6109``, ``t6116``, ``t6119``, ``t6120``, ``t6121``,+ ``t6138``+ * - T3 Tampering with shirudo's files and process+ - ``t6001``, ``t6006``, ``t6007``, ``t6110``, ``t6111``,+ ``t6112``, ``t6114``, ``t6115``, ``t6118``, ``t6123``,+ ``t6124``, ``t6127``, ``t6129``, ``t6133``, ``t6134``,+ ``t6135``, ``t6136``, ``t6137``+ * - T4 Substituting artifacts+ - ``t3001``, ``t3011``, ``t3104``, ``t3105``, ``t6117``,+ ``t6138``+ * - T5 Silent state change+ - ``t2005``, ``t4002``, ``t4003``, ``t4102``, ``t4103``,+ ``t5007``, ``t6115``, ``t6122``, ``t6125``, ``t6128``+ * - T6 The boot window+ - ``t1006``, ``t4101``, ``t6115``, ``t6126``+ * - T7 The delivery path+ - ``t7002``, ``t7003``, ``t7005``, ``t7101``, ``t7102``,+ ``t7103``, ``t8005``, ``t9105``+ * - T8 Quantum-capable adversaries+ - ``t2001``, ``t2002``, ``t5001``, ``t8005``+ * - T9 A target lying about its state+ - ``t4001``, ``t4003``, ``t4004``, ``t4102``, ``t9105``+ * - T10 An attempt that leaves no trace+ - ``t6003``, ``t6108``, ``t6118``, ``t6119``, ``t6120``,+ ``t6121``, ``t6124``, ``t6126``, ``t6135``, ``t6137``+ * - T11 Image-mode config and executable substitution+ - ``t5001``, ``t5002``, ``t5003``, ``t5006``, ``t5008``,+ ``t5101``, ``t5102``, ``t5103``, ``t5104``, ``t6112``,+ ``t6113``, ``t6127``, ``t6130``, ``t6131``, ``t6132``+ * - T12 Interrupted image activation+ - ``t4004``, ``t5007``, ``t5105``, ``t6004``++Coverage of tamper counters+---------------------------++``t6003`` checks that every counter has a name and a meaning, and+``t6108`` that ``status --json`` reports the counters as numbers. These+tests assert that a refusal moves its counter:++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Counter+ - Test+ * - ``LoadNotLoader``, ``ProgAttach``, ``ObjPin``, ``ObjGet``,+ ``BpfCommand``, ``PinUnlink``, ``PinRename``, ``BpffsUmount``+ - ``t6108``+ * - ``BpffsUmountAbove``+ - ``t6120``+ * - ``PinEntry``+ - ``t6121``+ * - ``PerfAttach``+ - ``t6119``+ * - ``SealEntry``+ - ``t6115``, ``t6118``+ * - ``SealCopyUp``+ - ``t6124``+ * - ``SealPtrace``+ - ``t6135``+ * - ``ExecTraced``+ - ``t6137``+ * - ``Kexec``+ - ``t6126``++Not covered+-----------++These are verified absences: no test under ``testing/`` exercises them.++Attacks+~~~~~~~++Most of these attacks are open threats in+:doc:`/security/threat-model`:++- ``attest verify`` run without ``--ak-name`` or without any+ expectation of the state.+- An environment that steers an authorized shirudo process, such as+ ``BPM_OCI_SCHEME``, ``BPM_OCI_CA_FILE``, proxy variables,+ ``SSLKEYLOGFILE`` or ``TSS2_LOGFILE``. ``t6136`` covers the dynamic+ loader's variables only.+- A repository index or tree publication signed with a classical+ algorithm.+- Removing an empty sealed directory, ``chattr`` on sealed files, POSIX+ ACLs on them, and a hard link of a labelled inode into an unsealed+ directory. ``t6118`` covers hard links into sealed directories only.+- An eventlog larger than the size the readers accept.+- A fake TPM transport that replays the attestation key name ``init``+ recorded. ``t6125`` covers a device with another name.+- Making ``init`` read another boot ID, or miss this boot's init+ record by other means than the unlabelled state directory ``t6115``+ covers, so that it binds the register again.+- A target without kernel lockdown. The test kernel enables no+ lockdown.+- A failure of ``shirudo-initrd.service`` that lets the boot continue+ without enforcement, and a first ``init`` outside the initrd.+- Another LSM denying the read of a seal label. The test kernel runs+ with ``CONFIG_LSM="bpf"`` alone.+- ``bpm config update --base-package`` running commands from a package+ fetched from a registry.+- A boot restore that fails part way.+- Loading an older artifact signed by the same key, and an unload+ directive signed by another trusted key than the load.+- Stopping a running shirudo with ``SIGSTOP``, ``mount_setattr(2)``,+ hibernation and ``/dev/snapshot``, ``/dev/mem``, and TPM access over+ ``i2c-dev`` or ``spidev``.++Tests that assert behavior the threat model lists as a threat to+resolve. They change when that threat is resolved:++- ``t5102`` asserts that a config root signed under a kernel built-in+ certificate is accepted.+- ``t2003`` and ``t5003`` assert that a revoked signer's earlier+ vouches stay valid.+- ``t5004`` asserts that tree publications verify against the runtime+ trust anchor.+- ``t7003`` adds a certificate from an OCI reference without a+ fingerprint to compare it with.++Commands and procedures+~~~~~~~~~~~~~~~~~~~~~~~++- ``bpm repo update``, ``bpm install``, ``bpm upgrade`` and ``bpm+ uninstall`` against a repository on a target. ``t7004`` reads the+ unit files, ``t7001`` checks argument validation and the+ ``bpm-index`` fuzz target the index parser.+- ``bpm config update``.+- ``upatch load`` or ``upatch unload`` refusing ``tampered`` for a+ stale ``--expect-chain``. Only ``attest verify`` is tested with that+ option.+- ``status --include-eventlog``, ``--include-kernellog``,+ ``--include-modules`` and ``--show-full``.+- ``upatch rewrite-rodata`` in ``shirudo-build``, which+ ``kernel-obs`` uses to rewrite its watch lists.+- The ``kernel-cve`` package. Its Beefile is a seed of the ``beefile``+ fuzz target only.+- The recovery, upgrade and decommissioning procedures of+ :doc:`/operate/backup-recovery` and :doc:`/operate/upgrade`.+- Exit statuses. ``t8001``, ``t4003`` and ``t4102`` check a few, but no+ test checks the exit status of every command. No test names the+ failure categories ``already_unloaded``, ``attach_target_missing``,+ ``detach_failed``, ``eventlog_full``, ``kernel_abi_unsupported``,+ ``lsm_denied``, ``signature_unsupported`` or ``verifier_rejected``.+- Completion against the parsers. ``completion/shirudo.bash`` keeps its+ option lists by hand, and no test compares them with the options the+ commands accept.++Units and boot+~~~~~~~~~~~~~~++- The units on the root file system as installed. The test VM replaces+ the ``ExecStart`` of each of them with the runtime command before the+ tests run, so no test runs one as installed. ``shirudo.service``,+ ``shirudo-keepalive.service`` and ``shirudo-bpm-repo-update.service``+ are never started. ``t8102``, ``t8103``, ``t8104`` and ``t9105``+ start the map-export and tree-sync services with the replaced+ command. ``shirudo-initrd.service`` runs from its template in the+ initrd of every target VM.+- A reboot. No test reboots a guest. Restore at boot and the completion+ of a pending activation run as repeated ``init`` runs and through+ helpers (``t5007``), and ``t4003`` resets a simulated TPM.++Tamper counters+~~~~~~~~~~~~~~~++No test asserts that a refusal moves ``LoadUnsigned``,+``LoadUnverified``, ``LoadKeyringKind``, ``LoadKeyring``, ``MapCreate``,+``MapWrite``, ``MapFdWrite``, ``ProgRun``, ``ExeIdentity``,+``KeyringWrite``, ``PinXattr``, ``BpffsMount``, ``SealWrite``,+``SealUnlink``, ``SealRename``, ``SealSetattr``, ``SealXattr``,+``SealLabel``, ``SealPerf`` or ``TpmExtend``. The refusals behind+several of them are tested, the counter is not.++Attach kinds+~~~~~~~~~~~~++- ``fexit``, ``tp_btf`` and ``kretprobe`` have no test, offline or on a+ target.+- ``fmod_ret`` and kprobe override are checked offline only+ (``t3008``).+- kprobe loads run only on a kernel with a kprobe PMU. The test kernel+ has none, so ``t6116`` leaves out its kprobe case.++Platforms+~~~~~~~~~++- Real TPMs. Every TPM test uses ``swtpm`` in the VM or the libtpms+ simulator helper. ``t1008`` checks only the kernel configuration for+ NitroTPM.+- Architectures. CI runs every tier on x86-64 only. The test VM boots+ arm64 too, and ``t1007`` checks its arm64 settings without booting.+ riscv64 has no test VM.+- Kernels. CI boots bpf-next only. ``KERNEL=`` boots a release kernel+ by hand.++Parsers and units+~~~~~~~~~~~~~~~~~++- The dm-verity superblock check in ``util/config_image.c`` has no+ fuzz target. ``t5001`` covers truncation and unsupported fields.+- 56 of the 63 modules in ``util/`` have no unit suite of their own.++Related+-------++- :doc:`testing` to run the tests and write one.+- :doc:`/security/threat-model` for the threats and residual risks.+- :doc:`/security/tamper-counters` for what each counter means.diff --git a/Documentation/contribute/testing.rst b/Documentation/contribute/testing.rstnew file mode 100644index 00000000..10451b2b--- /dev/null+++ b/Documentation/contribute/testing.rst@@ -0,0 +1,646 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: shirudo contributors++Run and write tests+===================++This page shows how to run shirudo's tests, from one unit suite to the+full run CI makes, how to use the test VM that plays the target, and+where a test you add goes. :doc:`test-coverage` lists what the tests+cover.++Before you begin+----------------++- A tree that builds, see :doc:`developer-guide`. ``make -C testing``+ builds the binaries, the helper and the test helpers it needs+ itself.+- For the unit and operator tests: ``python3``, ``clang``, OpenSSL 3.5+ or newer and the ``openssl`` command. ``veritysetup`` from+ ``cryptsetup-bin`` and ``mkfs.ext4`` from ``e2fsprogs`` for the image+ tests, ``libtpms-dev`` for the TPM simulator helper and ``rpmbuild``+ for the rpm packaging test.+- For the tests that boot a VM: root, a readable and writable+ ``/dev/kvm``, an x86-64 or arm64 host and what ``make target`` needs,+ since the bundle a VM boots holds the static target binary. On Ubuntu,+ ``.github/scripts/tests.sh setup`` installs ``cloud-image-utils``,+ ``dracut-core``, ``file``, ``isc-dhcp-client``, ``libguestfs-tools``,+ ``qemu-system-x86``, ``qemu-utils``, ``swtpm``, ``swtpm-tools`` and+ ``tpm2-tools`` among others. ``testing/vm/run.sh`` names the packages+ it misses with an install command for ``apt-get`` or ``dnf``.+- For the end-to-end tests: Docker on the host.++Test tiers+----------++.. list-table::+ :header-rows: 1+ :widths: 14 26 30 30++ * - Tier+ - Directory+ - Runs+ - Command+ * - Unit+ - ``testing/unit/``+ - On the build host+ - ``make -C testing unit``+ * - CI checks+ - ``testing/ci-checks/``+ - On the build host+ - ``make -C testing ci-checks``+ * - Functional+ - ``testing/functional/<family>/``+ - Operator tests on the build host, target tests in a VM per+ family+ - ``make -C testing functional``+ * - End-to-end+ - ``testing/end2end/``+ - Around one VM, with a registry and a collector in containers on+ the host+ - ``make -C testing end2end``+ * - Fuzz+ - ``testing/fuzz/``+ - On the build host, under libFuzzer, ASan and UBSan+ - ``make -C testing fuzz``++``make tests`` in the checkout root, or ``make -C testing``, runs the+unit, CI check, functional and end-to-end tiers in that order. The fuzz+targets run on their own.++Test numbers and families+-------------------------++A shell test is named ``t<F><K><NN>-<what>.sh``:++- ``F`` is the family, which fixes the directory.+- ``K`` is ``0`` for an operator test, which runs on the build host+ without root, a kernel or a TPM of its own, and ``1`` for a target+ test, which runs as root in the family's VM against an initialized+ target.+- ``NN`` orders the tests of a family and kind, and is the order they+ run in.++.. list-table::+ :header-rows: 1+ :widths: 6 30 64++ * - F+ - Directory+ - Covers+ * - 0+ - ``ci-checks/``+ - The DCO, SPDX and style checkers, the CI commit range and the+ SBOM generator+ * - 1+ - ``functional/build/``+ - Helper dispatch, the command surface, the static target, rpm+ packaging, the initrd generator and installer, the test VM+ scripts and the slim kernel configuration+ * - 2+ - ``functional/signing/``+ - Keys, signatures, vouching, revocation and the trusted set+ * - 3+ - ``functional/upatch/``+ - The ``.upatch`` container, attach metadata, decoders,+ serializers, load, unload and ``upatch get``+ * - 4+ - ``functional/tpm/``+ - TPM structures, the measurement register, the eventlog,+ attestation, the initrd binding and the register guard+ * - 5+ - ``functional/image/``+ - Runtime and config images, settings, keys, activation,+ revocation and interruption+ * - 6+ - ``functional/tamperproof/``+ - Attacks on the admission and BPF command policy, bpffs, the+ seal, task authority, the keyrings and the TPM path+ * - 7+ - ``functional/bpm/``+ - Package commands, publishing and the upatch tree+ * - 8+ - ``functional/otel/``+ - Map export, the status keepalive, OTLP transport and TLS policy+ * - 9+ - ``end2end/``+ - The ``kernel-obs`` package against real kernel activity and the+ whole delivery path++A test you add takes the next free number of its family and kind. A+number is never reused for another test. A file under ``testing/`` that+is not a test does not take a name of this form. A target test can have+a Python companion with the same stem, such as+``t5101-verity-boot-signers.py``, which only its shell test runs.++``t4003`` and ``t4004`` carry operator numbers but test the register+before ``init``. They skip on the build host and run in a separate VM+that the ``tpm`` family boots without the production initrd.++Run the tests+-------------++Run everything, as CI does:++.. code-block:: console++ # make tests++``make -C testing help`` lists the unit suites and the families. Run+one tier, one unit suite or one family:++.. code-block:: console++ $ make -C testing unit+ $ make -C testing unit/<suite>+ # make -C testing functional/<family>++``<suite>`` is a file name under ``testing/unit/`` without ``.c``, such+as ``json``. ``<family>`` is a directory under ``testing/functional/``,+such as ``upatch``. A family runs its operator tests in number order,+then boots its VM and runs its target tests there. ``make -j`` boots the+VMs of several families side by side.++Leave out every test that boots a VM, for a host without KVM or root:++.. code-block:: console++ $ make tests VM=0+ $ make -C testing functional/<family> VM=0++Run the cases of a unit suite whose names contain ``<substring>``:++.. code-block:: console++ $ build/unit/<suite> <substring>++Run one operator test directly. It changes to ``testing/`` itself and+uses the binaries in the checkout root, so build them first:++.. code-block:: console++ $ make && make shirudo-build && make -C testing test-helpers+ $ sh testing/functional/<family>/<test>.sh++A target test runs only in a VM, with its family or by hand in an+interactive VM, see :ref:`testing-by-hand`.++Read the results+~~~~~~~~~~~~~~~~++Every test prints TAP: ``ok <n> - <title>``, ``not ok <n> - <title>``+and a closing ``1..<n>``. A failing case's standard error follows as+lines that start with ``#``. ``testing/run-tests.sh`` exits with the+number of test scripts that failed.++A test that cannot run prints ``1..0 # SKIP <reason>``. On the build+host a skip counts as a pass, so look for ``# SKIP`` when an operator+test seems to pass too quickly. A target test that skips as a whole+fails its family with ``required target test was skipped``, since every+target test is required.++Run under the sanitizers+------------------------++1. Remove the objects of an earlier build. The build does not track+ compiler flags, so it would keep objects built without the+ sanitizers:++ .. code-block:: console++ $ make clean++2. Build and run every test that needs no VM under ASan and UBSan:++ .. code-block:: console++ $ make tests VM=0 SANITIZE=address,undefined++``SANITIZE`` instruments the host binaries and the test helpers. The BPF+objects are unaffected. Recovery is off, so every report fails the run.+CI runs the same with gcc and with clang.++Run the fuzz targets+--------------------++The fuzz targets cover the parsers of input from outside the host. They+need clang with its libFuzzer runtime, ``libclang-rt-21-dev`` on the CI+runner.++1. Build and run every target on its seed corpus for 60 seconds each:++ .. code-block:: console++ $ make -C testing fuzz FUZZ_SECONDS=60++2. Run one target again, for example after a fix:++ .. code-block:: console++ $ sh testing/fuzz/run.sh 60 <target>++ ``<target>`` is the name of ``testing/fuzz/fuzz-<target>.c``, such as+ ``json``.++``FUZZ_JOBS`` sets how many targets run at a time, one per CPU by+default. A crash fails the run and leaves its input in+``testing/fuzz/crash-<target>-*``.++Use the test VM+---------------++The test VM plays a production target. It boots a test kernel, an+Ubuntu cloud image and a software TPM, and runs ``init`` from a dracut+initrd with the dm-verity runtime image and a signed config image. The+family runs, the end-to-end run and the interactive VM all boot it.++Build the test kernel+~~~~~~~~~~~~~~~~~~~~~++``make -C testing kernel`` builds bpf-next with the slim configuration+in ``testing/vm/build-kernel.sh`` and the patches under ``kernel/``. It+writes the kernel image, ``vmlinux.btf``, ``kernel.config``, packages+and a record of the commit it built to+``artifacts/bpf-next-kernel-debs/``. Every target that boots a VM+builds the kernel first when it is missing.++1. Build the kernel:++ .. code-block:: console++ $ make -C testing kernel++2. Verify the commit it built:++ .. code-block:: console++ $ grep '^commit=' artifacts/bpf-next-kernel-debs/bpf-next-kernel-build++The stamp is ``artifacts/bpf-next-kernel-debs/bzImage.sha256sum``+(``Image.sha256sum`` on arm64). Make rebuilds the kernel when+``testing/vm/build-kernel.sh`` or a patch under ``kernel/`` is newer+than the stamp, so a checkout or rebase that touches either rebuilds+it on the next VM run. When you know the kernel is current, touch the+stamp, as ``.github/scripts/tests.sh`` does. The build removes the+artifact directory first, so do not run it while a VM run or a build+reads ``vmlinux.btf``.++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Variable+ - Effect+ * - ``KERNEL_TAG=v<version>``+ - Builds a release instead of bpf-next, v7.4 or newer, into+ ``artifacts/linux-v<version>-kernel-debs/``.+ * - ``KERNEL_COMMIT=<sha>``+ - Builds an exact commit of a release tag. Not for bpf-next.+ * - ``KERNEL_SOURCE_DIR=<dir>``+ - Builds from a clean git checkout instead of a fresh clone.+ * - ``KERNEL_CONFIG=<file>``+ - Starts from a full configuration instead of the slim fragment.+ * - ``KERNEL_PATCHES=<dir>``+ - Applies these patches instead of ``kernel/``.+ * - ``KERNEL_BUILD_JOBS=<n>``+ - Parallel jobs, ``nproc`` by default.+ * - ``WORK_DIR=<dir>``+ - The build directory, read from the environment.+ ``/tmp/<name>-kernel-build`` by default.++``make -C testing bpf-next`` rebuilds bpf-next without looking at the+stamp. The kernel build installs missing build dependencies with+``apt-get`` or ``dnf``, through ``sudo`` when it does not run as root.++Build the bundle+~~~~~~~~~~~~~~~~++The bundle is the operator's side of a VM run: shirudo built for the+target, the test helpers, the upatch fixtures signed with keys+generated for the bundle, the dm-verity runtime image and the signed+config images. ``testing/vm/build-bundle.sh`` builds the bpf-next+bundle into ``build/test-vm/host-bundle-bpf-next-verity/`` and keeps+the signing key in+``build/test-vm/host-bundle-bpf-next-verity.operator/keys/``.+Every target that boots a VM rebuilds the bundle when one of its inputs+changed. Build it alone with:++.. code-block:: console++ $ make -C testing bundle++Boot an interactive VM+~~~~~~~~~~~~~~~~~~~~~~++1. Boot a VM and leave it running:++ .. code-block:: console++ # make -C testing vm VM_NAME=<name>++ ``<name>`` names the VM state directory+ ``build/test-vm/vms/<name>/``. Without ``VM_NAME`` the script picks a+ unique name and prints it. ``KERNEL=7.4`` boots a release kernel+ instead of bpf-next and builds it if needed.++2. Open a shell on it:++ .. code-block:: console++ # make -C testing vm-ssh VM_NAME=<name>++ Without ``VM_NAME``, ``vm-ssh`` connects to the most recently created+ VM.++3. Verify that the guest is an initialized target:++ .. code-block:: console++ target# shirudo-runtime status++4. Attach to the serial console when SSH does not answer. ``Ctrl-]``+ detaches:++ .. code-block:: console++ # make -C testing vm-console VM_NAME=<name>++5. Stop the VM and keep its state, or remove its state and logs:++ .. code-block:: console++ # make -C testing vm-stop VM_NAME=<name>+ # make -C testing vm-clean VM_NAME=<name>++.. warning::++ Without ``VM_NAME``, ``vm-clean`` removes the whole+ ``build/test-vm/`` directory, the bundles and the cached runtime+ image included. Name the VM to remove only its state.++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Variable+ - Effect+ * - ``TEST_VM_CPUS``, ``TEST_VM_MEMORY``, ``TEST_VM_DISK_SIZE``+ - 4 CPUs, ``4G`` and ``30G`` by default.+ * - ``TEST_VM_SSH_PORT=<port>``+ - The host port for SSH. A free port from 22000 to 22999 by+ default.+ * - ``TEST_VM_QEMU=<path>``+ - Another emulator, such as RHEL's ``/usr/libexec/qemu-kvm``.+ * - ``TEST_VM_TIMEOUT=<seconds>``+ - How long a test-mode VM may run, 3600 by default. CI sets 900.+ * - ``TEST_VM_VERBOSE=1``+ - Streams the console of a test-mode VM to the terminal.++Inside the guest:++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Path+ - Contents+ * - ``/usr/local/bin/shirudo-runtime``+ - The command that runs the runtime image's binary, which holds+ task authority. ``/usr/local/bin/shirudo`` is a copy outside the+ image and has none.+ * - ``/workspace/shirudo``+ - The checkout, as an overlay over the read-only host checkout at+ ``/mnt/shirudo-src``. Writes stay in the VM.+ * - ``/mnt/shirudo-bundle``+ - The bundle: signed upatch fixtures in ``fixtures/``, image+ fixtures in ``verity/``.+ * - ``/mnt/shirudo-out``+ - The result share, ``build/test-vm/vms/<name>/result/`` on the+ host.++.. _testing-by-hand:++Run a target test by hand+~~~~~~~~~~~~~~~~~~~~~~~~~++1. On the interactive VM, change to the tests:++ .. code-block:: console++ target# cd /workspace/shirudo/testing++2. Set the environment a family run sets:++ .. code-block:: console++ target# export SHIRUDO_BIN=/usr/local/bin/shirudo-runtime+ target# export SHIRUDO_TEST_FIXTURES_DIR=/mnt/shirudo-bundle/fixtures+ target# export SHIRUDO_TEST_KEY_FIXTURES=/mnt/shirudo-bundle/verity++3. Run one test, or all target tests of a family. The ``image`` tests+ need the result directories that ``run-target-tests.sh`` sets, so+ run that family through the script:++ .. code-block:: console++ target# sh functional/<family>/<test>.sh+ target# ./run-target-tests.sh <family>++The interactive VM differs from a family's VM. It starts the+map-export, keepalive and package timers, and it keeps whatever the+tests you ran in it before loaded or left in sealed state. Run the+family with ``make -C testing functional/<family>`` for the verdict CI+gives.++Read the VM logs+~~~~~~~~~~~~~~~~++Each VM keeps its state under ``build/test-vm/vms/<name>/``. A family+VM is named ``test-<family>-<suffix>``, or ``<name>-<family>`` when you+set ``VM_NAME``.++.. list-table::+ :header-rows: 1+ :widths: 36 64++ * - File+ - Contents+ * - ``console.log``+ - The guest's serial console.+ * - ``qemu.log``+ - QEMU's own output.+ * - ``result/guest.log``+ - What the guest preparation and the tests printed.+ * - ``result/failed-tests``, ``result/failed-suites``+ - The test cases and scripts that failed.++A run that passed keeps its logs and drops its disk images. A run that+failed keeps its disks too, copies its logs to+``build/test-vm/logs/<name>/`` and prints where they are. Its guest+overlay holds an ephemeral signing key, so do not share the state+directory.++Run the end-to-end tests+------------------------++``make -C testing end2end`` runs ``t9001`` on the host, then+``testing/end2end/host.sh`` plays the operator around one VM. It starts+an OCI registry and an OpenTelemetry Collector in Docker containers,+pinned by digest and behind a throwaway CA. It builds ``kernel-obs``+into a package with ``bpm build``, pushes it with ``bpm push`` and+appends it to a signed upatch tree with ``bpm tree append``. The target+activates a signed config that points at the tree and the collector,+and its units pull, verify, load and export. The host then verifies the+target's TPM evidence with ``attest verify`` and checks that the+collector holds the package's records.++.. code-block:: console++ # make -C testing end2end++The host side writes to ``build/test-vm/end2end/``. The guest reaches+the containers through QEMU's address for the host.++Write a test+------------++Put a test in the lowest tier that can show the change works:++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - The change touches+ - The test goes in+ * - A function in ``util/<m>.c``+ - ``testing/unit/<m>.c``+ * - A command, a mechanism or an attack on one+ - The family that owns it, as an operator test if it needs no root,+ kernel or TPM, otherwise as a target test+ * - A whole delivery path+ - ``testing/end2end/``+ * - A parser of input from outside the host+ - A fuzz target in ``testing/fuzz/``, besides the functional test+ * - A script in ``.github/scripts/``+ - ``testing/ci-checks/``++Write a unit test+~~~~~~~~~~~~~~~~~++``testing/unit/<m>.c`` calls the functions of ``util/<m>.c`` and checks+them with the macros of ``unit.h``: ``EXPECT_*`` records a failure and+continues, ``ASSERT_*`` ends the case. List every case in the table,+which ends with an empty entry:++.. code-block:: c++ static void decode_refuses_non_hex(void)+ {+ __u8 out[1];++ EXPECT_EQ(hex_decode("zz", out, 1), -EINVAL);+ }++ static const struct unit_case cases[] = {+ UNIT_CASE(decode_refuses_non_hex),+ {}+ };++ UNIT_SUITE(hex, cases);++A case left out of the table is an unused static function, which fails+the build. Each case runs in a child process with a 60-second limit, so+a crash, a sanitizer report or a hang fails that case alone.+``unit_skip()`` skips a case with a reason. The suite links the util+objects from an archive and needs no build rule of its own.++Write a shell test+~~~~~~~~~~~~~~~~~~++1. Create ``testing/functional/<family>/t<F><K><NN>-<what>.sh`` with the+ next free number.++2. Start it from ``testing/`` and source the harness. An operator test+ sources ``test-lib.sh``:++ .. code-block:: sh++ #!/bin/sh+ # SPDX-License-Identifier: BSD-2-Clause+ # Copyright (c) 2026 Authors of shirudo+ #+ # t<F>0<NN> -- <what the test shows>.++ cd "$(dirname "$0")/../.."+ . ./test-lib.sh++ SHIRUDO=${SHIRUDO:-../shirudo}+ [ -x "$SHIRUDO" ] || test_skip_all "shirudo not built"++ WORK=$(mktemp -d)+ trap 'rm -rf "$WORK"' EXIT++ test_expect_success '<what this case shows>' '+ "$SHIRUDO" version >"$WORK/out"+ '++ test_done++ A target test sources ``integration-lib.sh`` instead and calls+ ``target_guard``, which requires root, ``$SHIRUDO_BIN`` and an+ attached LSM:++ .. code-block:: sh++ cd "$(dirname "$0")/../.."+ . ./integration-lib.sh+ target_guard++ require_loaded shirudo-test-basic ||+ test_skip_all "cannot load the basic fixture"++3. Run the family and check that the test ran and passed:++ .. code-block:: console++ # make -C testing functional/<family>++A target test finds loaded only what its family loaded, because each+family boots a VM of its own. ``require_loaded <fixture>`` loads a+signed fixture from the bundle unless it is loaded. State under+``/var/lib/shirudo`` is sealed, so a test cannot remove it, and the+tests of a family see what the earlier ones left there.++``test-lib.sh`` runs under ``set -eu``. Guard every step of an ``EXIT``+trap with ``|| true``, or the first failing step ends the cleanup and+the script fails although every case passed.++Add a fixture or a helper+~~~~~~~~~~~~~~~~~~~~~~~~~++- A target test loads BPF only from signed fixtures. Put the source in+ ``testing/fixtures/<name>.bpf.c`` and add a line+ ``build_fixture <name>.bpf.c <fixture> "$FIXTURE_WORK/trusted"`` to+ ``testing/vm/build-bundle.sh``. The bundle signs it on the build host+ and the guest finds it as+ ``$SHIRUDO_TEST_FIXTURES_DIR/<fixture>.upatch``.+- A compiled helper goes in ``testing/helper/<name>.c`` with a build+ rule in ``Makefile.shirudo`` and an entry in ``TEST_HELPERS``. A+ helper that a target test runs also goes in the list of helpers that+ ``testing/vm/build-bundle.sh`` copies into the bundle. A Python+ helper needs none of this.+- A fuzz target goes in ``testing/fuzz/fuzz-<name>.c`` with a seed+ corpus in ``testing/fuzz/corpus/<name>/`` and a rule in+ ``Makefile.shirudo`` that names the sources it links.++Next steps+----------++- :doc:`test-coverage` for what each family covers and what no test+ covers.+- :doc:`/upatches/testing` to test a upatch on a target.+- :doc:`contributing` before you send the change.diff --git a/Documentation/contribute/writing-docs.rst b/Documentation/contribute/writing-docs.rstnew file mode 100644index 00000000..f7ae1818--- /dev/null+++ b/Documentation/contribute/writing-docs.rst@@ -0,0 +1,239 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: shirudo contributors++Writing documentation+=====================++These rules keep the documentation accurate, consistent and easy to+read. They apply to every page under ``Documentation/``. When the code+and a page disagree, the code is right and the page is a bug.++Readers+-------++Every page serves one of four readers. State which one in the page+metadata, and write for that reader.++Operators+ DevOps and SecOps engineers who deploy, run and troubleshoot targets.+ They are often in the middle of a task or an incident, and they scan.++upatch authors+ Engineers who turn a kernel fix or an observation into a signed+ upatch and ship it as a package.++shirudo contributors+ Developers who change shirudo itself, its tests and its build.++Kernel developers and security reviewers+ Readers who need to understand the design, the kernel interfaces it+ relies on and the threat model well enough to judge them.++Page types+----------++Each page has exactly one type. Do not mix types on one page; link to+the other page instead.++.. list-table::+ :header-rows: 1+ :widths: 18 82++ * - Type+ - Purpose and voice+ * - Tutorial+ - Teaches by doing, from a clean start to a working result. Second+ person, numbered steps, a short explanation of what each step+ achieved.+ * - How-to+ - Gets one task done. Second person and imperative mood. Before you+ begin, numbered steps with one action each, a verify step, next+ steps.+ * - Explanation+ - Builds understanding of a concept, a mechanism or a design+ decision. Explanatory prose: the problem, why the obvious approach+ fails, the mechanism, its limits. "We" means the design.+ * - Reference+ - States facts to look up: commands, options, formats, settings,+ events, errors. Tables and exact syntax, no narrative.++Operator pages, procedures, troubleshooting, the CLI reference and the+cheat sheet are written as how-to or reference pages. Concepts, internals+and design rationale are explanation pages.++Explanation pages+~~~~~~~~~~~~~~~~~++Explain one thing at a time, in short paragraphs that each carry one+idea and open with it. Walk the reader from the problem to the mechanism:+what goes wrong without it, why the first approach that comes to mind+does not work, what the mechanism does, and where it stops. Number figures+and refer to them from the text. Put asides in footnotes. This is the+documentation of an infrastructure project, not a textbook: no quizzes,+no epigraphs, no exercises.++Threat model entries+~~~~~~~~~~~~~~~~~~~~++Each threat is an explanation followed by a fact box, a field list with+the ``facts`` class:++.. code-block:: rst++ .. rst-class:: facts++ :Adversary: ADV-B, root on the target without the signing key+ :Enforced at: ``lsm/bpf``, ``inode_unlink``, ``sb_umount``+ :Refusal: ``EACCES`` from the denied system call+ :Counters: ``BpfCommand``, ``PinUnlink``, ``BpffsUmount``+ :Tests: ``t6106``, ``t6107``, ``t6120``+ :Residual: R3++Name only hooks, counters and tests that exist. ``make -C Documentation+check`` verifies them against the tree.++Page metadata+-------------++Every page starts with the SPDX comment and two metadata fields, before+the title. The theme shows them as one line under the title.++.. code-block:: rst++ ..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++ :page-type: How-to+ :audience: Operators++ Respond to a tampered target+ ============================++Use ``Tutorial``, ``How-to``, ``Explanation`` or ``Reference`` for+``:page-type:``. Index pages of a section carry no metadata.++Titles and headings+-------------------++- Write titles and headings in sentence case: "Boot integration", not+ "Boot Integration".+- Do not start a title with "The", and do not use the "Topic: detail"+ form. Write "Signed loader path", not "The signed-loader path", and+ "Seal labels and task marks", not "The seal: labels and task marks".+- Name how-to pages with a verb and an object: "Rotate a signing key".+ Name explanation and reference pages with a noun phrase.+- Do not number headings. The navigation gives the order.+- Use ``=`` under the page title, ``-`` for sections and ``~`` for+ subsections. Split a page rather than going deeper.+- The title of a page and its entry in the navigation are the same text.++Words+-----++- Write American English: initialize, behavior, license.+- shirudo and upatch are always lowercase, also at the start of a+ sentence or in a heading. Rephrase a sentence rather than capitalize+ them.+- Use one term for one concept and define it in the+ :doc:`/concepts/glossary`. Link the term with ``:term:`` where a reader+ may not know it.+- Write in the present tense and the active voice, and name the actor:+ "The kernel verifies the loader's signature", not "The signature is+ verified".+- Describe what exists. Change history, bug stories and "now" or "new"+ belong in commit messages, not in the documentation.+- Prefer short sentences with one idea each. Do not chain clauses with+ semicolons in procedures and reference pages.+- Leave out filler words such as "simply", "just", "easily", "obviously"+ and "please", and Latin abbreviations such as "e.g.", "i.e." and "etc.".+- Do not use italics or bold for emphasis. Write the sentence so the+ important part comes first.+- Every security claim names its mechanism and its limit, and links the+ residual risk if there is one. Do not write "secure", "tamper-proof" or+ "guarantees" without the mechanism.+- No emojis and no marketing language.++Literals and code+-----------------++- Format every literal as inline code: commands, options, file names,+ paths, keyrings (``.bpf``), extended attributes, units, failure+ categories (``tampered``), hooks, kernel symbols and Kconfig options.+- Write command examples as ``console`` blocks. The prompt says where the+ command runs: ``operator$`` on the operator host, ``target#`` as root+ on a target, ``$`` and ``#`` for anything else. The copy button leaves+ prompts and output out.++ .. code-block:: rst++ .. code-block:: console++ operator$ shirudo attest verify --evidence=ev.json --nonce=$NONCE \+ --ak-name=<ak-name> --cert=signer.der --upatch=fix.upatch+ target# shirudo status++- Put one shirudo command in a block unless the commands only make sense+ together. Introduce each block with a sentence that ends in a colon.+- Write placeholders as ``<lowercase-words>`` and say what each one is.+ Use long option forms, with ``=`` where the parser requires it.+- Show real output, copied from a run in the test VM, with timestamps and+ host-specific values removed. Run every command a page shows in the+ test VM before the page lands.++Links and cross-references+--------------------------++- Link pages with ``:doc:`` and sections with ``:ref:``. Give a section a+ label only when another page links to it.+- Link text is the title of the target, or a phrase that names it. Never+ "here" or "click here".+- Collect further reading at the end of a page under "Next steps" or+ "Related", not in the middle of a procedure.+- State a fact once and link to it. The CLI reference, the formats and+ the failure categories are the single home of what they describe.++Admonitions+-----------++Use ``.. warning::`` only for an action that breaks the trust model,+locks out a target or cannot be undone, and say why and what to do+instead. Use ``.. note::`` rarely. Never put two admonitions in a row and+never open a page with one.++Tables and figures+------------------++- Prefer ``list-table`` for tables, with a header row.+- Put figures as SVG under ``Documentation/images/`` and include them with+ ``.. figure::``. Number them in the caption ("Figure 1.") and refer to+ them from the text before they appear.++Building and checking+---------------------++Render and serve the documentation on ``http://127.0.0.1:8000``:++.. code-block:: console++ $ make docs++Render it and check it against the code, as CI does:++.. code-block:: console++ $ make -C Documentation check++The build turns every Sphinx warning into an error. The check verifies+that the commands, options, failure categories, tamper counters, hooks,+tests and units a page names exist in the tree.++Related+-------++- :doc:`contributing` for commit messages and the sign-off.+- :doc:`coding-style` for the C code.diff --git a/Documentation/developer-guide.rst b/Documentation/developer-guide.rstdeleted file mode 100644index bab4416c..00000000--- a/Documentation/developer-guide.rst+++ /dev/null@@ -1,220 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--Developer guide-===============--This guide is for working on shirudo itself: building and running it from a-checkout, where the operator-only tools live, and writing and running the-tests. See `requirements <requirements.rst>`__ for what the build and test-hosts need, `contributing <contributing.rst>`__ for what to run before-sending a change and `coding-style <coding-style.rst>`__ for the style.--1) Working from a checkout-----------------------------``make`` builds the operator binary ``shirudo``, ``make shirudo-build`` the-operator-only helper and ``make target`` the fully static target binary.-The core binary never compiles or signs: ``shirudo build``, ``keys vouch``-and the operator ``bpm`` commands hand their arguments to-``tools/shirudo-build/shirudo-build`` with ``execv``, found through-``SHIRUDO_BUILD``, then ``$(libexecdir)/shirudo/shirudo-build``, then-``PATH``, and ``shirudo bpm --help`` lists the operator subcommands only-when the helper resolves. From a checkout, put ``tools/shirudo-build`` and-the checkout root first on ``PATH`` or set ``SHIRUDO_BUILD``.--The helper hosts everything that compiles or signs: the ``.bpf.c`` to-``gen_loader`` to signed ``.upatch`` path, unload directives, ``keys-vouch``, ``bpm build``, ``bpm config update``, ``bpm push`` and ``bpm tree-append``, and ``upatch rewrite-rodata``, which re-signs an upatch whose BTF-watch arrays alone changed and which kernel-obs's ``rewrite_watch_upatch.py``-calls. ``bpm build`` compiles with the package directory as its working-directory, so a package built from a checkout finds ``vmlinux.h`` and the-BPF headers through ``vendor`` and ``bpf`` links to the checkout's, as-``testing/end2end/host.sh`` and the publishing test make them.--``tools/gen-image/`` holds the image scripts the helper and ``shirudo image-build`` run: ``shirudo-gen-image`` makes an ext4 image of a source tree,-``shirudo-gen-runtime`` collects the trusted binary, its libraries and the-public assets for the runtime image, ``shirudo-gen-verity`` formats the-hash tree and has the helper sign the root, and ``common.sh`` holds their-shared checks. The ``runtime-service*.conf.in`` templates beside them-belong to ``shirudo-gen-runtime``. `config-images <config-images.rst>`__-describes the images they make.--2) The test layout---------------------shirudo is tested in tiers, each under its own directory of ``testing/``:-unit tests for the functions of ``util/``, functional tests for one command-or mechanism at a time, end-to-end tests for whole delivery paths, tests of-the scripts CI runs, and libFuzzer targets for the parsers of input from-outside the host. A change comes with a test in the lowest tier that can-show it works.--::-- testing/- unit/ unit tests, util/<m>.c by unit/<m>.c- ci-checks/ the scripts under .github/scripts- functional/<family>/ one command or mechanism at a time- end2end/ whole delivery paths on a test VM- fuzz/ libFuzzer targets and seed corpora- fixtures/ BPF programs, decoders and configs the- tests build from- helper/ C and Python helpers the tests run- vm/ the test VM: kernel, bundle, guest- test-lib.sh the TAP harness of the shell tests- integration-lib.sh shared setup of the target tests- run-tests.sh the unit and operator tests- run-target-tests.sh one family's target tests, in its VM--3) Test numbers------------------A shell test is named ``t<F><K><NN>-<what>.sh``, the way git numbers its-test families:--* ``F`` is the family, and with it the directory;-* ``K`` is ``0`` for an operator test, which runs on the build host and- needs no root, kernel or TPM of its own, and ``1`` for a target test,- which runs as root in the test VM against an initialised target;-* ``NN`` orders the tests of a family, and is the order they run in.--=== ============================ ==========================================-F Directory What it covers-=== ============================ ==========================================-0 ``ci-checks/`` DCO, SPDX, style, commit range, SBOM-1 ``functional/build/`` dispatch, static target, packaging,- initrd installer, the test VM scripts-2 ``functional/signing/`` keys, signatures, the trusted set-3 ``functional/upatch/`` the container, build metadata, load,- unload, serializers-4 ``functional/tpm/`` the register, eventlog, attestation and- initrd binding-5 ``functional/image/`` runtime and config images, activation,- revocation, interruption-6 ``functional/tamperproof/`` attacks on the LSM, the seal, the- keyrings, bpffs and the TPM path-7 ``functional/bpm/`` packages, repositories, the upatch tree-8 ``functional/otel/`` map export, status, TLS policy-9 ``end2end/`` the kernel-obs package, delivery paths-=== ============================ ==========================================--A new test takes the next free number of its family and kind; a number is-not reused for a different test. A file under ``testing/`` that is not a-test does not take a name of this form.--4) Running the tests-----------------------``make tests`` or ``make -C testing``- Runs every test, tier by tier: ``unit``, ``ci-checks``, ``functional``- and ``end2end``. CI runs the same.--``make -C testing <tier>``- Runs one tier. ``unit/<suite>`` runs one unit suite and- ``functional/<family>`` one family; ``make -C testing help`` lists- them. The unit tests and the ``ci-checks/`` tests run on the build- host.--A functional or end-to-end tier runs its operator tests first, in number-order, then its target tests: each family boots a VM of its own from one-bundle, through the production path, the dm-verity runtime and the signed-config from a dracut initrd. The tpm family also boots a VM before-``init``, without the production initrd, for the TPM register tests. The-VMs need root, and ``make -j`` boots several side by side. A VM that-passed keeps its logs and drops its disks; one that failed is kept under-``build/test-vm/vms/`` for inspection.--``VM=0`` leaves out the tests that boot a VM, for a host without KVM or-root; ``make tests VM=0 SANITIZE=address,undefined`` builds and runs the-rest under ASan and UBSan, as CI does.--``make -C testing fuzz [FUZZ_SECONDS=60]``- Runs every libFuzzer target on its seed corpus under ASan and UBSan.--``make -C testing vm``- Boots an interactive VM with a prepared shirudo, for running a test by- hand.--In CI, the tests workflow runs ``make tests`` and the sanitizer workflow-``make tests VM=0`` under ASan and UBSan with gcc and clang.--5) Unit tests----------------``testing/unit/<m>.c`` tests the functions of ``util/<m>.c``. It calls them-directly and checks the results with the assertions of ``unit.h``:-``EXPECT_*`` records a failure and goes on, ``ASSERT_*`` ends the case.-Each case is a ``static void`` function named for what it shows, and the-file lists its cases in one table that ends with an empty entry::-- static void decode_refuses_non_hex(void)- {- __u8 out[1];-- EXPECT_EQ(hex_decode("zz", out, 1), -EINVAL);- }-- static const struct unit_case cases[] = {- UNIT_CASE(decode_refuses_non_hex),- {}- };-- UNIT_SUITE(hex, cases);--A case left out of the table is an unused static function, which the-build refuses. Each case runs in a child of its own, so a crash, a-sanitizer report or a hang fails that case alone; the case's stderr comes-back as TAP diagnostics when it fails, and ``unit_skip()`` skips it with a-reason. The tests link the util objects from an archive, so a test pulls-in only what its module needs and needs no build rule of its own.--A change to a function of ``util/`` adds or updates its cases. What needs-the command line, root, the TPM simulator, the kernel or an implementation-written apart from shirudo to compare against is a functional test.--6) Functional and end-to-end tests-------------------------------------A shell test starts in ``testing/``, sources ``test-lib.sh``, and runs its-cases with ``test_expect_success``; ``test_skip_all`` skips the whole script-when a prerequisite is missing. It works in a scratch directory of its own-and writes nothing into the tree.--A target test also sources ``integration-lib.sh`` and calls-``target_guard``. Its family's VM was booted for that family alone, so it-finds loaded only what its family loaded; ``require_loaded <name>`` loads a-signed fixture of the bundle that a test needs. A target test that skips-as a whole fails its family, since every one of them is required.--The end-to-end tests in ``end2end/`` run a shipped package against real-kernel activity and follow it out through the export path, and the last of-them, ``t9105-delivery``, takes the whole delivery path. Around its VM,-``end2end/host.sh`` plays the operator: it starts an OCI registry and an-OpenTelemetry Collector in containers, pinned by digest, behind a-throwaway CA; builds kernel-obs into a package with ``bpm build``, pushes-it with ``bpm push`` and appends it to a signed upatch tree with ``bpm-tree append``, all with the key the bundle's fixtures are signed with.-The target activates the signed ``config-end2end`` image that points at-the tree and the collector, and the units it ships pull, verify and load-the package and export what it observes. The host then verifies the TPM-evidence the target produced with ``attest verify``, whose replayed records-must name the published payload and tree operation, and checks that the-collector holds the package's records. The registry and the collector need Docker on the-host; the guest reaches them through QEMU's address for the host.--7) The test VM-----------------``testing/vm/`` builds and runs the target side. ``build-kernel.sh``-builds the test kernel from bpf-next or a release tag with the slim-configuration and the patches under ``kernel/``. ``build-bundle.sh``-builds the operator side: shirudo, the helpers, the signed upatch fixtures,-the dm-verity runtime image and the signed config images, which-``image-fixtures.sh`` and ``bundle-images.sh`` produce. ``run.sh`` boots a-guest with a software TPM and the bundle and, in test mode, has-``guest.sh`` run one family's tests in it. ``testing/swtpm.sh`` runs a-software TPM on the host for development without a VM.diff --git a/Documentation/features.rst b/Documentation/features.rstdeleted file mode 100644index fc42a8c8..00000000--- a/Documentation/features.rst+++ /dev/null@@ -1,275 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--Features: what a upatch can attach to-=====================================--A upatch is a signed loader that installs one or more BPF programs and-attaches each one where its section name says. This document lists-every attachment kind shirudo supports, what the kernel does at that-point, how the loader attaches there, what the author writes and what-the target needs, and then the two program roles that attach nowhere.-The `upatch <upatch.rst>`__ guide covers writing, building and-shipping; the `requirements <requirements.rst>`__ list the kernel-options behind each kind.--Two rules hold for every kind. The attach point is fixed at build-time: the builder reads the section name from the object, records the-kind and the target in the signed metadata, and the signed loader-resolves the BTF target when it loads, so the artifact attaches where-its author said and nowhere else. And every attachment is a BPF link-pinned in shirudo's private bpffs (``link`` for a single program,-``link_0``, ``link_1`` and so on for several): the pin is what keeps-the program attached once the one-shot command has exited, the-enforcement programs stop anyone but shirudo from removing it, and an-unload is a signed directive that removes the pins. Section names-whose attachment cannot be a pinnable link are refused by the builder,-which is why plain ``socket`` filters and ``sk_skb`` programs are not-in the list.--1) Kernel functions: fentry, fexit, fmod_ret-----------------------------------------------``SEC("fentry/<function>")`` runs the program when the kernel enters-the function, with the function's arguments; ``SEC("fexit/<function>")``-runs it on return, with the arguments and the return value;-``SEC("fmod_ret/<function>")`` runs it on entry and, when the program-returns non-zero, skips the function body and returns that value to-the caller. All three go through the BPF trampoline the kernel-generates for the function from its BTF, and all three need the-function to be visible in BTF: ``fentry`` and ``fexit`` work on any-such function the kernel allows tracing programs to attach to, while-``fmod_ret`` is restricted to the ``security_*`` LSM hooks and to-functions marked ``ALLOW_ERROR_INJECTION``, which needs-``CONFIG_FUNCTION_ERROR_INJECTION`` and ``CONFIG_BPF_KPROBE_OVERRIDE``-beyond the hooks.--The loader records the function's BTF id as the program's attach-target at load, so the kernel checks the program's signature of-arguments against the function's. shirudo attaches with-``BPF_LINK_CREATE`` of the trampoline kind and falls back to-``BPF_RAW_TRACEPOINT_OPEN`` on a kernel that does not create links for-it; either way the result is pinned. ``fmod_ret`` is the shape of a-shield that rejects a call before the vulnerable code runs: return-``-EPERM`` or ``-EINVAL`` from the program and the caller sees the-error. ``fmod_ret.s/<function>`` declares the sleepable variant. The-builder refuses a bare ``fmod_ret`` without a function.--2) LSM hooks: lsm--------------------``SEC("lsm/<hook>")`` and ``SEC("lsm.s/<hook>")`` (sleepable) attach a-program to a hook of the Linux Security Module framework, named after-the ``security_<hook>`` function: ``lsm/file_open``,-``lsm/bprm_check_security``, ``lsm/socket_connect``. The kernel calls-the program where it would call an LSM module, with the hook's-arguments and the verdict of the modules before it, and a non-zero-return denies the operation. This is how shirudo's own enforcement-programs work (``bpf/bpf2.c`` and ``bpf/seal.c`` are LSM programs on-``bpf``, ``bpf_prog_load``, ``inode_unlink``, ``key_permission``,-``file_open`` and the mount hooks), and a upatch may use the same-hooks for policy of its own: refuse an ``ioctl``, a mount option or a-path before the vulnerable code sees it.--Attachment is ``BPF_LINK_CREATE`` with ``BPF_LSM_MAC`` on the hook's-BTF, pinned like every other link. The target needs-``CONFIG_BPF_LSM`` and ``bpf`` in the active LSM list, which the base-requirements already demand for shirudo itself, so every target that-runs shirudo accepts LSM upatches. The program's return value matters-only on hooks that return an ``int``; on ``void`` hooks it observes.--3) Tracepoints: tp_btf-------------------------``SEC("tp_btf/<tracepoint>")`` attaches a program to a kernel-tracepoint with its arguments typed from BTF, for example-``tp_btf/sched_process_exec`` or ``tp_btf/inet_sock_set_state``. The-program runs when the tracepoint fires and sees the raw arguments, not-the formatted trace record. Tracepoints are stable observation points-the kernel maintains deliberately, which makes them the first choice-for a detection shield that watches for the pattern of an exploit-without changing the code path.--Attachment is a raw-tracepoint link on the BTF target, pinned. Nothing-beyond the base requirements is needed; the tracepoint must exist in-the target kernel, which CO-RE checks at load and reports as-``btf_mismatch`` when it does not.--4) Probes on kernel functions: kprobe, kretprobe---------------------------------------------------``SEC("kprobe/<symbol>")`` and ``SEC("kretprobe/<symbol>")`` attach to-the entry or the return of any kernel function the kprobe subsystem-can instrument, whether or not it is in BTF or allowed as a trampoline-target. ``kprobe/<symbol>+<offset>`` probes an instruction inside the-function. The program receives the registers as ``struct pt_regs``,-so it reads its arguments through the ``PT_REGS_PARM*`` macros, and a-kprobe may call ``bpf_override_return()`` on functions marked for error-injection, the kprobe route to rejecting a call.--The loader opens a perf event of the ``kprobe`` type for the symbol-and offset, with the retprobe bit set for ``kretprobe``, and attaches-the program to it with ``BPF_LINK_CREATE`` of the perf-event kind; the-link is pinned and the perf event lives as long as the link. The-target needs ``CONFIG_KPROBES`` and ``CONFIG_KPROBE_EVENTS``. The-builder requires the symbol in the section name, refuses-``kprobe.multi`` and ``kretprobe.multi``, and refuses an offset on a-``kretprobe``. A kprobe on a function the target kernel does not-export fails at load with the kernel's error in the report; when the-function is in a module that is not loaded, the report says so and-``bpm`` treats the package as installed but not attached.--5) Probes on userspace binaries: uprobe.multi------------------------------------------------``SEC("uprobe.multi//absolute/path:<glob>")`` attaches a program to-the entry of every function in the named binary whose symbol matches-the glob, for example ``uprobe.multi//usr/bin/example:*Func``. The-program runs in the context of the process executing the function,-sees its registers, and is the way a shield reaches a userspace-library or daemon: a check at the entry of the vulnerable function, a-counter of its callers.--This kind is resolved at build time. The builder opens the binary on-the operator, matches the glob against its symbol table, records every-matching function's file offset and the binary's GNU build ID in the-signed metadata, and refuses a pattern that matches nothing or a binary-without a build ID. On the target the loader opens the path, checks-that it is a regular file whose build ID equals the recorded one and-whose size covers every offset, and attaches with ``BPF_LINK_CREATE``-of the ``uprobe_multi`` kind by file descriptor, so the probes land in-the inode that was checked and not in whatever the path names a moment-later; a kernel without the descriptor form gets the path, after the-same inode check. A binary that differs from the one the operator-built against is refused as stale, never probed at the wrong offsets.-The target needs ``CONFIG_UPROBE_EVENTS``. Return probes, the-single-function ``uprobe/`` form and ``,`` or ``|`` alternation in the-glob are refused by the builder; one ``*`` or ``?`` glob per section.--6) Packets at the cgroup: cgroup_skb---------------------------------------``SEC("cgroup_skb/ingress")`` and ``SEC("cgroup_skb/egress")`` attach a-program to the cgroup v2 root, so it sees every IP packet received by-or sent from any socket on the host, as a ``struct __sk_buff``. The-program returns 1 to let the packet through and 0 to drop it; it can-read the headers and the socket's cgroup, which makes it a host-wide-filter that a shield uses to stop a malformed packet or a known bad-peer before the vulnerable protocol code parses it.--Attachment is ``BPF_LINK_CREATE`` on a descriptor of ``/sys/fs/cgroup``-with ``BPF_CGROUP_INET_INGRESS`` or ``BPF_CGROUP_INET_EGRESS``, pinned.-The target needs ``CONFIG_CGROUP_BPF`` and the unified cgroup-hierarchy mounted at ``/sys/fs/cgroup``, which is systemd's default.-The builder accepts only the two directions spelled out; ``cgroup/skb``-and a bare ``cgroup_skb`` are refused. Several ``cgroup_skb`` programs-on the host coexist; the kernel runs all of them and drops the packet-if any says so.--7) Packets at netfilter: netfilter-------------------------------------``SEC("netfilter")`` attaches a program as a netfilter hook at IPv6-pre-routing, the point where a packet has arrived on an interface and-no routing decision has been made. The program receives a-``struct bpf_nf_ctx`` with the packet and the hook state and returns a-netfilter verdict, ``NF_ACCEPT`` or ``NF_DROP``; it runs before-connection tracking and before defragmentation (priority-``NF_IP6_PRI_RAW_BEFORE_DEFRAG``), so it sees fragments as they arrive,-which is where shields against malformed-fragment and extension-header-bugs belong.--Attachment is ``BPF_LINK_CREATE`` with ``BPF_NETFILTER`` for-``NFPROTO_IPV6`` at ``NF_INET_PRE_ROUTING``, pinned. The target needs-``CONFIG_NETFILTER`` and ``CONFIG_NETFILTER_BPF_LINK``. This is the-one kind whose hook, family and priority are fixed by shirudo rather-than by the section name; a shield that needs another family or hook-is written as a ``cgroup_skb`` or an ``lsm`` program instead.--8) Programs that attach nowhere----------------------------------Two roles are recognised by the program's name and must be in-``SEC("syscall")``, the program type the loader can run on request-with ``BPF_PROG_TEST_RUN``. Neither is attached; both are pinned-under the upatch's directory.--Serializers- ``shirudo_serialize__<map>`` renders ``<map>`` into the upatch's- ``shirudo_ser`` output map as a stream of ``struct- shirudo_serial_chunk`` records, which is how a map of structs or a- per-CPU map becomes a flat record the exporter can ship. ``shirudo- upatch map`` and the map-export timer run it on the target instead- 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 serializer- without the output map, one for a reserved or missing map, and two- for the same map.--Test-run programs- ``shirudo_test__<id>`` is run once by the loader right after the- attachments, with a zero context, which is how a upatch initialises- an arena it shares with its programs; a negative return fails the- load. It is then pinned for the author's own checks. One per- upatch.--Both roles ride inside the signed loader with the attached programs,-so a serializer is as much the operator's code as the shield beside-it, and neither can introduce anything the signature does not cover.--9) Maps and decoders-----------------------Whatever a program attaches to, its maps are declared in-``SEC(".maps")`` as usual. Every map the upatch creates is pinned-under ``upatches/<name>/maps/`` in the private bpffs, readable with-``shirudo upatch map <name> <map>`` and exportable to a collector-through a Lua decoder signed inside the upatch; a map whose name starts-with ``obs_i_`` is private to the upatch and neither pinned for the-operator nor exported. The metadata the loader needs rides in frozen-array maps the builder creates. The `telemetry <telemetry.rst>`__-document describes the export and the decoder API.--10) At a glance------------------.. list-table::- :header-rows: 1- :widths: 24 30 46-- * - Section- - Attaches through- - Needs beyond the base kernel- * - ``fentry/<fn>``, ``fexit/<fn>``- - trampoline link on the BTF target- - nothing- * - ``fmod_ret/<fn>``, ``fmod_ret.s/<fn>``- - trampoline link, ``BPF_MODIFY_RETURN``- - error injection for functions outside the ``security_*`` hooks- * - ``lsm/<hook>``, ``lsm.s/<hook>``- - link with ``BPF_LSM_MAC``- - nothing- * - ``tp_btf/<tracepoint>``- - raw-tracepoint link on the BTF target- - nothing- * - ``kprobe/<sym>[+off]``, ``kretprobe/<sym>``- - perf event of the kprobe type, perf-event link- - ``CONFIG_KPROBES``, ``CONFIG_KPROBE_EVENTS``- * - ``uprobe.multi//path:<glob>``- - ``uprobe_multi`` link by file descriptor, build ID checked- - ``CONFIG_UPROBE_EVENTS``- * - ``cgroup_skb/ingress``, ``cgroup_skb/egress``- - link on the cgroup v2 root- - ``CONFIG_CGROUP_BPF``- * - ``netfilter``- - ``BPF_NETFILTER`` link, IPv6 pre-routing- - ``CONFIG_NETFILTER``, ``CONFIG_NETFILTER_BPF_LINK``- * - ``syscall`` (serializer, test-run)- - not attached; run on request- - nothing--Everything else, including ``socket``, ``sk_skb``, ``uprobe``,-``uretprobe``, ``kprobe.multi``, ``cgroup/skb`` and ``xdp``, is refused-by ``shirudo build`` with a message naming the supported form.diff --git a/Documentation/getting-started.rst b/Documentation/getting-started.rstdeleted file mode 100644index d4bfd894..00000000--- a/Documentation/getting-started.rst+++ /dev/null@@ -1,425 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--Getting started-===============--This guide takes one operator host and one target from a source-checkout to a loaded, measured upatch, and then to packages pulled from-a registry. Commands shown with ``sudo`` run on the target as root;-the others run on the operator as the user who owns the signing key.-`requirements <requirements.rst>`__ lists what each host needs; read it-before selecting the target kernel: the validated baseline is an upstream-development-tree commit with the signed-loader ABI, BPF LSM, BTF and ML-DSA-support. A release number alone is not enough. For local development one-host can play both roles.--Targets require runtime and signed config images. Follow-`config-images <config-images.rst>`__ for generation and authenticated boot.-Writable state keeps its xattr protection and all BPF upatches remain signed.-The target commands below denote the generated runtime loader invocation;-operator commands use the ordinary host executable.--1) Build-----------From the checkout::-- make # the operator-profile shirudo binary- make shirudo-build # the operator-only build and publish helper- make target # the target binary, shirudo-target- make tests # every test, the target ones in VMs (root)- make tests VM=0 # without the VMs: no root, LSM or TPM- make tests VM=0 SANITIZE=address,undefined- # the same under ASan and UBSan--``make`` probes the toolchain and libraries and refuses an OpenSSL-older than 3.5. ``make target`` first runs ``make target-deps``, which-builds a static OpenSSL, libcurl and tpm2-tss from source; the build-host must also provide static ``libelf``, ``zlib``, ``zstd`` and-LuaJIT archives, with-``SHIRUDO_TARGET_STATIC_LIBDIR`` naming their directory when it is not-the system one. ``make help`` summarizes shared targets; the package and-test Makefiles have their own help targets.--Installable packages::-- make -C packaging bintar-pkg # tarballs with an install.sh- make -C packaging bindeb-pkg # shirudo-target and shirudo-operator .deb- make -C packaging binrpm-pkg # the same two packages as RPMs--``PKG_ROLES=target`` or ``PKG_ROLES=operator`` builds one of them; the-operator package links the host's shared libcurl and must be built on-the distribution it is installed on, while the target package is-self-contained. ``make install-target`` and ``make install-operator``-install one role straight from the tree. The target package carries-the ``shirudo`` binary, the systemd units and timers, and the default-configuration; the operator package adds ``shirudo-build`` and needs-clang on the host. Neither ``shirudo-build`` nor clang ever ships to-a target.--When working from a checkout instead of an installed package, the core-binary must be able to find ``shirudo-build`` for operator commands.-Set ``SHIRUDO_BUILD`` to the helper, or put both the helper directory-and the checkout root on ``PATH``::-- export SHIRUDO_BUILD="$PWD/tools/shirudo-build/shirudo-build"- # Or, instead:- export PATH="$PWD/tools/shirudo-build:$PWD:$PATH"--The operator-only BPM commands are advertised only when the helper is-available. If ``shirudo bpm --help`` lists only target commands, the-helper was not found; ``bpm build``, ``push`` and ``tree append`` will be-reported as unknown subcommands.--2) Create a signing key--------------------------On the operator::-- sudo shirudo genkey- sudo shirudo keys--``genkey`` writes an ML-DSA-87 (FIPS 204) private key to-``/var/lib/shirudo/keys/signing_key.pem`` (mode 0600) and a self-signed-certificate to ``cert.der`` beside it; ``--keys-dir <dir>`` chooses-another directory and ``--force`` overwrites an existing pair. There-is no other key type. ``keys`` prints the algorithm and fingerprints-of the material on disk and, on a target, the state of the kernel-keyring.--Put the initial public certificate in the runtime image. Never put-``signing_key.pem`` on a target or in either image. Additional BPF signers-need vouches in the signed config selected for boot; enrolling them requires-a reboot. Signed config can revoke an already enrolled signer at runtime.-See `key-lifecycle <key-lifecycle.rst>`__.--3) Build a signed upatch---------------------------From BPF source, or from an already compiled object::-- shirudo build fix.bpf.c- shirudo build fix.bpf.o -o fix.upatch--The default output is the input name with ``.c`` or ``.o`` replaced by-``.upatch``, next to the input. ``shirudo build`` dispatches to-``shirudo-build``, which compiles with ``clang -target bpf -O2 -g``,-generates the signed loader, signs it and writes the container.-Useful options: ``--name <name>`` to override the upatch name,-``--keys-dir <dir>`` (or ``--key`` and ``--cert``) when the key is not-in the default location, ``--vmlinux <vmlinux.h>`` when the default-``vendor/linux/vmlinux.h`` is not the target kernel's,-``--extra-cflags``, and ``--emit-artifacts`` to keep the compiled-``.bpf.o``. Build against BTF from the target kernel generation:-CO-RE relocations make the artifact portable across builds of the same-kernel, not across kernels that renamed a field.--Review before shipping::-- shirudo upatch info fix.upatch- shirudo upatch info --json fix.upatch--``info`` prints the header, the sections, the attach metadata and the-signed decoders. It is an offline view of the file; the program as-the kernel actually loaded it is shown by ``upatch get`` after the-load. The `upatch <upatch.rst>`__ guide covers the BPF side of a-upatch, decoders, serializers and the release workflow.--4) Initialise a target-------------------------Build and provision runtime and config images, install the generated runtime-service drop-in, and build an authenticated UKI as described in-`config-images <config-images.rst>`__ and `initrd <initrd.rst>`__.-Bootstrap settings name the expected runtime root and the reserved config PCR.-Boot with ``bpf.keyring_unsealed=1 dm_verity.keyring_unsealed=1`` and make-writable state available in the initrd. Missing settings or images stop init;-there is no root-only staging configuration.--The initrd verifies the images, seals the keyrings, labels writable state,-attaches every enforcement hook, restores signed upatches and measures startup.-The root service uses the verified runtime to check that state and adopt the-initrd eventlog record. After boot, using the runtime invocation::-- sudo shirudo status --json- sudo shirudo image status- sudo systemctl enable --now shirudo-bpm-repo-update.timer- sudo systemctl enable --now shirudo-keepalive.timer shirudo-map-export.timer--Check ``mode: production``, ``keyring_mode: bpf``, ``tpm.bound_in: initrd``,-consistent config state and an upatch register matching its eventlog. A TPM is-mandatory. The authenticated target uses the kernel TPM device so its-NV extension commands pass through the LSM. Host-side TPM tests can use-a software TPM TCTI; target environment overrides are refused.--5) Load and unload a local artifact--------------------------------------Copy the ``.upatch`` to the target by any means and load it::-- sudo shirudo upatch load fix.upatch- sudo shirudo upatch list- sudo shirudo upatch get fix--A stricter load binds the operation to the state the caller expects::-- chain=$(sudo shirudo status --json | jq -r .tpm.chain)- sudo shirudo upatch load --expect-chain=$chain \- --report=/tmp/fix.json fix.upatch--The value need not come from the target: ``shirudo attest predict---cert cert.der --upatch a.upatch --upatch b.upatch`` computes on the-operator what a target booted with exactly those artifacts must hold.-The load refuses with ``tampered`` if the register moved since the-value was computed, whether by an attacker or by another operator;-take a fresh status and decide again rather than retrying. ``--report`` writes a-JSON document with the phase reached, the failure category, the-verifier log and the chain after the operation.--Unloading needs a signed directive, built on the operator and bound to-the payload it may remove::-- shirudo build --unload fix --payload-sha256 <hex from upatch info>- sudo shirudo upatch unload fix.unload.upatch--Without ``--payload-sha256`` the builder reads the digest from-``/var/lib/shirudo/upatches/fix.upatch`` when that archive exists-locally, and otherwise emits an all-zero digest that makes the target-skip the payload check. The target loads the directive through the-same signature check as a load, compares the live pin's payload against-the directive, detaches, removes the persisted artifact and extends the-chain. Unloading something that is not loaded is ``already_unloaded``-and extends nothing.--6) Packages and registries-----------------------------A package is a directory with a ``<name>.bee`` Beefile next to the BPF sources::-- example-shield/- ├── example-shield.bee- └── shield.bpf.c--Example ``example-shield.bee``::-- [package]- name = "example-shield"- description = "Example BPF shield"- license = "GPL-2.0 OR BSD-2-Clause"- authors = ["Example Org"]-- [[files]]- source = "decoders/exec.lua"-- [[upatches]]- source = "shield.bpf.c"--``[[files]]`` entries are copied into the package (headers, decoders,-reproducers); each ``[[upatches]]`` entry is built and signed, with its-unload directive, through ``shirudo-build``. On the operator::-- shirudo bpm build ./pkg --version 1.0.0 \- -f ./pkg/example-shield.bee --keys-dir /var/lib/shirudo/keys- shirudo bpm info ./example-shield-1.0.0.bee- shirudo bpm push ./example-shield-1.0.0.bee \- oci://quay.io/example/example-shield --keys-dir /var/lib/shirudo/keys--``push`` uploads the package and its certificate and, given the signing-material, adds the version to the registry's signed index at-``shirudo/bpm-index:stable``. Registry credentials come from-``BPM_OCI_USERNAME`` and ``BPM_OCI_PASSWORD``, ``REGISTRY_AUTH_FILE``-or ``DOCKER_CONFIG``; ``BPM_OCI_CA_FILE`` adds a CA and-``BPM_OCI_SCHEME=http`` allows a cleartext local registry.--Put repository definitions and their index certificates in the signed config-image. After activation, install packages or let the timer refresh them::-- sudo shirudo bpm repo update- sudo shirudo bpm install example/kernel-obs- sudo shirudo bpm list- sudo shirudo bpm upgrade- sudo shirudo bpm uninstall kernel-obs--``shirudo bpm install oci://quay.io/example/kernel-obs:1.0.0``-installs a reference directly; the `upatch <upatch.rst>`__ guide has-the Beefile reference and the tree workflow in full. ``bpm info`` prints a package's README-before installing it, from a local ``.bee`` or a reference. ``bpm-uninstall`` loads the unload directives the package shipped.--Packages whose ``Beefile`` entries carry an ``[upatches.tree]`` table-can also be appended to a signed, append-only upatch tree with-selectors, so a fleet of mixed kernels pulls only what applies::-- shirudo bpm tree append ./kernel-obs-1.0.0.bee \- oci://quay.io/example/tree --keys-dir /var/lib/shirudo/keys- shirudo bpm tree append ./kernel-obs-1.0.0.bee \- oci://quay.io/example/tree --keys-dir /var/lib/shirudo/keys --op delete--A target follows a tree when its signed config's-``etc/shirudo/bpm/upatch-tree.conf``-names it (``endpoint=`` and ``reference=``); ``shirudo bpm tree sync-[--dry-run]`` applies the matching operations, and-``shirudo-bpm-tree-sync.timer`` runs it every minute. Node labels for-selectors live in ``/etc/shirudo/node.labels``.--7) Export telemetry----------------------Loaded upatches expose their maps, and shirudo exports them as OTLP-logs and metrics::-- sudo shirudo upatch map --all- sudo shirudo upatch map --all --otel \- --otel-endpoint=https://collector.example:4318- sudo shirudo status --otel --include-system--Set ``map_export.otel_endpoint`` in the signed config's-``etc/shirudo/shirudo.conf`` and-enable ``shirudo-map-export.timer`` and ``shirudo-keepalive.timer`` to-push map snapshots and a status keepalive every five seconds.-`telemetry <telemetry.rst>`__ describes the records, the decoders and-how to land them in ClickHouse, Splunk or a collector of your own.--8) Inspect-------------::-- sudo shirudo status --include-eventlog- sudo shirudo status --json- sudo shirudo upatch list- sudo shirudo upatch get fix- sudo shirudo upatch map fix counters- sudo shirudo config- journalctl -t shirudo--``config`` prints the effective configuration with every key explained.-Every command logs to syslog under the ``shirudo`` tag.--9) Attest a target---------------------``status`` is what the target says about itself. ``attest`` is what-its TPM signs. On the target, with a nonce the verifier chose::-- nonce=$(openssl rand -hex 16)- sudo shirudo attest --nonce=$nonce --out=/tmp/evidence.json--The document carries a quote over the firmware, boot loader, kernel,-initrd and systemd PCRs, a certification of the measurement register,-the attestation key, the endorsement key and its certificate, this-boot's eventlog and the measurement logs. When a target is enrolled,-run it once, record the attestation key name (``jq -r .ak.name-evidence.json``; the same TPM always yields the same key) and make-that key prove where it lives. On the operator::-- shirudo attest challenge --evidence=evidence.json \- --out=challenge.json --ek-ca=tpm-vendor-roots.pem--prints the checks on the endorsement key and its certificate and a-``credential:`` line to keep. Give ``challenge.json`` to the target-and request the next evidence with it::-- sudo shirudo attest --nonce=$nonce --challenge=challenge.json \- --out=/tmp/evidence.json--The target's TPM recovers the credential only if the attestation key-and the endorsement key live in it; pass the value as-``--expect-credential=<hex>`` to ``verify`` below. ``--ek-ca`` names-the manufacturer's issuers the endorsement certificate must chain to;-an endorsement key known from an inventory or a platform's API is-pinned with ``--ek-name`` instead, and ``--trust-presented-ek`` accepts-one nothing vouches for, which proves only that the same party answers-each time. Pass ``--ak-name`` with the pinned attestation key so the-challenge is made for it and not for whatever the document names.--On the operator, with the artifacts the target was given::-- shirudo attest verify --evidence=evidence.json --nonce=$nonce \- --ak-name=000b... --cert=cert.der \- --upatch=fix.upatch --upatch=shield.upatch--``verify`` prints one line per check and a verdict: the signatures and-the nonce, the endorsement key and the credential it opened, the-quote against the listed PCRs, the certified index against the-recorded binding, the eventlog replay, the anchor in PCR 9, and the-register against the value predicted for that set. Loads-and unloads after boot change the register; either pass-``--allow-runtime-events`` to see them listed, or compute the exact-value with ``shirudo attest predict --cert cert.der --upatch ...---event=load:<name>=<payload_sha256>`` and pass it as-``--expect-chain``. ``--expect-pcr=11=<hex>`` pins a kernel or-firmware PCR to a value you know (``systemd-measure calculate`` for a-UKI's PCR 11); ``--expect-bind-pcr=11=<hex>`` pins the PCR 11 value the-register was bound under, the ``enter-initrd`` phase value the same-tool computes, and ``--require-initrd`` refuses a binding made from the-root file system; ``--ek-name`` pins the endorsement key;-``--strict-anchor`` fails instead of noting when PCR 9 holds more than-the initrd and the anchor. Neither command needs the other machine.--10) Troubleshooting----------------------``init_prereqs_missing``- One or more pre-flight checks failed; the message names each one.- ``shirudo init --check-only`` reproduces the report.--``cert_kernel_support`` (pre-flight), ``signature_unsupported`` (load)- The kernel cannot verify ML-DSA. Enable ``CONFIG_CRYPTO_MLDSA`` and- ``CONFIG_CRYPTO_SHA512``.--``cert_algorithm`` (pre-flight)- The provisioned ``cert.der`` is not ML-DSA-87. Re-key with- ``shirudo genkey`` on the operator.--``kernel_abi_unsupported``- The kernel lacks the signed-loader ABI. Upgrade to a current- upstream kernel.--``signature_rejected``, ``keyring_missing``- The target was initialised with a different certificate, or not at- all. Compare ``shirudo keys`` on both sides.--``tpm2_reachable`` (pre-flight), ``tpm_error``- No TPM 2.0, or the measurement register cannot be bound. Check- ``/dev/tpmrm0`` and ``tpm.owner_auth`` on a TPM with an- owner password. Host-side software TPM tests may set ``tpm.tcti``.--``verifier_rejected``- Read the verifier log in the ``--report`` document and rebuild- against the target kernel's BTF.--``btf_mismatch``- Regenerate ``vmlinux.h`` from the target kernel and rebuild.--``tampered``- The register, the keyring serial or the pins are not what the- operation expected, or the register is not the index ``init``- bound this boot. Inspect ``shirudo status`` and the eventlog;- retry only after the state is understood.--``eventlog_full``- ``eventlog.max_bytes`` would be exceeded; nothing was loaded or- extended. Raise the cap or archive the eventlog.--``version_mismatch``- ``--expect-version-id`` named a different build of shirudo.--Registry fetch failures- Check the ``oci://`` endpoint, the ``BPM_OCI_*`` environment, the- certificate registered under ``/etc/shirudo/bpm``, and that the- registry offers TLS 1.3 with a hybrid ML-KEM group. For registries- that do not, add their exact hostnames as a comma-separated list in- ``tls.classical_hosts`` in ``/etc/shirudo/shirudo.conf`` on the- operator. For a target, the- setting must be in the immutable runtime image's config. This does- not change certificate verification, but permits classical key- exchange with no post-quantum confidentiality. Hybrid-only policy- remains active for every other host::-- tls.classical_hosts = ghcr.io,quay.io--The `operations <operations.rst>`__ guide has the full table of-categories with the action for each, and the recovery procedures.diff --git a/Documentation/images/background-dm-verity-tree.svg b/Documentation/images/background-dm-verity-tree.svgnew file mode 100644index 00000000..fa96b6d0--- /dev/null+++ b/Documentation/images/background-dm-verity-tree.svg@@ -0,0 +1,64 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 290" width="760" height="290" font-family="sans-serif" role="img" aria-labelledby="t">+ <title id="t">A dm-verity hash tree over eight data blocks: each hash covers two blocks below it, and the path from data block D5 through H2 and H23 to the root hash is highlighted</title>+ <style>@media (prefers-color-scheme: dark) { [fill="#5d6675"] { fill: #b4bcc7; } }</style>+ <g fill="none" stroke="#8a93a0" stroke-width="1.5">+ <line x1="52" y1="232" x2="90" y2="192"/>+ <line x1="128" y1="232" x2="90" y2="192"/>+ <line x1="204" y1="232" x2="242" y2="192"/>+ <line x1="280" y1="232" x2="242" y2="192"/>+ <line x1="356" y1="232" x2="394" y2="192"/>+ <line x1="508" y1="232" x2="546" y2="192"/>+ <line x1="584" y1="232" x2="546" y2="192"/>+ <line x1="90" y1="160" x2="166" y2="120"/>+ <line x1="242" y1="160" x2="166" y2="120"/>+ <line x1="546" y1="160" x2="470" y2="120"/>+ <line x1="166" y1="88" x2="318" y2="48"/>+ </g>+ <g fill="none" stroke="#8a93a0" stroke-width="3">+ <line x1="432" y1="232" x2="394" y2="192"/>+ <line x1="394" y1="160" x2="470" y2="120"/>+ <line x1="470" y1="88" x2="318" y2="48"/>+ </g>+ <g fill="#8a93a0" fill-opacity="0.06" stroke="#8a93a0" stroke-width="1.5">+ <rect x="134" y="88" width="64" height="32" rx="4"/>+ <rect x="58" y="160" width="64" height="32" rx="4"/>+ <rect x="210" y="160" width="64" height="32" rx="4"/>+ <rect x="514" y="160" width="64" height="32" rx="4"/>+ <rect x="26" y="232" width="52" height="32" rx="4"/>+ <rect x="102" y="232" width="52" height="32" rx="4"/>+ <rect x="178" y="232" width="52" height="32" rx="4"/>+ <rect x="254" y="232" width="52" height="32" rx="4"/>+ <rect x="330" y="232" width="52" height="32" rx="4"/>+ <rect x="482" y="232" width="52" height="32" rx="4"/>+ <rect x="558" y="232" width="52" height="32" rx="4"/>+ </g>+ <g fill="#8a93a0" fill-opacity="0.3" stroke="#8a93a0" stroke-width="2.5">+ <rect x="258" y="16" width="120" height="32" rx="4"/>+ <rect x="438" y="88" width="64" height="32" rx="4"/>+ <rect x="362" y="160" width="64" height="32" rx="4"/>+ <rect x="406" y="232" width="52" height="32" rx="4"/>+ </g>+ <g fill="#5d6675" font-size="13" text-anchor="middle">+ <text x="318" y="37">root hash</text>+ <text x="166" y="109">H01</text>+ <text x="470" y="109">H23</text>+ <text x="90" y="181">H0</text>+ <text x="242" y="181">H1</text>+ <text x="394" y="181">H2</text>+ <text x="546" y="181">H3</text>+ <text x="52" y="253">D0</text>+ <text x="128" y="253">D1</text>+ <text x="204" y="253">D2</text>+ <text x="280" y="253">D3</text>+ <text x="356" y="253">D4</text>+ <text x="432" y="253">D5</text>+ <text x="508" y="253">D6</text>+ <text x="584" y="253">D7</text>+ </g>+ <g fill="#5d6675" font-size="12">+ <text x="636" y="37">trusted value</text>+ <text x="636" y="109">hash blocks</text>+ <text x="636" y="181">hash blocks</text>+ <text x="636" y="253">data blocks</text>+ </g>+</svg>diff --git a/Documentation/images/background-telemetry-export.svg b/Documentation/images/background-telemetry-export.svgnew file mode 100644index 00000000..b1effa23--- /dev/null+++ b/Documentation/images/background-telemetry-export.svg@@ -0,0 +1,51 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 270" width="760" height="270" font-family="sans-serif" role="img" aria-labelledby="t">+ <title id="t">Telemetry export path from a target to a collector</title>+ <style>@media (prefers-color-scheme: dark) { [fill="#5d6675"] { fill: #b4bcc7; } }</style>+ <defs>+ <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">+ <path d="M0,0 L10,5 L0,10 z" fill="#8a93a0"/>+ </marker>+ </defs>+ <g fill="none" stroke="#8a93a0" stroke-width="1.5">+ <rect x="10" y="10" width="535" height="250" rx="6" stroke-dasharray="6 4"/>+ <rect x="25" y="60" width="110" height="64" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="155" y="60" width="110" height="64" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="285" y="60" width="110" height="64" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="415" y="60" width="115" height="64" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="25" y="170" width="370" height="64" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="415" y="170" width="115" height="64" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="600" y="105" width="145" height="84" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <line x1="135" y1="92" x2="153" y2="92" marker-end="url(#arrow)"/>+ <line x1="265" y1="92" x2="283" y2="92" marker-end="url(#arrow)"/>+ <line x1="395" y1="92" x2="413" y2="92" marker-end="url(#arrow)"/>+ <line x1="395" y1="202" x2="413" y2="202" marker-end="url(#arrow)"/>+ <path d="M530,92 L565,92 L565,135 L598,135" marker-end="url(#arrow)"/>+ <path d="M530,202 L565,202 L565,160 L598,160" marker-end="url(#arrow)"/>+ </g>+ <g fill="#5d6675" font-size="12">+ <text x="22" y="32">target: one-shot commands started by systemd timers</text>+ <text x="22" y="52" font-size="11">shirudo upatch map --all</text>+ <text x="22" y="162" font-size="11">shirudo status --otel</text>+ <g text-anchor="middle">+ <text x="80" y="88" font-size="13">BPF map</text>+ <text x="80" y="106" font-size="11">arena, hash,</text>+ <text x="80" y="119" font-size="11">per-CPU</text>+ <text x="210" y="88" font-size="13">serializer</text>+ <text x="210" y="106" font-size="11">or direct read</text>+ <text x="340" y="88" font-size="13">signed decoder</text>+ <text x="340" y="106" font-size="11">Lua in LuaJIT</text>+ <text x="472" y="88" font-size="13">OTLP JSON</text>+ <text x="472" y="106" font-size="11">log record or</text>+ <text x="472" y="119" font-size="11">metrics</text>+ <text x="210" y="198" font-size="13">status report</text>+ <text x="210" y="216" font-size="11">conditions, TPM, tamper counters</text>+ <text x="472" y="198" font-size="13">OTLP JSON</text>+ <text x="472" y="216" font-size="11">keepalive log</text>+ <text x="672" y="135" font-size="13">collector</text>+ <text x="672" y="153" font-size="11">OTLP receiver</text>+ <text x="672" y="168" font-size="11">then backends</text>+ <text x="672" y="212" font-size="11">HTTPS POST to</text>+ <text x="672" y="226" font-size="11">/v1/logs, /v1/metrics</text>+ </g>+ </g>+</svg>diff --git a/Documentation/images/background-tpm-register.svg b/Documentation/images/background-tpm-register.svgnew file mode 100644index 00000000..3e70d04a--- /dev/null+++ b/Documentation/images/background-tpm-register.svg@@ -0,0 +1,82 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 400" width="760" height="400" font-family="sans-serif" role="img" aria-labelledby="t">+ <title id="t">Binding the measurement register: the PCR 9 and 11 values enter the write policy, the policy defines the NV extend index, and the index name is anchored in PCR 9</title>+ <style>@media (prefers-color-scheme: dark) { [fill="#5d6675"] { fill: #b4bcc7; } }</style>+ <defs>+ <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">+ <path d="M0,0 L10,5 L0,10 z" fill="#8a93a0"/>+ </marker>+ </defs>+ <g fill="#8a93a0" fill-opacity="0.08" stroke="#8a93a0" stroke-width="1.5">+ <rect x="20" y="30" width="210" height="80" rx="6"/>+ <rect x="20" y="140" width="210" height="110" rx="6"/>+ <rect x="280" y="30" width="260" height="180" rx="6"/>+ <rect x="280" y="250" width="260" height="70" rx="6"/>+ <rect x="575" y="30" width="165" height="140" rx="6"/>+ <rect x="575" y="205" width="165" height="125" rx="6"/>+ </g>+ <g fill="none" stroke="#8a93a0" stroke-width="1.5" marker-end="url(#arrow)">+ <line x1="230" y1="70" x2="278" y2="70"/>+ <line x1="230" y1="175" x2="278" y2="175"/>+ <line x1="540" y1="90" x2="573" y2="90"/>+ <line x1="410" y1="250" x2="410" y2="212"/>+ <line x1="657" y1="170" x2="657" y2="203"/>+ <polyline points="657,330 657,365 125,365 125,252"/>+ </g>+ <g fill="#5d6675" font-size="12">+ <text x="32" y="52" font-weight="bold" font-size="13">PCR 11</text>+ <text x="32" y="72">UKI sections, enter-initrd</text>+ <text x="32" y="92">at binding: phase_before</text>++ <text x="32" y="162" font-weight="bold" font-size="13">PCR 9</text>+ <text x="32" y="182">initrd, command line,</text>+ <text x="32" y="198">NvPCR anchors</text>+ <text x="32" y="218">at binding: pcr_before</text>+ <text x="32" y="238">then shirudo's anchor</text>++ <text x="292" y="52" font-weight="bold" font-size="13">Write policy</text>+ <text x="292" y="74">PolicyOR of two branches:</text>+ <text x="304" y="94">written: PolicyNvWritten(YES)</text>+ <text x="304" y="114">init: PolicyNvWritten(NO)</text>+ <text x="304" y="132">and PolicyPCR(9, 11)</text>+ <text x="292" y="156">then PolicySigned(writer key)</text>+ <text x="292" y="176">then PolicyCommandCode(NV_Extend)</text>+ <text x="292" y="198" font-size="11">digest = the index's authPolicy</text>++ <text x="292" y="272" font-weight="bold" font-size="13">NV writer key</text>+ <text x="292" y="292">RSA-3072, owner hierarchy,</text>+ <text x="292" y="310">signs nonce and command hash</text>++ <text x="587" y="52" font-weight="bold" font-size="13">NV index</text>+ <text x="587" y="72">0x01818E00</text>+ <text x="587" y="92" font-size="11">TPM_NT_EXTEND</text>+ <text x="587" y="108" font-size="11">POLICYWRITE</text>+ <text x="587" y="124" font-size="11">ORDERLY</text>+ <text x="587" y="140" font-size="11">CLEAR_STCLEAR</text>+ <text x="587" y="160" font-size="11">Name = H(public area)</text>++ <text x="587" y="227" font-weight="bold" font-size="13">Anchor</text>+ <text x="587" y="247">nvpcr-init:shirudo:</text>+ <text x="587" y="263">0x1818e00:<written</text>+ <text x="587" y="279">Name></text>+ <text x="587" y="303" font-size="11">its SHA-256 extends</text>+ <text x="587" y="319" font-size="11">PCR 9</text>+ </g>+ <g fill="none" stroke="#8a93a0" stroke-width="1.2">+ <circle cx="254" cy="58" r="9"/>+ <circle cx="254" cy="163" r="9"/>+ <circle cx="557" cy="76" r="9"/>+ <circle cx="672" cy="187" r="9"/>+ <circle cx="390" cy="350" r="9"/>+ </g>+ <g fill="#5d6675" font-size="11" text-anchor="middle">+ <text x="254" y="62">1</text>+ <text x="254" y="167">1</text>+ <text x="557" y="80">2</text>+ <text x="672" y="191">3</text>+ <text x="390" y="354">4</text>+ </g>+ <g fill="#5d6675" font-size="11">+ <text x="418" y="236">signs</text>+ <text x="406" y="388" text-anchor="middle">PCR_Extend(9, SHA-256(anchor)) closes the init branch</text>+ </g>+</svg>diff --git a/Documentation/images/internals-architecture.svg b/Documentation/images/internals-architecture.svgnew file mode 100644index 00000000..dcb9bdc0--- /dev/null+++ b/Documentation/images/internals-architecture.svg@@ -0,0 +1,57 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 780 430" width="780" height="430" font-family="sans-serif" role="img" aria-labelledby="t">+ <title id="t">shirudo components on the operator host and on a target</title>+ <style>@media (prefers-color-scheme: dark) { [fill="#5d6675"] { fill: #b4bcc7; } }</style>+ <defs>+ <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">+ <path d="M0,0 L10,5 L0,10 z" fill="#8a93a0"/>+ </marker>+ </defs>+ <g fill="none" stroke="#8a93a0" stroke-width="1.5">+ <rect x="10" y="40" width="200" height="150" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="250" y="60" width="130" height="70" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="250" y="250" width="130" height="56" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="420" y="10" width="350" height="410" rx="6" stroke-dasharray="6 4"/>+ <rect x="435" y="40" width="320" height="120" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="435" y="190" width="320" height="120" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="435" y="340" width="320" height="66" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <line x1="210" y1="95" x2="248" y2="95" marker-end="url(#arrow)"/>+ <line x1="380" y1="95" x2="433" y2="95" marker-end="url(#arrow)"/>+ <line x1="595" y1="160" x2="595" y2="188" marker-end="url(#arrow)"/>+ <line x1="700" y1="160" x2="700" y2="338" marker-end="url(#arrow)"/>+ <line x1="433" y1="140" x2="382" y2="270" marker-end="url(#arrow)"/>+ <path d="M435,385 L110,385 L110,192" stroke-dasharray="5 4" marker-end="url(#arrow)"/>+ </g>+ <g fill="#5d6675" font-size="13">+ <text x="20" y="32" font-weight="bold">Operator host</text>+ <text x="22" y="64">shirudo, shirudo-build</text>+ <text x="22" y="86">ML-DSA-87 signing key</text>+ <text x="22" y="108">build and sign upatches</text>+ <text x="22" y="130">build and sign images</text>+ <text x="22" y="152">publish packages, trees</text>+ <text x="22" y="174">attest verify, predict</text>+ <text x="260" y="82" font-weight="bold">OCI registry</text>+ <text x="260" y="104">packages, index,</text>+ <text x="260" y="122">upatch tree</text>+ <text x="260" y="272" font-weight="bold">Collector</text>+ <text x="260" y="294">OTLP over TLS</text>+ <text x="430" y="32" font-weight="bold">Target</text>+ <text x="445" y="62" font-weight="bold">Userspace, one-shot commands</text>+ <text x="445" y="84">shirudo from the runtime image</text>+ <text x="445" y="104">/run/shirudo/runtime, /run/shirudo/config</text>+ <text x="445" y="124">/var/lib/shirudo (sealed state)</text>+ <text x="445" y="144">systemd units and timers</text>+ <text x="445" y="212" font-weight="bold">Kernel</text>+ <text x="445" y="234">BPF LSM programs: bpf2, seal</text>+ <text x="445" y="254">signed upatches</text>+ <text x="445" y="274">.bpf and .dm-verity keyrings</text>+ <text x="445" y="294">private bpffs with the pins</text>+ <text x="445" y="362" font-weight="bold">TPM 2.0</text>+ <text x="445" y="384">NV register, PCR 9 anchor,</text>+ <text x="445" y="402">config PCR, attestation key</text>+ <text x="215" y="86" font-size="12">push</text>+ <text x="392" y="86" font-size="12">pull</text>+ <text x="602" y="180" font-size="12">bpf(), mount, keyctl</text>+ <text x="608" y="330" font-size="12">extend, quote</text>+ <text x="120" y="378" font-size="12">signed evidence, checked offline</text>+ </g>+</svg>diff --git a/Documentation/images/security-trust-boundaries.svg b/Documentation/images/security-trust-boundaries.svgnew file mode 100644index 00000000..0f08bb6c--- /dev/null+++ b/Documentation/images/security-trust-boundaries.svg@@ -0,0 +1,73 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 780 490" width="780" height="490" font-family="sans-serif" role="img" aria-labelledby="t">+ <title id="t">Trust boundaries of a shirudo deployment and the evidence boundary</title>+ <style>@media (prefers-color-scheme: dark) { [fill="#5d6675"] { fill: #b4bcc7; } }</style>+ <defs>+ <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">+ <path d="M0,0 L10,5 L0,10 z" fill="#8a93a0"/>+ </marker>+ </defs>+ <g fill="none" stroke="#8a93a0" stroke-width="1.5">+ <rect x="10" y="40" width="200" height="120" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="10" y="340" width="200" height="100" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="230" y="10" width="170" height="290" rx="6" stroke-dasharray="6 4"/>+ <rect x="245" y="50" width="140" height="70" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="245" y="200" width="140" height="70" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="230" y="320" width="170" height="160" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <line x1="230" y1="392" x2="400" y2="392" stroke-dasharray="3 3"/>+ <rect x="420" y="10" width="350" height="470" rx="6" stroke-dasharray="6 4"/>+ <rect x="435" y="40" width="320" height="60" rx="4"/>+ <rect x="435" y="115" width="320" height="55" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="430" y="190" width="330" height="275" rx="6" stroke-dasharray="3 3" fill="#8a93a0" fill-opacity="0.05"/>+ <rect x="445" y="215" width="300" height="75" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="445" y="310" width="300" height="140" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <line x1="210" y1="85" x2="243" y2="85" marker-end="url(#arrow)"/>+ <line x1="385" y1="100" x2="443" y2="235" marker-end="url(#arrow)"/>+ <line x1="443" y1="270" x2="387" y2="245" marker-end="url(#arrow)"/>+ <line x1="445" y1="410" x2="402" y2="410" marker-end="url(#arrow)"/>+ <line x1="230" y1="410" x2="212" y2="410" marker-end="url(#arrow)"/>+ </g>+ <g fill="#5d6675" font-size="13">+ <text x="20" y="32" font-weight="bold">Operator host</text>+ <text x="22" y="66">ML-DSA-87 signing key</text>+ <text x="22" y="88">shirudo-build, clang</text>+ <text x="22" y="110">signs upatches, indexes,</text>+ <text x="22" y="130">trees, configs, vouches</text>+ <text x="20" y="332" font-weight="bold">Verifier</text>+ <text x="22" y="366">attest verify, offline</text>+ <text x="22" y="388">pinned AK name</text>+ <text x="22" y="430">expected state, PCRs</text>+ <text x="240" y="32" font-weight="bold">Network, untrusted</text>+ <text x="255" y="74" font-weight="bold">OCI registry</text>+ <text x="255" y="94">packages, indexes,</text>+ <text x="255" y="112">tree publications</text>+ <text x="255" y="224" font-weight="bold">Collector</text>+ <text x="255" y="244">keepalives, map</text>+ <text x="255" y="262">snapshots</text>+ <text x="240" y="342" font-weight="bold">Evidence</text>+ <text x="430" y="32" font-weight="bold">Target</text>+ <text x="445" y="62" font-weight="bold">Root and other processes</text>+ <text x="445" y="84">constrained by the LSM, not trusted</text>+ <text x="445" y="137" font-weight="bold">Writable state</text>+ <text x="445" y="157">/var/lib/shirudo, sealed by label</text>+ <text x="455" y="237" font-weight="bold">Runtime tasks</text>+ <text x="455" y="257">exec from the dm-verity runtime</text>+ <text x="455" y="277">image grants the task mark</text>+ <text x="455" y="332" font-weight="bold">Kernel and TPM</text>+ <text x="455" y="354">BPF LSM: bpf2 and seal objects</text>+ <text x="455" y="374">.bpf and .dm-verity keyrings</text>+ <text x="455" y="394">private bpffs: pins and maps</text>+ <text x="455" y="430">TPM: register, AK, NV writer</text>+ </g>+ <g fill="#5d6675" font-size="11">+ <text x="440" y="207">target TCB</text>+ <text x="214" y="76">push</text>+ <text x="376" y="165">pull</text>+ <text x="392" y="282">export</text>+ <text x="240" y="362">TPM-signed:</text>+ <text x="240" y="379">quote, NV certification</text>+ <text x="240" y="412">target's own account:</text>+ <text x="240" y="429">eventlog, config history,</text>+ <text x="240" y="446">init record fields</text>+ <text x="240" y="463">(bound_in, ts, boot_id)</text>+ </g>+</svg>diff --git a/Documentation/images/start-how-it-works.svg b/Documentation/images/start-how-it-works.svgnew file mode 100644index 00000000..6b661008--- /dev/null+++ b/Documentation/images/start-how-it-works.svg@@ -0,0 +1,67 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 380" width="760" height="380" font-family="sans-serif" role="img" aria-labelledby="t">+ <title id="t">The life of an upatch from the operator host through a registry to a target and its TPM, and the evidence back to the operator</title>+ <style>@media (prefers-color-scheme: dark) { [fill="#5d6675"] { fill: #b4bcc7; } }</style>+ <defs>+ <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">+ <path d="M0,0 L10,5 L0,10 z" fill="#8a93a0"/>+ </marker>+ </defs>+ <g fill="none" stroke="#8a93a0" stroke-width="1.5">+ <rect x="10" y="50" width="190" height="250" rx="6" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="240" y="110" width="150" height="100" rx="6" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="430" y="10" width="320" height="320" rx="6" stroke-dasharray="6 4"/>+ <rect x="445" y="44" width="295" height="104" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="445" y="184" width="160" height="132" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <rect x="620" y="184" width="120" height="132" rx="4" fill="#8a93a0" fill-opacity="0.08"/>+ <line x1="200" y1="160" x2="238" y2="160" marker-end="url(#arrow)"/>+ <line x1="390" y1="130" x2="443" y2="130" marker-end="url(#arrow)"/>+ <line x1="527" y1="148" x2="527" y2="182" marker-end="url(#arrow)"/>+ <line x1="680" y1="148" x2="680" y2="182" marker-end="url(#arrow)"/>+ <path d="M680,316 L680,362 L105,362 L105,302" marker-end="url(#arrow)"/>+ </g>+ <g fill="#5d6675" font-size="11">+ <text x="442" y="32" font-size="12">target</text>+ <g text-anchor="middle">+ <text x="105" y="74" font-size="13">Operator host</text>+ <text x="315" y="134" font-size="13">OCI registry</text>+ <text x="315" y="158">packages (.bee)</text>+ <text x="315" y="174">signed index</text>+ <text x="315" y="190">tree publication</text>+ <text x="592" y="66" font-size="13">shirudo, one-shot commands</text>+ <text x="527" y="206" font-size="13">Kernel</text>+ <text x="680" y="206" font-size="13">TPM</text>+ <text x="219" y="152">push</text>+ <text x="416" y="122">pull</text>+ <text x="390" y="354">evidence for the operator's nonce</text>+ </g>+ <text x="22" y="104">1</text>+ <text x="37" y="104">shirudo build</text>+ <text x="37" y="120">signed loader artifact</text>+ <text x="22" y="146">2</text>+ <text x="37" y="146">shirudo bpm build</text>+ <text x="37" y="162">bpm push</text>+ <text x="37" y="178">bpm tree append</text>+ <text x="22" y="252">7</text>+ <text x="37" y="252">shirudo attest verify</text>+ <text x="37" y="268">attest predict</text>+ <text x="457" y="90">3</text>+ <text x="472" y="90">bpm repo update, bpm upgrade,</text>+ <text x="472" y="106">bpm tree sync (timers)</text>+ <text x="457" y="128">4</text>+ <text x="472" y="128">upatch load</text>+ <text x="533" y="170">bpf()</text>+ <text x="686" y="170">extend</text>+ <text x="457" y="230">5</text>+ <text x="472" y="230">signature check</text>+ <text x="472" y="246">against .bpf keyring</text>+ <text x="472" y="266">LSM admission</text>+ <text x="472" y="286">loader runs, links</text>+ <text x="472" y="302">attached and pinned</text>+ <g text-anchor="middle">+ <text x="680" y="232">6</text>+ <text x="680" y="248">register extended</text>+ <text x="680" y="276">attestation key</text>+ <text x="680" y="292">signs evidence</text>+ </g>+ </g>+</svg>diff --git a/Documentation/images/upatches-double-buffer.svg b/Documentation/images/upatches-double-buffer.svgnew file mode 100644index 00000000..72db72bb--- /dev/null+++ b/Documentation/images/upatches-double-buffer.svg@@ -0,0 +1,41 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 250" width="760" height="250" font-family="sans-serif" role="img" aria-labelledby="t">+ <title id="t">A double-buffered arena table: kernel hooks write into the active buffer; an export swaps the buffers, a serializer renders the drained buffer page by page into the shirudo_ser output map that shirudo upatch map reads, and the drained buffer is cleared after the last page</title>+ <style>@media (prefers-color-scheme: dark) { [fill="#5d6675"] { fill: #b4bcc7; } }</style>+ <defs>+ <marker id="a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">+ <path d="M0,0 L10,5 L0,10 z" fill="#8a93a0"/>+ </marker>+ </defs>+ <g fill="#8a93a0" fill-opacity="0.06" stroke="#8a93a0" stroke-width="1.5">+ <rect x="20" y="40" width="130" height="50" rx="4"/>+ <rect x="200" y="40" width="160" height="50" rx="4"/>+ <rect x="200" y="160" width="160" height="50" rx="4"/>+ <rect x="410" y="160" width="130" height="50" rx="4"/>+ <rect x="590" y="160" width="150" height="50" rx="4"/>+ </g>+ <g fill="none" stroke="#8a93a0" stroke-width="1.5" stroke-dasharray="5 4">+ <rect x="185" y="20" width="190" height="210" rx="6"/>+ </g>+ <g fill="none" stroke="#8a93a0" stroke-width="1.5" marker-end="url(#a)">+ <line x1="150" y1="65" x2="196" y2="65"/>+ <line x1="360" y1="185" x2="406" y2="185"/>+ <line x1="540" y1="185" x2="586" y2="185"/>+ <path d="M330,94 C350,120 350,130 330,156"/>+ <path d="M230,156 C210,130 210,120 230,94"/>+ </g>+ <g fill="#5d6675" font-size="13" text-anchor="middle">+ <text x="85" y="62">kernel hooks</text>+ <text x="85" y="78">append records</text>+ <text x="280" y="62">active buffer</text>+ <text x="280" y="78">this interval</text>+ <text x="280" y="182">drain buffer</text>+ <text x="280" y="198">previous interval</text>+ <text x="475" y="182">serializer</text>+ <text x="475" y="198">one page per run</text>+ <text x="665" y="182">shirudo_ser chunks</text>+ <text x="665" y="198">read by upatch map</text>+ <text x="388" y="130" text-anchor="start">swap at the start</text>+ <text x="388" y="146" text-anchor="start">of an export</text>+ <text x="280" y="246">one BPF arena</text>+ </g>+</svg>diff --git a/Documentation/index.rst b/Documentation/index.rstindex 79f54abf..380bae85 100644--- a/Documentation/index.rst+++ b/Documentation/index.rst@@ -2,143 +2,110 @@SPDX-License-Identifier: BSD-2-ClauseCopyright (c) 2026 Authors of shirudo-shirudo manual-==============--shirudo ("shields", Japanese) is a BPF security platform. It ships-BPF live patches, called upatches, to Linux targets without a reboot,-and it makes sure a target runs only the BPF its operator signed. Once-``shirudo init`` has run, the kernel accepts BPF from userspace only-inside a signed loader program whose signature verifies against the-certificate in a sealed kernel keyring; root without the signing key-cannot load, replace or detach BPF, and every state change is measured-into a per-boot TPM register the TPM certifies on request. The-userspace side is one agentless-``shirudo`` binary: no daemon, no listening socket, one-shot commands-driven by systemd timers that pull signed packages from OCI registries-and push state to an OTLP collector.--The kernel's CVE stream runs at dozens of fixes a day and exploitation-now regularly precedes the patch, while a fleet reboot cycle takes-weeks. shirudo exists for the window in between: an agent or an-engineer derives a BPF shield from the fix, the operator signs it, and-the fleet pulls it within the hour, measured and revocable.--This index points at the documents in the tree. The code is-authoritative for behaviour; the documents describe it and say why it-is the way it is.--1) Which document--------------------Checking whether a host can run shirudo- `requirements <requirements.rst>`__ lists the kernel options, the- operator toolchain and the target runtime, with the reason for- each.--Deploying shirudo- `getting-started <getting-started.rst>`__ walks through building,- creating a signing key, initialising a target, loading an upatch- and publishing packages to a registry.--Using executable and config images- `config-images <config-images.rst>`__ describes the required dm-verity- layout: separate runtime and config images, operator generation,- bootstrap trust, live config and key updates, static-PCR measurements,- interrupted activation, manual reboot, enforcement and current limitations.--Writing and shipping upatches- `upatch <upatch.rst>`__ is the author's and operator's guide: the- BPF side of a upatch, building and signing, testing on a target,- the Beefile and ``bpm build``, publishing to a registry and to the- signed upatch tree, and what a target does with both.-- `features <features.rst>`__ lists every attachment kind a upatch- can have, what the kernel does at that point, how the loader- attaches there and what the target needs for it.--Keys- `key-lifecycle <key-lifecycle.rst>`__ covers the signing keys and- their certificates from creation to retirement: the trusted set a- target enrols, vouching for a new key, rotation, revocation and- custody.--Running targets- `operations <operations.rst>`__ is the day-two guide: the units- and timers, what to watch, upgrading shirudo and the kernel,- decommissioning, backup, recovery, and every failure category.--Understanding what shirudo does- `architecture <architecture.rst>`__ describes why shirudo exists,- its design properties, the signed-loader path, the kernel- enforcement programs, the target state, and the delivery and- observability paths.--Reviewing the security design- `threat-model <threat-model.rst>`__ states the trust boundaries,- the adversaries, the threats shirudo addresses with the mechanism- behind each, and the residual risks.--Measuring and attesting a target- `initrd <initrd.rst>`__ describes the production configuration:- the run of ``init`` inside the initrd, what the root file system's- run finishes, what an initrd must contain and how the generator- and the installer build one.-- `tpm <tpm.rst>`__ describes the per-boot measurement register,- the events and the eventlog, the TPM-signed evidence and its- verification, how they relate to systemd's NvPCRs and what they- do not yet do.--Shipping state to a collector- `telemetry <telemetry.rst>`__ explains the OTLP export of map- snapshots and status keepalives and how to feed them into the- OpenTelemetry Collector, ClickHouse, Splunk or a collector of your- own.--Reading or writing a ``.upatch``- `upatch-spec <upatch-spec.rst>`__ is the byte-level reference for- the signed artifact.--Developing shirudo- `developer-guide <developer-guide.rst>`__ covers working from a- checkout, the operator-only tools, writing and running the tests in- their tiers, the test VM, and the coverage and parser gaps still open.--Contributing- `contributing <contributing.rst>`__ covers commit messages, the- mandatory ``Signed-off-by:`` and the kernel's tags.- `coding-style <coding-style.rst>`__ is the kernel's coding style,- copied verbatim from ``Documentation/process/coding-style.rst``- and applied to userspace C and BPF alike.--2) Companion files in the repository root--------------------------------------------``AGENTS.md``- Guidance for coding agents contributing to shirudo; ``CLAUDE.md``- imports it for Claude Code.--``README.md``- A short overview of what shirudo is and where to look.--``CODE_OF_CONDUCT.md``- The community Code of Conduct, based on the CNCF one; conduct- concerns go to [email protected].--``LICENSE``- BSD-2-Clause for userspace. BPF programs declare ``Dual BSD/GPL``- because the kernel's LSM hook framework requires a GPL-compatible- licence. Vendored files keep their upstream SPDX identifiers.--``upatches/``- The packages shirudo ships, each with a named ``.bee`` package definition.--``vendor/libbpf/``- Vendored libbpf and BPF UAPI headers with shirudo's BSD shims for- the kernel's ``tools/include`` internals; refreshed by ``make- bpf-deps``, see its ``README.md``.--``testing/``- The tests, the test VM that runs the target ones, and ``swtpm.sh``- for a software TPM.+shirudo documentation+=====================++shirudo is a BPF-based security platform: Linux targets run only the BPF+their operator signed, every change is measured into the TPM, and the+functionality ships as signed upatches that targets pull from OCI+registries.++Use cases+---------++shirudo is the platform. It does not need to understand what an upatch+does; it makes sure that only signed upatches run and that every change is+on record.++.. container:: grid++ .. container::++ Live patching for kernel and userspace++ Security mitigations that block vulnerable code paths. They+ complement traditional kernel live patching with a faster rollout+ and bridge the deployment cycles of the kernel and of userspace+ applications.++ .. container::++ System hardening++ Sandboxes for containers, Kubernetes pods and LLM agents, and+ kernel hardening implemented as upatches.++ .. container::++ Runtime security and observability++ For the kernel and userspace applications, LLM agents included.+ Data is collected and aggregated in BPF maps and pushed over+ OpenTelemetry into collectors.++ .. container::++ Minimal overhead++ Agentless, with no daemon and no open port, and built in as part of+ the trusted computing base. Designed for embedded devices as well as+ servers.++Properties+----------++shirudo is built on a set of properties for a BPF security platform:++- Always on: the platform is part of the trusted computing base and starts+ from the initrd in early boot.+- Signed and sealed: BPF is admitted only through loaders signed against+ the sealed BPF keyring, and the platform guards its own assets against+ a root user who does not hold the signing key.+- In-kernel control plane: every load and unload is a signed loader the+ kernel verifies before it runs.+- Measured: a TPM-backed register records the history of every operation+ on upatches, and the TPM signs it for a remote verifier.+- Platform, not policy: shirudo protects only its own assets. Everything+ else ships as upatches: signed BPF light skeletons, a loader and its+ assets.+- Code, not DSLs: upatches are plain BPF C in small pieces that engineers+ and agents can read, generate and maintain, and commands take and+ produce structured data.+- Pull in, push out: targets pull upatches from OCI registries and push+ telemetry to collectors; nothing on a target listens for connections.++The :doc:`security/threat-model` states where each of these mechanisms+stops.++Documentation+-------------++- :doc:`start/index`: build shirudo, boot a protected test target and take+ one upatch through its whole life, then install it.+- :doc:`concepts/index`: the mechanisms shirudo builds on, from BPF signing+ and the BPF LSM to dm-verity, TPM 2.0 and post-quantum cryptography, and+ the vocabulary of the rest of the documentation.+- :doc:`operate/index`: system requirements, deployment, attestation,+ monitoring, upgrades, troubleshooting and incident response for targets+ in production.+- :doc:`upatches/index`: write, test, package and publish upatches.+- :doc:`security/index`: the security model, the threat model and the+ threats still to resolve, cryptography and tamper counters.+- :doc:`internals/index`: how shirudo works inside the kernel and on the+ target, and why it is built this way.+- :doc:`reference/index`: every command, format, setting, event, failure+ category, file and unit, and a cheat sheet.+- :doc:`contribute/index`: work on shirudo itself, its tests and its+ documentation.++.. toctree::+ :hidden:++ start/index+ concepts/index+ operate/index+ upatches/index+ security/index+ internals/index+ reference/index+ contribute/indexdiff --git a/Documentation/initrd.rst b/Documentation/initrd.rstdeleted file mode 100644index 2dc2ce34..00000000--- a/Documentation/initrd.rst+++ /dev/null@@ -1,137 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--Bringing shirudo up from the initrd-===================================--Every target starts enforcement from an authenticated systemd initrd before-untrusted workloads. The initrd verifies a runtime image and a separate signed-config image. The host root filesystem stays in place; there is no root pivot.-See `config-images <config-images.rst>`__ for the image contents and generation-commands, `architecture <architecture.rst>`__ for the LSM flow and-`tpm <tpm.rst>`__ for measurement and attestation.--1) What boot needs----------------------* An authenticated UKI containing the bootstrap binary and configuration.- ``runtime.image`` names the cached runtime bundle and ``runtime.root_hash``- gives its exact expected SHA-256 root. Missing image settings are an error.-* The runtime image contains the fully static Shirudo executable,- initial BPF certificate, config-verification certificate and bootstrap TPM- settings. The initial config bundle is signed by an accepted config key.-* Boot parameters ``bpf.keyring_unsealed=1 dm_verity.keyring_unsealed=1``.- The initrd enrolls the trust anchors and seals both kernel keyrings. There- is no fallback to a user keyring when the BPF ring is sealed empty.-* A TPM 2.0, the required BPF and dm-verity kernel interfaces, and a reserved- static SHA-256 PCR for config measurements. See- `requirements <requirements.rst>`__ for the exact kernel requirements,- including disabled 32-bit compatibility.-* ``/sysroot/var/lib/shirudo`` mounted writable before Shirudo starts.- ``shirudo-initrd.service`` remounts ``/sysroot`` read-write; if state is on- a separate filesystem, mount it read-write in the initrd too. Config- selections and cached bundles must be durable before PCR extension.-* ``systemd-pcrphase-initrd.service`` and its ``enter-initrd`` measurement- before Shirudo binds its upatch register. A direct QEMU kernel/initrd boot- tests the handoff but does not establish a measured UKI or the PCR 11 phase- distinction. Non-systemd initrds are unsupported.--2) The initrd run--------------------``shirudo-initrd.service`` runs after the root filesystem is available at-``/sysroot`` and before switch-root. Shirudo binds writable state at-``/var/lib/shirudo``, verifies the images and determines the boot signer set.-The initial BPF certificate comes from the runtime; additional certificates-need valid vouches from the selected config. Config revocations exclude keys-from enrollment. The config verification certificate is enrolled in-``.dm-verity`` and the BPF trust set in ``.bpf``; both keyrings are sealed.--Initialization labels writable state, loads the two embedded bootstrap BPF-objects and freezes their shared state before attaching admission gates.-The authenticated bootstrap task has temporary authority to finish startup.-It mounts the runtime under the device and mount guards, measures config,-applies revocations before restoring signed upatches, and binds the upatch-measurement register. Runtime and config files receive no seal xattrs;-writable state keeps them. All BPF upatches still require signed loaders.--The mounts live below ``/run/shirudo`` so systemd carries them through-switch-root: ``runtime`` is ``ro,nodev,nosuid``, ``config`` is-``ro,nodev,nosuid,noexec``, and ``bpffs`` holds the links and maps. Kernel-keyrings and TPM state survive independently. The initrd eventlog record-waits in ``/run/shirudo/eventlog.pending`` for the root service to adopt.--3) The root service-----------------------Generate a systemd drop-in with ``shirudo-gen-runtime --unit-output`` and-install it at ``/etc/systemd/system/shirudo.service.d/verity.conf``. It invokes-the fully static binary at ``/run/shirudo/runtime/usr/bin/shirudo`` directly.-The executable comes from the verified runtime image.--The service re-runs ``init``, checks the existing guards and measurements,-and adopts the initrd eventlog record without another extension. Successful-exec from the runtime grants the task mark needed for these operations.-There are no lasting executable inode identities or root-only bootstrap-fallback. Do not apply caller-controlled seccomp to this invocation.--4) Building the initrd-------------------------The target package installs ``tools/gen-initrd/module-setup.sh`` as dracut-module ``90shirudo`` and installs ``shirudo-gen-initrd``. The module includes-the bootstrap binary, a preflight certificate copy, authenticated-``/etc/shirudo/shirudo.conf``, the enabled initrd service, TPM support and the-image drivers. Actual BPF enrollment uses the verified image's trust set.--After building and provisioning the images, generate an initrd with::-- sudo shirudo-gen-initrd --bootstrap-conf bootstrap.conf \- --kver <kernel-release> --output /boot/initrd-shirudo.img- shirudo-gen-initrd --check /boot/initrd-shirudo.img- shirudo-gen-initrd --print-cmdline--``--binary`` and ``--binary-path`` select the authenticated bootstrap copy;-``--cert``, ``--trusted-dir`` and ``--unit`` select preflight material and the-service. Arguments after ``--`` go to dracut. The archive check requires the-binary, bootstrap config, certificate, service, enablement and phase unit.-A dracut configuration can provide the same inputs through ``shirudo_binary``,-``shirudo_binary_path``, ``shirudo_cert``, ``shirudo_trusted_dir``,-``shirudo_conf`` and ``shirudo_unit``.--Build and authenticate the UKI with this initrd and both enrollment boot-parameters. Do not start an unprotected target from the host filesystem and-expect image setup to repair earlier writable references. The package-installer can install files and prepare dracut; it does not provision the-images or authorize their runtime hash, and its old ``--now`` mode is removed.--5) Checks, updates and recovery----------------------------------Using the configured runtime invocation, check::-- shirudo status --json- shirudo image status--The status must report ``mode: production``, ``keyring_mode: bpf`` and-``tpm.bound_in: initrd``. The config status must be consistent with no pending-activation, and the upatch register must match this boot's eventlog.-Attestation verification should require the approved UKI measurements,-``--require-initrd`` and the expected config root and PCR.--Live config updates activate another signed immutable image. BPF upatches-continue to use their signed-loader path. A new runtime, config verification-key or BPF signer requires the appropriate authenticated boot rollout and-reboot. The existing activation record takes precedence over the initial-``config.image`` default; the CLI has no separate next-boot selection command.--If activation is interrupted after pending state is recorded, further changes-and config attestation refuse. The node continues running and Shirudo never-reboots automatically. The operator chooses when to reboot; trusted startup-re-verifies the selected image, records a fresh BOOT event and finishes init.-It does not retry the previous boot's PCR extension.--The standard disposable VM run is ``sudo make -C testing functional``. It-exercises this initrd handoff, signed config and upatch updates, task and-writable-state protection, TPM checks and interrupted activation.diff --git a/Documentation/internals/architecture.rst b/Documentation/internals/architecture.rstnew file mode 100644index 00000000..3db97642--- /dev/null+++ b/Documentation/internals/architecture.rst@@ -0,0 +1,185 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: Kernel developers, security reviewers++Architecture overview+=====================++This page names the parts of shirudo, says where each one runs and how+they depend on each other, and points to the page that explains each part+in depth. It describes the implementation; when the code and this page+disagree, the code is right.++Problem+-------++A target runs BPF that its operator ships as signed upatches, and root on+the target must not be able to run BPF of its own, remove what the+operator installed without a record, or rewrite the record. Root can issue+every system call, so none of these properties can rest on a userspace+process that root could stop, trace or bypass. We put each decision into+the kernel, on the call that changes state, and keep the userspace part+small, short-lived and verified at boot.++The operator side has the opposite problem. It holds the only secret, the+ML-DSA-87 signing key, and it must not need any state about the targets,+so that losing or rebuilding an operator host loses nothing but the key.++Operator and target+-------------------++One ``shirudo`` executable serves both roles. The role follows from what+is present on the machine, not from a build option. The operator holds+``signing_key.pem`` in its keys directory; a target holds the sealed+kernel keyrings, the private bpffs and the TPM register that ``shirudo+init`` set up this boot.++Operator commands that compile, sign or package, ``shirudo build``,+``shirudo bpm build``, ``shirudo bpm push``, ``shirudo bpm tree append``,+``shirudo image build``, ``shirudo image verify`` and ``shirudo keys+vouch``, execute the separate ``shirudo-build`` helper. Only that helper+links the CMS signer (``util/sign.c``) and the package builder and+publisher (``tools/shirudo-build/``). It runs ``clang`` to compile BPF,+libbpf's gen_loader to produce the signed loader, and ``veritysetup`` to+format and check images. The core binary finds it through+``SHIRUDO_BUILD``, the compiled-in libexec directory or ``PATH``.++On the target, commands use linked libraries and kernel interfaces only:+libbpf for ``bpf()``, raw ``keyctl(2)`` for keyrings, tpm2-tss over the+kernel TPM device for the register, libcrypto for digests and+certificates, libcurl for registries and OTLP. No target command starts+another program. Every command is a one-shot process; there is no daemon+and no listening socket.++Components+----------++Figure 1 shows the components and the paths between them.++.. figure:: /images/internals-architecture.svg+ :alt: The operator host publishes to an OCI registry. The target pulls+ from it. On the target, userspace commands from the runtime image+ call into the kernel, which holds the BPF LSM programs, the+ signed upatches, the keyrings and the private bpffs, and into the+ TPM, which holds the register. The TPM signs evidence that the+ operator checks offline.++ Figure 1. Components on the operator host and on a target. Nothing+ connects into the target; it pulls packages and pushes telemetry.++The binary embeds three BPF objects, compiled from ``bpf/`` and included+with ``.incbin`` in ``util/loader.c``:++``bpf2``+ BPF admission (``lsm/bpf``, ``lsm/bpf_map``, ``lsm/bpf_prog_load``),+ the guards of the private bpffs and of ``/run/shirudo``, the mount+ guards, the keyring and TPM command guards, the kexec refusal, the+ device-mapper and perf ioctl guards and the dm-verity device records.++``seal``+ Task marks (``bprm_check_security``, ``bprm_committed_creds``,+ ``task_alloc``), process protection (``ptrace_access_check``,+ ``perf_event_alloc``, ``mmap_file``, ``file_mprotect``) and the label+ checks on writable state.++``unload``+ The template that ``shirudo-build`` turns into the loader of an unload+ directive. The target never runs it.++``shirudo init`` loads ``bpf2`` and ``seal`` without a signature. They+are part of the binary that the authenticated initrd carries; the BPF+keyring does not cover them. All other BPF enters through the signed+loader path.++Two read-only dm-verity images carry what the target trusts:++Runtime image+ Mounted at ``/run/shirudo/runtime`` with ``ro,nodev,nosuid``. It holds+ the target binary, its bootstrap ``etc/shirudo/shirudo.conf``, the+ initial BPF certificate ``keys/cert.der`` and the config verification+ certificate. The UKI names its exact root hash.++Config image+ Mounted at ``/run/shirudo/config`` with ``ro,nodev,nosuid,noexec``. It+ holds registries, the upatch tree subscription, node labels,+ export settings, further vouched BPF certificates and revocations. A+ CMS signature over its root hash authorizes it, and a live update can+ replace it.++Writable state lives under ``/var/lib/shirudo``: the archived upatches+that boot restore loads, the eventlog, the package and tree state, the+image cache and the config activation journal. The first ``init`` labels+the tree with the ``security.bpf.shirudo`` extended attribute, shirudo+labels every inode it creates there, and the seal refuses changes to+labelled inodes by tasks without runtime authority.++Per-boot state lives under ``/run/shirudo``, a private tmpfs mount that+systemd carries from the initrd into the root file system. The private+bpffs at ``/run/shirudo/bpffs`` holds the pins that keep every+enforcement link and every upatch link attached, the frozen identity+map, the task, device and config-root maps and the tamper counters.+``/run/shirudo/eventlog.pending`` carries the record of the initrd run to+the root file system.++The systemd units run the commands. ``shirudo-initrd.service`` runs+``shirudo init`` in the initrd. ``shirudo.service`` runs it again in the+root file system through a drop-in that starts the binary from the+runtime image. Timers start ``shirudo bpm repo update`` and ``shirudo bpm+upgrade``, ``shirudo bpm tree sync``, the status keepalive and the map+export.++The TPM holds the measurement register, an NV extend index anchored in+PCR 9, the config PCR the bootstrap settings select, and the attestation+key that signs evidence.++How the parts depend on each other+----------------------------------++Runtime authority ties the kernel and userspace parts together. A task+has it when it carries a mark in the task map that both BPF objects+share. It gets the mark by a successful exec of a file on the runtime+image, or, as the initrd's ``init`` process, from a seed ``init`` writes+before it freezes the map. Every guard that lets shirudo do what it+refuses to everyone else asks for that mark, not for a user ID, a+capability or an executable path.++The keyrings tie the operator to the target. ``init`` enrolls the+initial certificate and the vouched certificates of the selected config+in ``.bpf``, the config verification certificate in ``.dm-verity``, and+seals both. The kernel verifies every upatch loader against ``.bpf`` and+every config root against its dm-verity trust path. The operator never+touches either keyring.++The register ties the target's state to evidence. Every change of the+loaded set, every tree operation and every live key revocation extends it+under a domain-separated tag, and the eventlog records the event beside+it. The operator predicts the register from the artifacts it signed and+checks evidence the TPM signed, without trusting the target's own account.++Delivery runs in one direction. The operator publishes to an OCI+registry, and a target timer pulls, verifies and loads. A ``.upatch``+copied to the target by any other means loads through the same path.+shirudo has no push transport and no fleet state.++Where to read more+------------------++- :doc:`signed-loader` explains how a signed loader installs an upatch,+ and why a userspace check could not.+- :doc:`enforcement` lists every LSM hook, what it refuses and in which+ order ``init`` attaches them.+- :doc:`seal` explains task marks and the labels on writable state.+- :doc:`boot-flow` follows ``init`` from the initrd to the root file+ system.+- :doc:`measurement-register` explains the register, the eventlog and+ attestation.+- :doc:`config-images` explains the runtime and config images and live+ activation.+- :doc:`kernel-interfaces` and :doc:`kernel-patches` list what shirudo+ needs from the kernel.+- :doc:`design-decisions` gives the reasons behind the design.+- :doc:`/security/threat-model` states what the design defends against+ and where it stops.diff --git a/Documentation/internals/boot-flow.rst b/Documentation/internals/boot-flow.rstnew file mode 100644index 00000000..ec86465d--- /dev/null+++ b/Documentation/internals/boot-flow.rst@@ -0,0 +1,223 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: Kernel developers, security reviewers++Boot from initrd to root+========================++``shirudo init`` runs twice on every boot: once in the initrd, where it+brings enforcement up, and once in the root file system, where it checks+what the first run left and adopts its record. This page follows both+runs step by step, says what crosses the switch to the root file system,+and what happens when a run fails.++Why the initrd+--------------++Enforcement protects nothing that happened before it attached. Every+process that runs before ``init`` could load BPF, hold a descriptor or+change state, and the evidence would not show it. The initrd is the+earliest point at which a systemd service can reach the state on the root+file system, and on a measured UKI boot the initrd is measured with the+UKI.++The register needs the initrd too. Its first write is possible only+while PCRs 9 and 11 hold the values ``init`` reads, and systemd extends+PCR 11 with ``leave-initrd`` before the switch to the root file system.+A binding made in the initrd is therefore one that nothing later can+repeat. :doc:`measurement-register` explains the policy.++Initrd run+----------++The dracut module ``90shirudo`` puts the binary, its bootstrap+``/etc/shirudo/shirudo.conf``, a copy of the certificates for the+pre-flight and ``shirudo-initrd.service`` into the initrd. The unit runs+after ``initrd-root-fs.target``, ``tpm2.target``,+``systemd-pcrphase-initrd.service`` and+``systemd-tpm2-setup-early.service``, and before ``initrd.target`` and+the switch to the root file system. It needs+``/sysroot/var/lib/shirudo``, remounts ``/sysroot`` read-write, and runs+``shirudo init`` with ``KeyringMode=inherit``.++``init`` then runs these steps. ``cmd_init()`` and ``run_init()`` in+``builtin-init.c`` are the reference.++#. Read the bootstrap settings from the initrd's+ ``/etc/shirudo/shirudo.conf``. ``runtime.image`` and+ ``runtime.root_hash`` must be present; the UKI authenticates both.+#. Run the pre-flight: root, the BPF LSM active, bpffs, the signed+ loader ABI, the certificates readable, ML-DSA-87 and accepted by the+ kernel, the BPF keyring present, the embedded objects present, the+ TPM reachable. A failed check ends ``init``.+#. Check that ``/`` is an initramfs and bind+ ``/sysroot/var/lib/shirudo`` recursively at ``/var/lib/shirudo``. The+ bind must be writable, because config selection is recorded there+ before the config PCR is extended.+#. Create ``/run/shirudo``, mount a private tmpfs there when it is still+ part of ``/run``, label it, and mount the private bpffs at+ ``/run/shirudo/bpffs`` with ``mode=0700,nosuid,nodev,noexec``.+#. Map the runtime image with dm-verity, check its root hash against+ ``runtime.root_hash``, read the whole mapping, mount it and read the+ runtime's bootstrap settings: ``config.image``,+ ``config.verification_key`` and ``config.pcr``.+#. Enroll the config verification certificate in the ``.dm-verity``+ keyring and seal it; the keyring must then hold that certificate+ alone.+#. Open the TPM and the activation journal under+ ``/var/lib/shirudo/config-update``, and select the config: the one+ the activation record names, or ``config.image`` on a first boot. Map+ it, which makes the kernel verify its root signature, read it and+ validate its contents.+#. Build the BPF trust set from the runtime's ``keys/cert.der`` and the+ config's vouched certificates, less its revocations, with the+ runtime certificate always included. Enroll the set in the ``.bpf``+ keyring, seal it, and check that it holds exactly that set.+#. Unmount the runtime and the candidate config and remove their+ mappings.+#. Label the state tree on the first boot.+#. Load and attach the enforcement objects, in the order+ :doc:`enforcement` gives.+#. Walk the state tree again, which fills the directory marks of the+ seal.+#. Map and mount the runtime image again, this time under the guards, so that+ the device record makes its executables eligible for runtime+ authority. It is mounted at ``/run/shirudo/runtime`` with+ ``ro,nodev,nosuid``.+#. Activate the selected config as a boot event: record the selection as+ pending, extend the config PCR, read the PCR back, append the event to+ the config log, apply the config's revocations and mount it at+ ``/run/shirudo/config`` with ``ro,nodev,nosuid,noexec``.+#. Restore the archived upatches from ``/var/lib/shirudo/upatches`` in+ sorted order through the signed loader path. An entry without the+ seal label, or one that is not a valid artifact, is ignored. The+ first failure stops the restore; upatches restored before it stay+ loaded.+#. Bind the measurement register, extend it with one ``init`` event that+ covers the trust set, the restored set and the tree root, extend+ PCR 9 with the anchor, and write the record to+ ``/run/shirudo/eventlog.pending``.+#. Mark the config selection complete.+#. Detach the ``/var/lib/shirudo`` bind.++The keyrings are sealed before any guard attaches, by the initrd's+binary, which the boot chain measured. The runtime image that later+commands run from is mounted under the guards.++What crosses the switch to the root file system+-----------------------------------------------++systemd moves ``/run`` with its mounts into the root file system. The+private tmpfs at ``/run/shirudo`` goes with it, and with that tmpfs:++- the private bpffs, whose pins keep every enforcement link and every+ restored upatch attached, and which holds the identity map, the task+ and device maps and the tamper counters;+- the runtime image at ``/run/shirudo/runtime`` and the config image at+ ``/run/shirudo/config``;+- ``eventlog.pending``, the record of the initrd run.++The sealed keyrings, the device records and the TPM state are kernel and+TPM state and do not depend on the switch. The bind of+``/var/lib/shirudo`` does not cross; the root file system has the same+directory at that path.++Root file system run+--------------------++``shirudo.service`` runs in the root file system before+``sysinit.target``, after ``local-fs.target``,+``systemd-tpm2-setup-early.service`` and+``systemd-pcrnvdone.service``, and only when ``/run/shirudo/runtime`` is+a mount point. The drop-in that ``shirudo-gen-runtime --unit-output``+writes replaces its ``ExecStart`` with the binary on the runtime image,+so this ``init`` earns runtime authority by its exec.++This run reads the runtime root hash from the frozen identity map rather+than from a file, checks that every pinned enforcement link is an LSM+link to the expected kernel function on the expected maps, and checks+that the runtime mount is the recorded runtime device. Then:++- the private bpffs is already mounted, and the ``.bpf`` keyring serial+ and the runtime root equal the frozen record;+- the state tree must already carry its label, and ``init`` labels+ nothing;+- the pending record is appended to ``/var/lib/shirudo/eventlog`` under+ the eventlog lock, and ``eventlog.pending`` is removed;+- the enforcement links are found pinned, and nothing attaches;+- the config record is checked: same TPM boot, not pending, and the+ config log replays to the live config PCR;+- every archived upatch must already be loaded with the archived+ payload; one that is not is refused as ``tampered``;+- the register is found written under the recorded name, and no event+ is added.++The root run therefore adds nothing to the register. The ``init`` event+from the initrd stays the only one for the boot until an operator+changes the loaded set.++When init fails+---------------++A failed ``init`` does not stop the boot. ``initrd.target`` only wants+``shirudo-initrd.service``, the unit has no failure action, and shirudo+never halts or reboots a node. What the target runs afterwards depends on+where ``init`` stopped:++- Before the enforcement objects attach (settings, pre-flight, images,+ keyrings): nothing is attached. A failure inside the attach sequence+ unpins what was attached, with the same result. The runtime image is+ not mounted, so ``shirudo.service`` is skipped, and the target runs+ without enforcement.+- After attaching, before the runtime image is mounted again: the guards+ are in place, ``shirudo.service`` is skipped, and commands that need+ the runtime image fail.+- After the config boot event (a restore failure, a register that cannot+ be bound): the guards are in place and the config selection stays+ pending. ``shirudo.service`` refuses with the activation pending, and+ every target command except ``shirudo status`` and ``shirudo image+ status`` refuses until a reboot.++``shirudo status`` and attestation are how such a target shows. Without+a complete initrd ``init`` the register is not bound in the initrd, and a+verifier that requires an initrd binding rejects the target's evidence.++Hibernation and TPM resets+--------------------------++shirudo does not refuse hibernation. The register and the config record+are tied to the TPM's reset and restart counts. When the TPM is reset or+restarted without a reboot, which a resume from hibernation can do, the+register is cleared and one of the counts changes while the kernel's+boot ID stays. Register extensions then fail with ``tpm_error``, and every+target command except ``shirudo status`` and ``shirudo image status``+refuses because the config record belongs to another TPM boot. Nothing+re-runs ``init`` automatically. A manual ``shirudo init`` records a new+config boot event and binds the register again, from the root file system+and with the PCR values of that moment; a verifier that requires an+initrd binding rejects that evidence.++Kexec+-----++``lsm/kernel_load_data`` and ``lsm/kernel_read_file`` refuse every kexec+kernel image and initramfs to every caller, through ``kexec_load(2)`` and+``kexec_file_load(2)``, crash kernels included, once ``init`` has+attached them (``Kexec``). A kexec would hand the machine to a kernel of+the caller's choosing with the TPM as it is, so the evidence of this boot+would vouch for what runs after it. A crash kernel that kdump needs must+be loaded before ``init`` runs, or it is refused.++Related+-------++- :doc:`/concepts/background/initrd-dracut` and+ :doc:`/concepts/background/boot` for the boot chain.+- :doc:`/operate/boot-integration` for setting up the initrd and the+ UKI.+- :doc:`config-images` for the images and the activation journal.+- :doc:`/security/threat-model` for what a failed or skipped ``init``+ means for the trust model.diff --git a/Documentation/internals/config-images.rst b/Documentation/internals/config-images.rstnew file mode 100644index 00000000..1fbc3255--- /dev/null+++ b/Documentation/internals/config-images.rst@@ -0,0 +1,308 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: Kernel developers, security reviewers++Config images and dm-verity+===========================++A target runs shirudo from a read-only runtime image and takes its+updatable settings from a separate, signed config image. Both are+dm-verity file systems. This page explains why there are two, which+settings live where, how a target maps and checks an image, which keys+verify it, how a config becomes active, what happens when an activation+is interrupted, and what can change without a reboot.++Problem+-------++The binary that holds runtime authority has to be the one the operator+built, and the settings that decide trust, the certificates, the TPM+settings and the config PCR, have to be the operator's too. On the host+root file system root can replace both. Some settings must still change+while a target runs: repositories, the tree subscription, node labels,+export destinations, revocations.++Why a signed file is not enough+-------------------------------++A signature on a file is checked when the file is read. Root can change+the file after the check and before the use, or the target can read it+twice and get two answers. A userspace verifier also runs before the+thing it is supposed to establish, so its own integrity is the question.++dm-verity moves the check into the kernel and makes it continuous. The+kernel checks every block it reads from the data device against a hash+tree whose root hash is the one trusted value. Whoever knows that the+root hash is right knows that every read returns the operator's bytes,+for as long as the mapping exists. :doc:`/concepts/background/dm-verity`+explains the mechanism.++Two images+----------++The runtime image carries what may execute and what decides trust. The+UKI's bootstrap settings name its exact root hash, so no other image can+take its place, and no signature is involved. It is mounted at+``/run/shirudo/runtime`` with ``ro,nodev,nosuid``. Every executable on it+is eligible for runtime authority, which is why a config image, however+validly signed, can never be one.++The config image carries what may change during a boot. A CMS signature+over its root hash authorizes it, so the operator can sign a new one at+any time. It is mounted at ``/run/shirudo/config`` with+``ro,nodev,nosuid,noexec``, and no exec from it grants authority.++Bootstrap files+---------------++Two different files carry bootstrap settings, and each takes keys the+other refuses.++.. list-table::+ :header-rows: 1+ :widths: 30 35 35++ * - File+ - Required keys+ - Further keys+ * - ``/etc/shirudo/shirudo.conf`` in the initrd, inside the UKI+ - ``runtime.image``, the cache prefix of the runtime image, and+ ``runtime.root_hash``, its 64-character root hash+ - ``tpm.tcti``, ``tpm.owner_auth``, and the ``config.*`` keys+ * - ``etc/shirudo/shirudo.conf`` on the runtime image+ - ``config.image``, the initial config prefix;+ ``config.verification_key``, a certificate path under+ ``/run/shirudo/runtime/``; ``config.pcr``, a PCR from 0 to 15+ other than 9 and 11+ - ``tpm.tcti``, ``tpm.owner_auth``, ``tls.classical_hosts``. Any+ ``runtime.*`` key is refused.++The initrd's file must exist before the runtime image is known, and the+runtime root hash it names is known only once the runtime image is built,+so the runtime image is built first. Where both files set a key, the+runtime image's value wins, and the root file system's ``init`` reads only+the runtime image's file. With a TPM owner password, both files carry+``tpm.owner_auth``: ``init`` in the initrd creates the NV writer with the+initrd's file, and later commands use the runtime image's. The initrd's+file must then not be readable by group or others. The initial BPF+certificate is not a setting: it is ``keys/cert.der`` on the runtime+image.+:doc:`/reference/formats/configuration` lists every key.++Image files+-----------++An image is four files with a common prefix:++``<prefix>.img``+ The ext4 data.++``<prefix>.verity``+ The hash tree with a standard ``veritysetup`` superblock: format+ version 1, hash type 1, SHA-256, 4096-byte data and hash blocks.++``<prefix>.roothash``+ The root hash as exactly 64 lowercase hexadecimal characters.++``<prefix>.p7s``+ For a config image, a detached CMS signature over exactly those 64+ ASCII bytes, without a newline, at most 16 KiB. The target does not+ read one for the runtime image.++The target parses the superblock and checks the sizes of both files+against it; it builds no hash tree of its own. ``shirudo image build``+and ``shirudo image verify`` on the operator use ``veritysetup``.++Mapping and checking an image+-----------------------------++``util/dm_verity.c`` maps an image through kernel interfaces only:++#. Attach the data and hash files to loop devices.+#. Create a device-mapper device. For a config image, stage the root the+ task expects in ``shirudo_roots``.+#. Load a read-only ``verity`` table:+ ``1 <data> <hash> 4096 4096 <blocks> 1 sha256 <root> <salt>``. For a+ config image the table adds ``2 root_hash_sig_key_desc <desc>``, and+ the signature travels as a ``user`` key with a random description in+ the thread keyring, whose permission allows only a possessor's+ search.+#. Resume the device and read the table back; it must name the same+ devices, root and salt.+#. Read the whole mapping once, with ``O_DIRECT``, so that every block+ passes the hash check before anything parses the contents, then check+ that the loop devices still back the same files.+#. Mount it as ext4 with ``ro,nodev,nosuid``, ``noexec`` for a config,+ and ``noload``, and check that the mount is that device.++When the table loads, the kernel verifies the config root signature. When+the device resumes, ``lsm.s/bdev_setintegrity`` sees its root hash and+records the device: as runtime when the root equals the runtime root+frozen in the identity map, as config when it equals the root the calling+task staged, which is then used up. Any other mapping gets no record. The+records are what make a runtime executable eligible for authority, and+what the mount guards protect. :doc:`enforcement` lists the hooks.++Which keys verify a config+--------------------------++The kernel's dm-verity signature check tries the built-in trusted keys+first, together with the secondary keyring when+``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_SECONDARY_KEYRING`` is set, then+the platform keyring when+``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_PLATFORM_KEYRING`` is set, and the+``.dm-verity`` keyring last, once it is sealed and holds a key.++``init`` in the initrd enrolls the certificate that+``config.verification_key`` names in ``.dm-verity`` and seals the+keyring, which the kernel leaves open only when booted with+``dm_verity.keyring_unsealed=1``. The keyring must then hold that+certificate alone, and ``lsm/key_permission`` keeps root from unlinking+it. The ``.bpf`` keyring is not involved: a valid config signature never+authorizes BPF, and a BPF signature never authorizes a config.++Config contents+---------------++A config image holds:++- ``etc/shirudo/shirudo.conf``, which must exist and may set only+ ``eventlog.max_bytes`` and ``map_export.*`` keys;+- ``etc/shirudo/bpm/registries.d/`` and ``etc/shirudo/bpm/keys/``, the+ repositories and their certificates;+- ``etc/shirudo/bpm/upatch-tree.conf``, the tree subscription;+- ``etc/shirudo/node.labels``, the labels tree selectors match;+- ``keys/trusted/``, further BPF certificates, each with a ``.vouch``+ signature by a certificate already in the set;+- ``keys/revoked/``, revoked certificates named+ ``<fingerprint>.der``.++The target validates the tree before it uses it: regular files and+directories only, all on the image's device, at most 65536 entries and 32+levels. It opens everything below the image root through the root+descriptor, never through a path string.++The BPF trust set of a config is the runtime image's ``keys/cert.der``+plus every certificate in ``keys/trusted/`` that a member of the set+vouches for, less the revoked ones.++Activation+----------++``shirudo image update <prefix>`` copies the four files, from a local+prefix or an ``https://`` one, into a staging directory under+``/var/lib/shirudo/images``, maps and checks the image there, and only+then publishes it in the cache as ``<root hash>.img`` and its siblings.+It then activates it:++#. Map and check the candidate as above, require the device record,+ mount it at ``/run/shirudo/config-candidate``, validate it, and check+ that every certificate of its trust set is in the sealed ``.bpf``+ keyring.+#. Record the selection in the journal as pending.+#. Extend the config PCR with the update event.+#. Read the PCR and the TPM's reset and restart counts back; the PCR must+ hold the expected value.+#. Append the event to the config log.+#. Apply the revocations: unlink each revoked certificate that is in the+ ``.bpf`` keyring, extend the register with a ``key_revoke`` event,+ and purge the archived upatches the certificate signed, unloading+ those that are loaded.+#. Mount the candidate at ``/run/shirudo/config``.+#. Record the selection as complete.++At boot, ``init`` runs the same sequence as a boot event for the selected+config, but completes it only at the end of ``init``, after the restore+and the register binding. :doc:`boot-flow` gives the boot order.++The journal lives in ``/var/lib/shirudo/config-update``: ``state`` holds+the current selection and whether it is pending, ``events`` the config+log, and ``lock`` the lock every target command holds while it runs,+waiting up to 30 seconds for another command to finish. The files must+belong to the user running shirudo, have mode ``0600`` and one link.+:doc:`measurement-register` gives the event digest and what attestation+checks.++Interrupted activation+----------------------++An activation can stop after the pending record is on disk: a crash, a+power loss, a failed mount or a failed revocation. The record then stays+pending, and shirudo does not try again within the same TPM boot. Every+target command except ``shirudo status`` and ``shirudo image status``+refuses while the selection is pending, and so does ``init``. The node+keeps running, with the guards and the loaded upatches it had; shirudo+never reboots it.++The reboot is the recovery. At the next boot, ``init`` selects the+config the record names, pending or not, maps and checks it again,+records a fresh boot event in the config PCR and completes. It never+repeats the previous boot's extension.++Two other states refuse the same way. When the config PCR no longer+replays from the config log, because something else extended it,+commands refuse with ``EUCLEAN`` until a reboot. When the TPM's reset or+restart count differs from the record's, commands refuse with+``ESTALE`` until ``init`` runs again and records a boot event for the new+TPM boot.++What can change without a reboot+--------------------------------++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Change+ - How+ * - Repositories, tree subscription, node labels, eventlog limit,+ export settings+ - A new config image and ``shirudo image update``.+ * - Revoking an enrolled BPF certificate+ - A new config image with the certificate in ``keys/revoked/``. It+ is unlinked, measured and its upatches purged.+ * - Adding a BPF certificate+ - Not live. The ``.bpf`` keyring is sealed, so activation refuses a+ candidate whose trust set holds a certificate the keyring lacks.+ * - The config verification certificate, the config PCR, the TPM+ settings, ``tls.classical_hosts``, the initial BPF certificate+ - Not live. They are on the runtime image, which only a new UKI and+ a reboot replace.+ * - The shirudo binary+ - Not live, for the same reason.++Two boot-time rules bear on the changes that need a reboot. ``init``+selects the config that the journal names, not ``config.image``, once a+selection exists. And it enrolls the config verification certificate of+the runtime image before it maps that config. A reboot therefore does not+pick up a config that was never activated, and a runtime image with+another config verification certificate needs a selected config that+certificate verifies. :doc:`/operate/keys` covers key changes.++Limits+------++These are properties of the design as implemented.+:doc:`/security/threat-model` gives their consequences.++- Every key the kernel trusts for dm-verity signatures verifies a config:+ the built-in trusted keys, and the secondary and platform keyrings when+ the kernel is built to use them. shirudo does not check the signer of a+ config in userspace.+- Nothing prevents rollback. Any config ever signed by an accepted key+ can be activated again.+- Any process that can send ``TPM2_PCR_Extend`` can extend the config+ PCR; the register's writer guard does not cover it.+- shirudo does not remove cached images.++Related+-------++- :doc:`/concepts/background/dm-verity` for the mechanism.+- :doc:`/operate/boot-integration` for building the images and the+ initrd.+- :doc:`/reference/cli/image` for the ``shirudo image`` commands.+- :doc:`/reference/formats/configuration` for the settings.diff --git a/Documentation/internals/design-decisions.rst b/Documentation/internals/design-decisions.rstnew file mode 100644index 00000000..e11fbeb9--- /dev/null+++ b/Documentation/internals/design-decisions.rst@@ -0,0 +1,223 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: Kernel developers, security reviewers++Design decisions+================++This page collects the decisions that shape shirudo, the reason for each+and what it costs. Most of them follow from one goal: keep the code a+target has to trust, the kernel and shirudo, as small as possible, and+make every security decision where root cannot step around it.++A single binary for operator and target+---------------------------------------++The same ``shirudo`` executable runs on the operator host and on a+target, and its role follows from what is present: the signing key on+the operator, the sealed keyrings and the register on a target.++The reason is that both sides compute the same things. The operator's+``shirudo attest predict`` calls the functions the target uses to compute+the ``init`` event and fold the register, and both sides parse+``.upatch`` files with the same code. A second implementation would be+a second thing to get right and to keep in step.++The cost is a binary that contains operator commands a target never+runs. The code that holds the private key does not ship that way: the+CMS signer and the package builder and publisher are linked only into+the separate ``shirudo-build`` helper, and the core binary dispatches to+it.++Agentless targets+-----------------++A target runs no daemon and opens no listening socket. Every operation+is a one-shot ``shirudo`` command, started by hand or by a systemd timer.++A long-running process is something root can trace, stop or feed+input to for as long as it runs, and a socket is an attack surface for+anyone who can reach it. shirudo needs neither. Pins in the private bpffs+keep the enforcement and the upatches attached after ``init`` exits, the+kernel enforces without a helper, and the TPM keeps the record.++The cost is that nothing on the target watches continuously. Package+updates and telemetry run on timer periods, and a target reports its+state only when a command runs.++Pull-based delivery+-------------------++The operator publishes signed packages to an OCI registry, and each+target pulls, verifies and loads them. shirudo has no push transport, no+SSH integration and no fleet inventory.++Nothing connects into a target, so a target has no inbound path to+defend. Registries already exist, scale, and need no shirudo code to+operate. The registry is not trusted: the signatures carry the trust, and+a ``.upatch`` that reaches a target any other way loads through the same+signature check. How an administrator reaches a target stays outside+shirudo.++The cost is latency: a fix reaches a target at its next update run, not+when the operator publishes it.++Stateless operator+------------------++The operator writes only its keypair (``shirudo genkey``) and the+artifacts and reports the caller names. It keeps no caches, no state+files, no logs of its own and no record of targets.++An operator host can then be rebuilt from the key alone, and there is no+operator state to tamper with or to leak. Every expectation a verifier+needs, such as ``--expect-chain``, either comes from the caller or is+computed from the artifacts by ``shirudo attest predict``.++Signed loaders instead of a userspace gate+------------------------------------------++The kernel verifies each upatch's signature on the ``BPF_PROG_LOAD`` that+loads it, and BPF LSM programs refuse every other way to install or+remove BPF. :doc:`signed-loader` explains why a service that checks+signatures before calling ``bpf()`` cannot work: root does not have to+ask it.++The cost is a dependence on a recent kernel ABI (see below), and a+detach that still runs in userspace because ``bpf_sys_bpf()`` offers no+detach.++ML-DSA-87 only+--------------++shirudo signs with ML-DSA-87 (FIPS 204, the largest parameter set) and+nothing else. ``shirudo genkey`` has no algorithm option, and the+signer, ``shirudo keys vouch`` and ``shirudo image verify`` refuse other+keys.++One algorithm means no negotiation and no downgrade. A key that anchors+a fleet's trust has to outlive hardware generations, so it gets the+largest margin of the post-quantum parameter sets, for about 2 KiB more+per signature than the smallest. The kernel verifies ML-DSA natively, so+the target needs no code of its own for it.++The costs: OpenSSL 3.5 or later on both sides, ``CONFIG_CRYPTO_MLDSA``+in the target kernel, and signatures of several kilobytes. TPM evidence+stays classical, because TPMs sign with ECDSA and RSA. The target checks+the algorithm of the certificates its pre-flight reads; it does not check+repository certificates or certificates a signed config adds, which+:doc:`/security/threat-model` lists.++A per-boot NV register+----------------------++The measurement lives in an NV extend index that clears at every TPM+reset, not in a PCR and not in a persistent index.++A stock system has no free static PCR, and PCR 23 is resettable. A+persistent index would carry history across boots and need an+authorization secret. A per-boot register starts from zero, so its value+is a function of the trust set, the restored upatches and the events+since boot, and the operator can predict it without any history. Its+write policy allows the first write only while PCRs 9 and 11 hold their+initrd values, and every write only with a signature from a TPM-held key+whose extension command the kernel guards. The register follows the+construction of systemd's NvPCRs and adds the authorized writer.+:doc:`measurement-register` has the details.++A TPM 2.0 is mandatory. There is no unmeasured mode, because an+unmeasured target cannot be told from a tampered one.++Enforcement from the initrd+---------------------------++Enforcement comes up from the authenticated initrd, before the root file+system's services run, and ``init`` runs again from the root file system+to check and adopt what the first run did.++Anything that runs before enforcement can do what enforcement refuses,+and the evidence would not show it; the initrd shortens that window to+what the measured boot itself runs. The register can be bound only while+PCR 11 holds the ``enter-initrd`` value, which systemd changes at+``leave-initrd``, so a binding made in the initrd is one that nothing+later can repeat. :doc:`boot-flow` follows both runs.++The costs: a dracut module, a measured UKI, an initrd that has to carry+the binary and its settings, and a second run of ``init``. A failed+``init`` does not stop the boot.++A single instance per host+--------------------------++One shirudo instance runs per host. The ``.bpf`` keyring, the private+bpffs, ``/var/lib/shirudo``, the ``security.bpf.shirudo`` attribute and+the NV index are single-tenant.++The kernel has one ``.bpf`` keyring and one set of LSM hooks, and the+guards would have to tell instances apart to allow one and refuse the+other. A single instance keeps each guard a single comparison.++CO-RE+-----++The enforcement objects and the upatches read kernel structures through+CO-RE relocations against the kernel's BTF, so one build runs on kernels+whose structure layouts differ.++A hard-coded offset signs as well as a relocated one, but on another+kernel it reads the wrong field; the signature cannot tell. CO-RE turns+a layout difference into a load failure.++State in BPF arenas+-------------------++An upatch that accumulates records keeps them in one+``BPF_MAP_TYPE_ARENA`` map and ships a ``shirudo_serialize__<map>``+program that walks them. Hash and array maps hold only what cannot live+in an arena: task, socket and per-CPU scratch state, keys the kernel+owns, and the serializer output.++An arena gives one consistent snapshot, memory the serializer can reset+between exports, and an overflow count the exported record carries. An+element-by-element read of a plain map gives a torn view, and a full+table drops records without saying so. ``upatches/kernel-obs/obs_table.h``+is the template. :doc:`/upatches/maps-arenas-serializers` explains it.++No target shell-outs+--------------------++Target commands use linked libraries and kernel interfaces and never+start another program. The dm-verity setup, for example, is made of+loop and device-mapper ioctls, not a call to ``veritysetup``, and the+target has no userspace hash-tree code: the kernel's dm-verity checks+every block.++A program the target started would be code outside the runtime image,+and an exec of a file outside the image clears the caller's runtime+authority. It would also bring its own environment, search path and+libraries into the trust decision. The operator's helper may run+``clang`` and ``veritysetup``; the operator holds no target authority.++No legacy kernel fallbacks+--------------------------++shirudo requires the signed-loader ABI, the BPF LSM hooks and current+clang and LLVM. A missing kernel feature fails the build, the pre-flight+or the load. There is no compatibility mode.++A fallback is a second, weaker path, and an attacker chooses which path+runs by choosing the conditions. The ABI check reads the kernel's BTF+rather than its release string, because a development tree can carry the+ABI before its version number says so. :doc:`kernel-interfaces` lists+what is required. The cost is a narrow set of kernels: bpf-next or a+release that contains its signed-loader work, with the patches in+:doc:`kernel-patches`.++Related+-------++- :doc:`architecture` for how the parts fit together.+- :doc:`/security/threat-model` for what the design defends against.diff --git a/Documentation/internals/enforcement.rst b/Documentation/internals/enforcement.rstnew file mode 100644index 00000000..bc52de7b--- /dev/null+++ b/Documentation/internals/enforcement.rst@@ -0,0 +1,547 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: Kernel developers, security reviewers++Enforcement in the kernel+=========================++shirudo's enforcement is a set of BPF LSM programs that ``shirudo init``+attaches early in boot. This page explains what they protect, how they+tell shirudo from root, in which order ``init`` attaches them and why,+and ends with a reference table of every hook.++Problem+-------++A signature gate on program loads is not enough on its own. Root could+leave the gate in place and remove what makes it work: unlink the pin+that keeps a link attached, unmount the bpffs that holds the pins, write+a map that a guard reads, unlink the certificate from the keyring, extend+the measurement register with an event of its own choosing, trace the+process that holds authority, or boot another kernel by kexec with this+boot's TPM state. Each of these is an ordinary system call that root is+allowed to make.++A check in userspace cannot refuse any of them, for the reason+:doc:`signed-loader` gives: root does not have to ask. The refusal has to+happen in the kernel, on the call itself. BPF LSM programs do that. Each+one runs at an LSM hook, sees the call's arguments and the calling task,+and returns an error that the kernel hands back to the caller.++Two objects+-----------++The binary embeds two BPF objects. ``bpf2`` (``bpf/bpf2.c`` with+``bpf/admission.h``) holds BPF admission and the guards of shirudo's own+kernel state. ``seal`` (``bpf/seal.c`` with ``bpf/seal.h``) holds the+task marks, the process protection and the checks on writable state.+``init`` loads both without a signature, from the binary the+authenticated initrd carries.++The objects share five maps, which ``init`` hands from ``bpf2`` to+``seal`` with ``bpf_map__reuse_fd()`` and pins in the private bpffs:++.. list-table::+ :header-rows: 1+ :widths: 22 22 56++ * - Map+ - Pin+ - Contents+ * - ``shirudo_bpffs_sb``+ - ``identity``+ - The record ``init`` freezes: device numbers of the private bpffs+ and of ``/run/shirudo``, the runtime root hash, the ``.bpf``+ keyring serial and kind, the serials of the enrolled keys, the+ ``.dm-verity`` keyring and key serials, the NV index, the NV+ writer's public modulus and seed, and the attestation key name.+ * - ``shirudo_tasks``+ - ``task_authority``+ - Task storage with each task's mark and exec candidate.+ * - ``shirudo_devices``+ - ``devices``+ - The dm-verity devices recorded as runtime or config, up to 128.+ * - ``shirudo_roots``+ - ``config_roots``+ - Task storage with the config root an authorized task expects to+ map next.+ * - ``shirudo_tamper``+ - ``tamper``+ - One counter per refusal point, see :doc:`/security/tamper-counters`.++``init`` freezes every one of them against userspace writes except+``shirudo_roots``, which an authorized task writes before each config+mapping. ``bpf2`` keeps a sixth map, ``shirudo_mnt_rec``, with the bpffs+mount it records, and ``seal`` keeps its scratch buffer and the inode+storage of directory marks.++Telling shirudo from root+-------------------------++Every guard that allows shirudo what it refuses to everyone else asks one+question: does the calling task have runtime authority? A task has it+when it carries a mark in ``shirudo_tasks``. A task gets the mark by a+successful exec of a file on the authenticated runtime image, or, for the+``init`` process in the initrd, from a seed ``init`` writes before it+freezes the map. A fork inherits the mark. :doc:`seal` explains how the+mark is granted and cleared.++The ``bpf()`` hooks have a second discriminator. ``lsm/bpf`` and+``lsm/bpf_prog_load`` receive ``bool kernel``, which is true for calls a+signed loader makes from inside the kernel. Those calls are allowed;+userspace calls are filtered.++No guard looks at the user ID, a capability or the path of the+executable. Root has all of those, and a path can be replaced.++What the hooks guard+--------------------++The BPF system call+ ``lsm/bpf`` admits a userspace ``BPF_PROG_LOAD`` only for a+ ``BPF_PROG_TYPE_SYSCALL`` program with a signature, and+ ``lsm/bpf_prog_load`` admits it only when the kernel verified it+ against the ``.bpf`` keyring. Map creation, update and freeze, test+ runs, link creation, raw tracepoint attach and pinning need runtime+ authority. Every command shirudo has not classified, including+ ``BPF_LINK_DETACH``, ``BPF_LINK_UPDATE``, ``BPF_PROG_DETACH``,+ ``BPF_BTF_LOAD`` and every map delete, is refused to every userspace+ caller, shirudo included, so a command a later kernel adds stays+ refused until someone classifies it.++Descriptors and pins+ A descriptor keeps its object alive. A link held open stays attached+ after shirudo unpins it for an unload, a revocation purge or the undo+ of a refused load, and no LSM hook sees a link descriptor being handed+ out. A map descriptor reads what the serializers own and, if+ writable, changes what the guards read. ``lsm/bpf`` therefore refuses+ ``BPF_OBJ_GET``, ``BPF_MAP_GET_FD_BY_ID`` and ``BPF_LINK_GET_FD_BY_ID``+ to a task without runtime authority. ``lsm/bpf_map``, which every+ route to a map descriptor passes, refuses every map descriptor to+ such a task, read-only or writable. ``lsm/file_open`` refuses such a+ task the opening of anything but a directory in the private bpffs,+ since a pin opened as a file reads a map's contents; directories stay+ listable. ``BPF_PROG_GET_FD_BY_ID`` and ``BPF_BTF_GET_FD_BY_ID`` stay+ allowed. Root without runtime authority therefore cannot read+ shirudo's maps or hold one of its links open by pin or by id.+ ``lsm/file_ioctl`` refuses ``PERF_EVENT_IOC_SET_BPF``, which binds a+ program to a perf event without a ``bpf()`` command, to the same+ tasks.++The private bpffs and /run/shirudo+ The pins are the only reference that keeps the enforcement links and+ the upatch links attached once ``init`` exits. The inode hooks of+ ``bpf2`` refuse unlink, rmdir, mkdir, symlink, hard link, rename and+ extended attribute changes in the private bpffs and in the+ ``/run/shirudo`` tmpfs to tasks without runtime authority. The mount+ hooks refuse to every caller, shirudo included, the unmount, move,+ remount and mount-over of the bpffs, and any unmount that would take+ the recorded bpffs mount down with it, through its subtree or through+ mount propagation.++Keyrings and the register+ ``lsm/key_permission`` refuses write, setattr, unlink and+ unpossessed search on the ``.bpf`` and ``.dm-verity`` keyrings and the+ keys ``init`` recorded, so root cannot remove a trust anchor.+ ``lsm/tpm_command`` refuses ``TPM2_NV_Extend`` of shirudo's NV index+ to tasks without runtime authority, so a signature from the+ TPM-held writer key is not enough to change the register.++Images and device mapper+ ``lsm.s/bdev_setintegrity`` records which dm-verity devices hold the+ runtime image and the config image, the mount hooks refuse to unmount,+ move or cover them, and ``lsm/file_ioctl`` allows a task without+ runtime authority only the read-only device-mapper control commands.++Exec and processes+ ``seal`` grants and inherits the task mark and keeps ptrace and+ task-bound perf events away from marked tasks. ``bpf2`` runs every+ runtime executable in secure-exec mode, so the dynamic loader ignores+ ``LD_PRELOAD`` and the other unsafe variables, and refuses+ ``PR_SET_MM_EXE_FILE`` and ``PR_SET_MM_MAP`` to tasks without+ authority. ``seal`` refuses a marked task executable memory that does+ not come from the runtime image.++Kexec+ A kexec hands the machine to a kernel and initrd of the caller's+ choosing with the TPM as it is, so the evidence of this boot would+ vouch for whatever runs after. ``lsm/kernel_load_data`` and+ ``lsm/kernel_read_file`` refuse every kexec image and initramfs to+ every caller.++Writable state+ ``seal`` refuses changes to labelled inodes under+ ``/var/lib/shirudo`` to tasks without runtime authority.+ :doc:`seal` explains the labels.++Attach order+------------++``init_lsm()`` in ``builtin-init.c`` brings the enforcement up in this+order:++#. Load ``bpf2``.+#. Fill the identity map and freeze it.+#. Seed the bootstrap mark for its own process through a pidfd, freeze+ ``shirudo_tasks``, ``shirudo_devices`` and ``shirudo_tamper``, and pin+ them with ``shirudo_roots``. Pin the identity map.+#. Attach ``task_prctl``, ``bprm_check_security``, ``inode_rmdir``,+ ``inode_rename``, ``inode_mkdir``, ``inode_symlink``, ``inode_link``,+ ``kernel_load_data`` and ``kernel_read_file``.+#. Attach ``file_ioctl``, ``file_ioctl_compat``, ``bdev_setintegrity``+ and ``bdev_free_security``.+#. Attach ``inode_unlink``, ``inode_setxattr``, ``inode_removexattr``,+ ``key_permission`` and ``tpm_command``.+#. Attach the mount guards ``sb_umount``, ``move_mount``, ``sb_mount``,+ ``sb_remount`` and the ``file_open`` recorder, open the bpffs root so+ the recorder notes the mount, and freeze that record.+#. Load ``seal`` on the shared maps, freeze its scratch map, and attach+ its twenty hooks, then ``mmap_file`` and ``file_mprotect``.+#. Attach ``lsm/bpf_map``, then ``lsm/bpf_prog_load``, then ``lsm/bpf``.++``init`` pins every link as it attaches it, before the next fallible+step. A link that is not pinned detaches when ``init`` exits, and a+crash would leave an attached link nobody owns.++The order follows from three constraints. First, ``init`` loads the two+objects without a signature, and ``lsm/bpf`` and ``lsm/bpf_prog_load``+refuse an unsigned program load to every caller, ``init`` included, so+they attach last. Second, every guard reads the identity map, so the map+is complete and frozen before the first guard attaches; no guard ever+decides on a half-written record. Third, the+bpffs mount must be immutable before admission goes live, so the mount+guards and the bpffs inode guards attach before the seal and the+admission gates. ``init`` itself passes every guard on the way because+its bootstrap mark is in place before the first one attaches.++When any step fails, ``init`` unpins every link it attached and removes+the map pins, so no partial enforcement survives a failed ``init``.++Order at run time+-----------------++The order in which programs run on one hook is the reverse of the order+in which they attached. The kernel's BPF trampoline puts a new program at+the head of the list, and for an LSM hook that returns a value, a+non-zero return ends the list. Where ``bpf2`` and ``seal`` share a hook+(``bprm_check_security``, ``file_open``, ``inode_unlink``,+``inode_rename``, ``inode_setxattr``, ``inode_removexattr``,+``inode_mkdir``, ``inode_symlink``, ``inode_link``), the ``seal``+program runs first, and when it refuses, its errno and counter are the+ones the caller sees. A traced exec of a runtime file, for example, fails with+``EACCES`` from ``seal`` rather than ``EPERM`` from ``bpf2``.++The BPF LSM is one LSM among those the kernel runs. The kernel stops at+the first LSM that refuses, and each shirudo program returns an earlier+refusal unchanged. shirudo's verdicts can only add refusals to those of+SELinux, AppArmor, Smack or Yama; they never turn one of their refusals+into a permission.++Counters+--------++Most refusals increment a counter in ``shirudo_tamper``, a map+``init`` freezes against userspace writes and pins as ``tamper``.+``shirudo status`` reads it back. The counters, their meanings and what+an operator does about each are in :doc:`/security/tamper-counters`. The+table below names the counter of each refusal and says where a refusal+is not counted.++Hook reference+--------------++``bpf2`` and ``seal`` name the object. "Authority" means runtime+authority as above. The last column says what the program does when it+cannot decide: when a read fails, when storage cannot be allocated, or+when the record it needs is missing.++.. list-table::+ :header-rows: 1+ :widths: 17 37 8 18 20++ * - Hook+ - Refuses, and allows+ - Errno+ - Counter+ - Cannot decide+ * - ``lsm/bpf`` (``bpf2``)+ - With ``kernel`` false: a program load of another type than+ ``BPF_PROG_TYPE_SYSCALL``, or without a signature size, to every+ caller. Map create, update and freeze, test run, link create, raw+ tracepoint open, object pin, object get, map and link fd by id,+ to a task without authority. Every unclassified command to every+ caller. Allows every call with ``kernel`` true and the read-only+ commands: map lookups, ``GET_NEXT_ID``, ``PROG_GET_FD_BY_ID``,+ ``BTF_GET_FD_BY_ID``, ``OBJ_GET_INFO_BY_FD``, ``PROG_QUERY``,+ ``TASK_FD_QUERY``.+ - ``EACCES``+ - ``LoadNotLoader``, ``LoadUnsigned``, ``MapCreate``, ``MapWrite``,+ ``ProgRun``, ``ProgAttach``, ``ObjPin``, ``ObjGet``,+ ``BpfCommand``+ - Closed: unclassified commands are refused.+ * - ``lsm/bpf_prog_load`` (``bpf2``)+ - A userspace load the kernel did not verify, verified against+ another keyring kind than ``.bpf``, or with a non-zero keyring+ serial other than the frozen one. Allows ``kernel`` true.+ - ``EACCES``+ - ``LoadUnverified``, ``LoadKeyringKind``, ``LoadKeyring`` (never+ reached: the kernel records serial 0 for ``.bpf``)+ - Closed: no frozen keyring serial refuses every load, uncounted.+ * - ``lsm/bpf_map`` (``bpf2``)+ - Every map descriptor to a task without authority.+ - ``EACCES``+ - ``MapFdWrite`` (writable), ``ObjGet`` (read-only)+ - Closed.+ * - ``lsm/file_open`` (``bpf2``)+ - Opening a non-directory inode of the private bpffs, through any+ mount of it, to a task without authority. Records the bpffs mount+ when the bootstrap task opens its root.+ - ``EACCES``+ - ``ObjGet``+ - Closed.+ * - ``lsm/file_ioctl``, ``lsm/file_ioctl_compat`` (``bpf2``)+ - ``PERF_EVENT_IOC_SET_BPF`` on any file, and every device-mapper+ control command except ``DM_VERSION``, ``DM_LIST_DEVICES``,+ ``DM_DEV_STATUS``, ``DM_DEV_WAIT``, ``DM_TABLE_DEPS``,+ ``DM_TABLE_STATUS``, ``DM_LIST_VERSIONS`` and+ ``DM_GET_TARGET_VERSION`` on the control device (10:236), to a+ task without authority.+ - ``EACCES`` (perf), ``EPERM`` (DM)+ - ``PerfAttach``; DM refusals uncounted+ - Closed: unknown DM commands are refused.+ * - ``lsm/inode_unlink``, ``lsm/inode_rmdir``, ``lsm/inode_mkdir``,+ ``lsm/inode_symlink``, ``lsm/inode_link``, ``lsm/inode_rename``,+ ``lsm/inode_setxattr``, ``lsm/inode_removexattr`` (``bpf2``)+ - The operation in the private bpffs or the ``/run/shirudo`` tmpfs+ to a task without authority. Rename checks both directories.+ Other file systems are not checked.+ - ``EPERM``+ - In the bpffs: ``PinUnlink``, ``PinEntry`` (mkdir, symlink, link),+ ``PinRename``, ``PinXattr``. Rmdir and ``/run/shirudo`` refusals+ uncounted.+ - Closed for those two file systems.+ * - ``lsm/sb_umount`` (``bpf2``)+ - To every caller: unmounting the bpffs, an unmount whose subtree or+ propagation reaches the recorded bpffs mount, unmounting+ ``/run/shirudo``, unmounting the runtime image. Unmounting a+ config image to a task without authority.+ - ``EPERM``+ - ``BpffsUmount``, ``BpffsUmountAbove``; image and ``/run/shirudo``+ refusals uncounted+ - Closed: a walk beyond 1024 mounts, 32 levels or 4 masters is+ refused.+ * - ``lsm/move_mount`` (``bpf2``)+ - To every caller: moving the bpffs, the ``/run/shirudo`` mount or+ the runtime image, or moving a mount onto the bpffs or the runtime+ image. Moving a mount onto a path in ``/run/shirudo``, and moving+ a config image or onto one, to a task without authority.+ - ``EPERM``+ - ``BpffsMount``; others uncounted+ - Closed.+ * - ``lsm/sb_mount`` (``bpf2``)+ - To every caller: a mount onto the bpffs or the runtime image, and+ a propagation change of the ``/run/shirudo`` mount. A mount onto a+ path in ``/run/shirudo`` or on a config image to a task without+ authority. The source of a bind or legacy move is not checked.+ - ``EPERM``+ - ``BpffsMount``; others uncounted+ - Closed.+ * - ``lsm/sb_remount`` (``bpf2``)+ - Remounting the bpffs, ``/run/shirudo`` or a recorded image, to+ every caller.+ - ``EPERM``+ - ``BpffsMount``; others uncounted+ - Closed.+ * - ``lsm.s/bdev_setintegrity`` (``bpf2``)+ - Records a dm-verity device as runtime when its SHA-256 root equals+ the frozen runtime root, or as config when it equals the root an+ authorized task staged for this mapping; the staged root is used+ once. Refuses a second record for a recorded device, a root it+ cannot read, disk sequence 0 and a full record map.+ - ``EPERM``, ``EACCES``, ``ENOMEM``+ - Uncounted+ - Other mappings get no record and so no authority.+ * - ``lsm/bdev_free_security`` (``bpf2``)+ - Removes the device record.+ - None+ - None+ - The kernel can skip this call; lookups also compare the device+ number and disk sequence.+ * - ``lsm/key_permission`` (``bpf2``)+ - Write, setattr, unlink, and search through an unpossessed+ reference, on the ``.bpf`` keyring, the ``.dm-verity`` keyring and+ its key, and the keys enrolled in ``.bpf``, to a task without+ authority. Allows view, read, link and possessed search, and every+ other key.+ - ``EACCES``+ - ``KeyringWrite``+ - Open before ``init`` records a keyring serial.+ * - ``lsm/tpm_command`` (``bpf2``)+ - ``TPM2_NV_Extend`` of shirudo's NV index to a task without+ authority. A command shorter than 10 bytes, an ``NV_Extend``+ shorter than 18 bytes, or one it cannot read, to every caller.+ Allows every other command.+ - ``EACCES``+ - ``TpmExtend``+ - Closed for malformed commands.+ * - ``lsm/task_prctl`` (``bpf2``)+ - ``PR_SET_MM`` with ``PR_SET_MM_EXE_FILE`` or ``PR_SET_MM_MAP`` to+ a task without authority. Answers the enforcement probe, option+ ``0x53520001``, with errno 1002.+ - ``EPERM``+ - ``ExeIdentity``+ - Closed.+ * - ``lsm/bprm_check_security`` (``bpf2``)+ - Sets secure-exec for every exec of a runtime file, and refuses a+ traced one. The ``seal`` program on this hook runs first.+ - ``EPERM``+ - ``ExecTraced``+ - A file not recorded as runtime gets no secure-exec, and no mark.+ * - ``lsm.s/bprm_check_security`` (``seal``)+ - Stages the mark candidate: trusted when the file is a direct, not+ overlay, inode on a recorded runtime device. Refuses a trusted+ candidate that is traced or has a seccomp filter.+ - ``EACCES``+ - ``ExecTraced``; seccomp uncounted+ - Closed: no task storage refuses the exec with ``ENOMEM``.+ * - ``lsm.s/bprm_committed_creds`` (``seal``)+ - Commits the staged candidate as the task's mark when an exec+ succeeds.+ - None+ - None+ - No task storage leaves the task without authority.+ * - ``lsm/task_alloc`` (``seal``)+ - Copies a marked parent's mark to the child.+ - ``ENOMEM``+ - None+ - Closed: no storage refuses the fork of a marked parent.+ * - ``lsm/ptrace_access_check`` (``seal``)+ - Every ptrace access mode against a marked task, which covers+ attach, ``/proc/<pid>/mem``, ``pidfd_getfd()`` and+ ``process_vm_readv()``.+ - ``EACCES``+ - ``SealPtrace``+ - Closed.+ * - ``lsm/perf_event_alloc`` (``seal``)+ - A perf event bound to a marked task. CPU-wide events have no task+ and are not checked.+ - ``EACCES``+ - ``SealPerf``+ - Not applicable.+ * - ``lsm/mmap_file`` (``seal``)+ - An executable mapping in a marked task, other than the bootstrap+ task, that is writable or does not come from a runtime file.+ - ``EACCES``+ - Uncounted+ - Closed.+ * - ``lsm/file_mprotect`` (``seal``)+ - In the same tasks: making an executable mapping writable, or making+ executable a mapping that was not, or that is not from a runtime+ file.+ - ``EACCES``+ - Uncounted+ - Closed.+ * - ``lsm/kernel_load_data``, ``lsm/kernel_read_file`` (``bpf2``)+ - Every kexec kernel image and initramfs, by either system call, to+ every caller.+ - ``EPERM``+ - ``Kexec``+ - Unconditional.+ * - ``lsm.s/file_open`` (``seal``)+ - A write open of a labelled file to a task without authority. On a+ directory open, records or clears the directory mark from its+ label.+ - ``EACCES``+ - ``SealWrite``+ - See the label verdict below.+ * - ``lsm.s/inode_unlink``, ``lsm.s/inode_setattr``,+ ``lsm.s/inode_removexattr`` (``seal``)+ - The operation on a labelled inode to a task without authority.+ Setattr covers truncate, chmod, chown and timestamps.+ - ``EACCES``+ - ``SealUnlink``, ``SealSetattr``, ``SealXattr``+ - See the label verdict below.+ * - ``lsm.s/inode_setxattr`` (``seal``)+ - Setting ``security.bpf.shirudo`` on any inode, and any other name+ on a labelled inode, to a task without authority.+ - ``EACCES``+ - ``SealLabel``, ``SealXattr``+ - See the label verdict below.+ * - ``lsm.s/inode_rename`` (``seal``)+ - A labelled source, a marked destination directory or a labelled+ inode it would replace, to a task without authority.+ - ``EACCES``+ - ``SealRename``, ``SealEntry``+ - See the label verdict below.+ * - ``lsm/inode_create``, ``lsm/inode_mkdir``, ``lsm/inode_symlink``,+ ``lsm/inode_mknod``, ``lsm/inode_link`` (``seal``)+ - A new entry in a marked directory to a task without authority.+ The source inode of a hard link is not checked.+ - ``EACCES``+ - ``SealEntry``+ - Open: a directory without a cached mark is not checked.+ * - ``lsm/inode_init_security`` (``seal``)+ - Labels a new inode under a marked directory, inside the creation,+ and marks a new directory. Refuses the creation when it cannot add+ the label.+ - ``EACCES``+ - Uncounted+ - Open without a parent mark; closed when the label cannot be added.+ * - ``lsm/inode_copy_up`` (``seal``)+ - The overlay copy-up of a marked inode.+ - ``EPERM``+ - ``SealCopyUp``+ - Open: an inode without a cached mark is not checked.+ * - ``lsm.s/inode_post_setxattr``, ``lsm.s/inode_post_removexattr``+ (``seal``)+ - Refresh a directory's mark from its label after the change.+ - None+ - None+ - A failed read removes the mark.++The label verdict of the ``seal`` hooks reads ``security.bpf.shirudo``+with the caller's permission. No label (``ENODATA``), no security+extended attributes on the file system (``EOPNOTSUPP``) and a label the+caller may not read (``EACCES``, ``EPERM``) count as unlabelled, and the+operation goes ahead. A label of any length, any other read error and a+failure to allocate the scratch buffer require runtime authority.+:doc:`seal` explains why and what follows from it.++Limits+------++The hooks decide only what reaches them. These paths do not:++- The ``kernel`` argument is true for every ``bpf()`` call through a+ kernel pointer, including BPF that kernel code loads with+ ``kern_sys_bpf()``, such as a light skeleton in a module.+- ``BPF_PROG_GET_FD_BY_ID`` stays open. ``lsm/bpf`` and+ ``lsm/file_ioctl`` refuse the ``bpf()`` attach commands and the perf+ ioctl to tasks without authority; other kernel interfaces that take a+ program descriptor are not hooked here.+- ``mount_setattr(2)`` has no LSM hook, ``pivot_root(2)`` is not hooked,+ and ``lsm/sb_mount`` does not check the source of a bind or legacy+ move.+- A perf event bound to a task before that task execs the runtime image+ survives the exec, and CPU-wide events and probes on the runtime+ binary are not checked.+- ``lsm/tpm_command`` sees commands written to ``/dev/tpm0`` and+ ``/dev/tpmrm0``. A TPM reached around the kernel's TPM character+ devices is outside it. The hook is not in bpf-next;+ :doc:`kernel-patches` describes the patch the test kernel carries.+- ``shirudo_roots`` and the directory marks are not frozen, by design.+ Device records are limited to 128.+- Several refusals are uncounted, as the table shows.++:doc:`seal` lists the gaps of the writable-state seal, and+:doc:`/security/threat-model` gives the residual risks.++Related+-------++- :doc:`/concepts/background/bpf-lsm` for how BPF LSM programs work.+- :doc:`signed-loader` for the load path these hooks guard.+- :doc:`/security/tamper-counters` for the counters.diff --git a/Documentation/internals/index.rst b/Documentation/internals/index.rstnew file mode 100644index 00000000..5a7172cf--- /dev/null+++ b/Documentation/internals/index.rst@@ -0,0 +1,28 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++Internals+=========++How shirudo works inside the kernel and on a target, and why it is built+this way: the signed loader path, the LSM programs and the seal, the+boot sequence, the measurement register, the images, and the kernel+interfaces and patches it depends on. These pages are for kernel+developers and security reviewers who need to judge the design.+Operators do not need them to run shirudo; :doc:`/security/threat-model`+states what the mechanisms here defend against and where they stop.++.. toctree::+ :titlesonly:++ architecture+ signed-loader+ enforcement+ seal+ boot-flow+ measurement-register+ config-images+ kernel-interfaces+ kernel-patches+ design-decisionsdiff --git a/Documentation/internals/kernel-interfaces.rst b/Documentation/internals/kernel-interfaces.rstnew file mode 100644index 00000000..7110e009--- /dev/null+++ b/Documentation/internals/kernel-interfaces.rst@@ -0,0 +1,482 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Kernel developers, security reviewers++Kernel interfaces+=================++The kernel interfaces shirudo uses on a target, with the exact arguments.+The operator side uses none of them. :doc:`signed-loader` and+:doc:`enforcement` explain why each is needed.++Kernel baseline+---------------++.. list-table::+ :header-rows: 1+ :widths: 22 48 30++ * - Commit+ - Subject+ - First release+ * - ``b55d26bd1891``+ - block,lsm: add LSM blob and new LSM hooks for block devices+ - v6.12+ * - ``0c3772a8db1f``+ - x86/ftrace: Implement DYNAMIC_FTRACE_WITH_JMP+ - v6.19+ * - ``033724b1c627``+ - dm-verity: add dm-verity keyring+ - v7.0+ * - ``63a673e8a411``+ - bpf: Expose signature verdict via bpf_prog_aux+ - v7.2+ * - ``3f8c65b06faf``+ - bpf: have bpf_real_data_inode() take a struct file+ - v7.2+ * - ``264d8fd2794f``+ - bpf, keys: Add a bpf keyring for program signature validation+ - bpf-next+ * - ``abaa0835b4f3``+ - bpf: Refuse caller-supplied keyrings when the bpf one is active+ - bpf-next+ * - ``ff0d1c0915d1``+ - bpf, lsm: Let BPF LSM provide xattrs at inode creation+ - bpf-next+ * - ``1041fca2ee8a``+ - keys: add KEY_SPEC_DM_VERITY_KEYRING+ - 7.4 cycle++bpf-next contains the signed-loader ABI at merge ``0867b7bfa9de``.+``testing/vm/build-kernel.sh`` accepts bpf-next or a release of v7.4 or+later. shirudo defines ``KEY_SPEC_DM_VERITY_KEYRING`` (-10) itself when+the UAPI headers lack it. The ``tpm_command`` LSM hook is not+in bpf-next; :doc:`kernel-patches` lists the patches the test kernel+carries. A kernel is admitted by the ABI check below, not by its release+string.++Signing ABI check+-----------------++``kernel_abi_check()`` (``util/kernel_abi.c``) reads the running kernel's+BTF and requires:++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Member+ - Required type+ * - ``struct bpf_map.sha``+ - ``u8[32]``, not a bit field+ * - ``struct bpf_map.excl_prog_sha``+ - pointer to a byte, not a bit field+ * - ``struct bpf_prog_aux.sig``+ - struct+ * - ``struct bpf_prog_aux.sig.keyring_serial``+ - ``s32``+ * - ``struct bpf_prog_aux.sig.keyring_type``+ - ``u8``+ * - ``struct bpf_prog_aux.sig.verdict``+ - ``u8``++The pre-flight runs it as ``signed_loader_kernel_abi``, and every+``upatch load`` and ``upatch unload`` without ``--no-precheck`` runs it+before ``BPF_PROG_LOAD``. A failure is ``kernel_abi_unsupported``.+``lsm/bpf_prog_load`` compares ``sig.verdict`` with ``BPF_SIG_VERIFIED``+and ``sig.keyring_type`` with ``BPF_SIG_KEYRING_BPF``; these enum values+are compiled into ``bpf2`` from the ``vmlinux.h`` of the build.++Signature verification+----------------------++Kernel behavior a signed load relies on (``bpf_prog_verify_signature()``+in ``kernel/bpf/verifier.c``):++.. list-table::+ :header-rows: 1+ :widths: 35 65++ * - Input+ - Behavior+ * - ``signature``, ``signature_size``+ - Size 1 to 64 KiB. Verified when ``signature`` is set.+ * - ``keyring_id``+ - ``0``: built-in keys, kind ``BPF_SIG_KEYRING_BUILTIN``. ``1``:+ secondary keyring. ``2``: platform keyring. ``KEY_SPEC_BPF_KEYRING``+ (-9): the ``.bpf`` keyring, kind ``BPF_SIG_KEYRING_BPF``, serial+ recorded as 0; ``ENOKEY`` when the keyring is empty or not sealed.+ Any other id: a user keyring, refused with ``EPERM`` when booted+ with ``bpf.keyring_unsealed=1``.+ * - ``fd_array``, ``fd_array_cnt``+ - The maps resolved from ``fd_array`` are folded into the signed+ data: ``insns || value(map_0) || ...``. Each must be an array, frozen,+ without active writers, and exclusive (``excl_prog_sha`` set).+ * - ``core_relo_cnt``+ - Must be 0 for a signed program (``EACCES``).+ * - Result+ - On success, ``prog->aux->sig`` records serial, kind and+ ``BPF_SIG_VERIFIED``. Order inside ``bpf_check()``: resolve+ ``fd_array``, verify the signature, ``security_bpf_prog_load()``,+ then the verifier's analysis. ``security_bpf()`` runs earlier, at+ system call entry.++A map with ``excl_prog_hash`` set binds only to a program whose SHA-256+digest equals it.++BPF system calls of a load+--------------------------++Every call below is made from userspace with ``kernel`` false, except+where the caller is the loader.++.. list-table::+ :header-rows: 1+ :widths: 24 76++ * - Command+ - Attributes set+ * - ``BPF_MAP_CREATE``+ - ``map_type`` ``BPF_MAP_TYPE_ARRAY``, ``key_size`` 4,+ ``value_size`` the data length, ``max_entries`` 1, ``map_name``+ ``__loader.map``, ``excl_prog_hash`` SHA-256 of the loader+ instructions, ``excl_prog_hash_size`` 32.+ * - ``BPF_MAP_UPDATE_ELEM``+ - ``map_fd``, ``key`` 0, ``value`` the data, ``flags`` 0.+ * - ``BPF_MAP_FREEZE``+ - ``map_fd``.+ * - ``BPF_PROG_LOAD``+ - ``prog_type`` ``BPF_PROG_TYPE_SYSCALL``, ``insns``, ``insn_cnt``,+ ``license`` ``Dual BSD/GPL``, ``prog_flags`` ``BPF_F_SLEEPABLE``,+ ``prog_name`` the upatch name with characters other than+ ``[A-Za-z0-9_.]`` replaced by ``_``, cut to 15, ``signature``,+ ``signature_size``, ``keyring_id`` ``KEY_SPEC_BPF_KEYRING``,+ ``fd_array`` holding the map, ``fd_array_cnt`` 1, ``log_level`` 1,+ ``log_size`` 16 MiB, ``log_buf``.+ * - ``BPF_PROG_TEST_RUN``+ - ``prog_fd`` the loader, ``ctx_in`` and ``ctx_size_in``: a context+ of ``sz``, ``flags``, ``log_level`` 1, ``log_size`` 16 MiB and+ ``log_buf``, followed by one map descriptor (``map_fd``,+ ``max_entries``, ``initial_value``) per map and one program+ descriptor (``prog_fd``) per program, and 1024 bytes of padding.+ The loader fills the descriptors.+ * - loader: ``BPF_MAP_CREATE``, ``BPF_MAP_UPDATE_ELEM``,+ ``BPF_MAP_FREEZE``, ``BPF_PROG_LOAD`` through ``bpf_sys_bpf()``+ - As gen_loader recorded them.+ * - ``BPF_RAW_TRACEPOINT_OPEN``+ - Attach kind 0 for a program that is not ``BPF_PROG_TYPE_LSM``:+ ``raw_tracepoint.name`` 0, ``prog_fd``.+ * - ``BPF_LINK_CREATE``+ - Attach kind 0 for ``BPF_PROG_TYPE_LSM``: ``target_fd`` 0,+ ``attach_type`` ``BPF_LSM_MAC``. Kind 5, ``fmod_ret``:+ ``attach_type`` ``BPF_MODIFY_RETURN``. Kinds 3 and 4,+ ``cgroup_skb``: ``target_fd`` an ``O_DIRECTORY`` descriptor of+ ``/sys/fs/cgroup``, ``attach_type`` ``BPF_CGROUP_INET_INGRESS`` or+ ``BPF_CGROUP_INET_EGRESS``. Kinds 1 and 2, kprobe and kretprobe:+ ``target_fd`` a perf event, ``attach_type`` ``BPF_PERF_EVENT``.+ Kind 6, netfilter: ``attach_type`` ``BPF_NETFILTER``, ``pf`` 10+ (``NFPROTO_IPV6``), ``hooknum`` 0 (``NF_INET_PRE_ROUTING``),+ ``priority`` -450 (``NF_IP6_PRI_RAW_BEFORE_DEFRAG``), ``flags`` 0.+ Kind 7, ``uprobe.multi``: ``attach_type``+ ``BPF_TRACE_UPROBE_MULTI``, ``offsets``, ``cnt``, ``flags``+ ``BPF_F_UPROBE_MULTI_PATH_FD``, ``path_fd`` a descriptor of the+ target binary opened and checked by build ID.+ * - ``BPF_OBJ_GET_INFO_BY_FD``+ - On each link before it is pinned. Cgroup links: ``cgroup_id`` 1.+ Netfilter: ``pf``, ``hooknum``, ``priority`` as set, and the+ caller's network namespace cookie (``SO_NETNS_COOKIE``) 7. Kprobe:+ perf event type, function name and offset as signed. Uprobe:+ offset count. ``fmod_ret``: ``BPF_MODIFY_RETURN``.+ * - ``BPF_OBJ_PIN``+ - Links at ``upatches/<name>/link`` or ``link_<n>``, serializer+ programs at ``serializers/<map>``, the test-run program at+ ``test``, maps at ``maps/<map>``, under ``/run/shirudo/bpffs``.++A kprobe link's perf event comes from ``perf_event_open(2)`` with+``type`` read from ``/sys/bus/event_source/devices/kprobe/type``,+``config1`` the symbol, ``config2`` the offset, the bit named in+``.../kprobe/format/retprobe`` set in ``config`` for a kretprobe, ``pid``+-1, ``cpu`` 0 and ``PERF_FLAG_FD_CLOEXEC``.++An unload directive makes the first four calls and no others.++``init`` loads ``bpf2`` and ``seal`` with libbpf (``BPF_BTF_LOAD``,+``BPF_MAP_CREATE``, ``BPF_PROG_LOAD`` of ``BPF_PROG_TYPE_LSM``), attaches+each program with ``BPF_LINK_CREATE`` and ``BPF_LSM_MAC``, and pins it.+It populates the identity map with ``BPF_MAP_UPDATE_ELEM``, seeds+``shirudo_tasks`` with a pidfd as key, and freezes maps with+``BPF_MAP_FREEZE``.++Extended attributes+-------------------++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Name+ - Use+ * - ``security.bpf.shirudo``+ - The seal label on writable state and on ``/run/shirudo``.+ * - ``security.bpf.shirudo.payload``+ - The 32-byte payload digest on each upatch's pin directory in the+ private bpffs.++LSM hooks+---------++.. list-table::+ :header-rows: 1+ :widths: 50 20 30++ * - Hook+ - Object+ - Kernel condition+ * - ``bpf``, ``bpf_map``, ``bpf_prog_load``+ - ``bpf2``+ - ``CONFIG_BPF_SYSCALL``+ * - ``key_permission``+ - ``bpf2``+ - ``CONFIG_KEYS``+ * - ``tpm_command``+ - ``bpf2``+ - Carried patch+ * - ``task_prctl``, ``bprm_check_security``, ``inode_unlink``,+ ``inode_rmdir``, ``inode_mkdir``, ``inode_symlink``,+ ``inode_link``, ``inode_rename``, ``inode_setxattr``,+ ``inode_removexattr``, ``kernel_load_data``, ``kernel_read_file``,+ ``file_open``, ``sb_umount``, ``move_mount``, ``sb_mount``,+ ``sb_remount``, ``file_ioctl``, ``file_ioctl_compat``,+ ``bdev_setintegrity`` (sleepable), ``bdev_free_security``+ - ``bpf2``+ - None+ * - ``perf_event_alloc``+ - ``seal``+ - ``CONFIG_PERF_EVENTS``+ * - ``bprm_check_security``, ``bprm_committed_creds``, ``file_open``,+ ``inode_unlink``, ``inode_rename``, ``inode_setattr``,+ ``inode_setxattr``, ``inode_removexattr``,+ ``inode_post_setxattr``, ``inode_post_removexattr`` (all+ sleepable); ``task_alloc``, ``ptrace_access_check``,+ ``inode_copy_up``, ``inode_init_security``, ``inode_create``,+ ``inode_mkdir``, ``inode_symlink``, ``inode_mknod``,+ ``inode_link``, ``mmap_file``, ``file_mprotect``+ - ``seal``+ - None++A missing hook makes the object fail to load. :doc:`enforcement` gives+each hook's verdicts.++Kfuncs and helpers+------------------++.. list-table::+ :header-rows: 1+ :widths: 35 65++ * - Kfunc+ - Use+ * - ``bpf_get_file_xattr()``, ``bpf_get_dentry_xattr()``+ - Read ``security.bpf.shirudo``. Sleepable; check ``MAY_READ`` for+ the calling task.+ * - ``bpf_inode_init_xattr()``+ - Add the label in ``inode_init_security``.+ * - ``bpf_real_data_inode()``+ - Tell an overlay copy from a direct inode at exec. Sleepable.+ * - ``bpf_iter_num_new()``, ``bpf_iter_num_next()``,+ ``bpf_iter_num_destroy()``+ - Bounded loops (``bpf_for``) of the mount walk.++Helpers: ``bpf_map_lookup_elem()``, ``bpf_map_update_elem()``,+``bpf_map_delete_elem()``, ``bpf_task_storage_get()``,+``bpf_inode_storage_get()``, ``bpf_inode_storage_delete()``,+``bpf_get_current_task_btf()``, ``bpf_probe_read_kernel()``,+``bpf_probe_read_kernel_str()``, ``bpf_bprm_opts_set()`` with+``BPF_F_BPRM_SECUREEXEC``, ``bpf_dynptr_from_mem()``,+``bpf_strncmp()``.++Map types: ``BPF_MAP_TYPE_ARRAY``, ``BPF_MAP_TYPE_HASH``,+``BPF_MAP_TYPE_TASK_STORAGE``, ``BPF_MAP_TYPE_INODE_STORAGE``.++Keyrings+--------++.. list-table::+ :header-rows: 1+ :widths: 50 50++ * - Call+ - Use+ * - ``keyctl(KEYCTL_GET_KEYRING_ID, KEY_SPEC_BPF_KEYRING)``+ - Serial of ``.bpf``.+ * - ``add_key("asymmetric", NULL, <der>, KEY_SPEC_BPF_KEYRING)``+ - Enroll a BPF certificate.+ * - ``keyctl(KEYCTL_RESTRICT_KEYRING, KEY_SPEC_BPF_KEYRING, NULL,+ NULL)``+ - Seal ``.bpf``: no restriction type, every later link refused.+ * - ``keyctl(KEYCTL_GET_KEYRING_ID, KEY_SPEC_DM_VERITY_KEYRING)``,+ ``add_key(..., KEY_SPEC_DM_VERITY_KEYRING)``,+ ``keyctl(KEYCTL_RESTRICT_KEYRING, KEY_SPEC_DM_VERITY_KEYRING, ...)``+ - The same for ``.dm-verity`` (-10) and the config verification+ certificate.+ * - ``keyctl(KEYCTL_READ, <ring>)``, ``keyctl(KEYCTL_DESCRIBE, <key>)``+ - List a keyring and compare it with the expected set.+ * - ``keyctl(KEYCTL_UNLINK, <key>, <ring>)``+ - Remove a revoked certificate from ``.bpf``.+ * - ``add_key("asymmetric", ..., KEY_SPEC_THREAD_KEYRING)``+ - Probe whether the kernel parses a certificate, then unlink it.+ * - ``add_key("user", "shirudo-verity-<hex>", <sig>,+ KEY_SPEC_THREAD_KEYRING)``,+ ``keyctl(KEYCTL_SETPERM, <key>, KEY_POS_SEARCH)``+ - Hand a config root signature to dm-verity as+ ``root_hash_sig_key_desc``.+ * - ``keyctl(KEYCTL_GET_KEYRING_ID, KEY_SPEC_USER_KEYRING)``+ - Pre-flight check that keys are available.++Device mapper and loop+----------------------++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Call+ - Use+ * - ``LOOP_CTL_GET_FREE``, ``LOOP_CONFIGURE``+ - Attach an image file read-only with ``LO_FLAGS_READ_ONLY``,+ ``LO_FLAGS_AUTOCLEAR``, 4096-byte blocks and a size limit.+ * - ``LOOP_GET_STATUS64``+ - Check that a loop device still backs the image file.+ * - ``DM_DEV_CREATE``, ``DM_TABLE_LOAD`` with ``DM_READONLY_FLAG``,+ ``DM_DEV_SUSPEND`` to resume, ``DM_TABLE_STATUS``,+ ``DM_DEV_REMOVE``, ``DM_LIST_DEVICES``+ - Create, check, list and remove ``verity`` mappings.+ * - ``BLKGETDISKSEQ``, ``BLKGETSIZE64``, ``BLKROGET``+ - Identify a mapping and check its size and read-only state.++Process setup and prctl+-----------------------++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Call+ - Use+ * - ``prctl(0x53520001)``+ - Enforcement probe. ``lsm/task_prctl`` fails it with errno 1002+ when ``bpf2`` is attached; ``EINVAL`` or ``ENOSYS`` means it is+ not.+ * - ``prctl(PR_SET_DUMPABLE, 0)``, ``prctl(PR_SET_NO_NEW_PRIVS, 1)``,+ ``prctl(PR_SET_PTRACER, 0)``+ - Process hardening before every command.+ * - ``setrlimit(RLIMIT_CORE, 0)``, ``mlockall(MCL_CURRENT |+ MCL_FUTURE)``+ - No core dumps; memory kept out of swap. A failed ``mlockall``+ ends the command.+ * - ``pidfd_open(getpid(), 0)``+ - Key for the bootstrap mark in ``shirudo_tasks`` and the expected+ config root in ``shirudo_roots``.++Mounts+------++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Mount+ - Options+ * - ``tmpfs`` at ``/run/shirudo``+ - ``nosuid,nodev,noexec``, ``mode=0700,size=16M``, made private+ recursively.+ * - ``bpf`` at ``/run/shirudo/bpffs``+ - ``nosuid,nodev,noexec``, ``mode=0700``.+ * - ext4 runtime image at ``/run/shirudo/runtime``+ - ``ro,nodev,nosuid``, ``noload``.+ * - ext4 config image at ``/run/shirudo/config``+ - ``ro,nodev,nosuid,noexec``, ``noload``.+ * - bind of ``/sysroot/var/lib/shirudo`` at ``/var/lib/shirudo``+ - Recursive, in the initrd only, detached when ``init`` exits.++Kconfig+-------++.. list-table::+ :header-rows: 1+ :widths: 45 55++ * - Option+ - Why+ * - ``CONFIG_BPF``, ``CONFIG_BPF_SYSCALL``, ``CONFIG_BPF_JIT``+ - ``bpf()``, the JIT, bpffs.+ * - ``CONFIG_SECURITY``, ``CONFIG_BPF_LSM``, ``CONFIG_BPF_EVENTS``,+ ``bpf`` in ``CONFIG_LSM`` or ``lsm=``+ - The BPF LSM. ``CONFIG_BPF_LSM`` depends on ``CONFIG_BPF_EVENTS``.+ * - ``CONFIG_SECURITYFS``+ - ``/sys/kernel/security/lsm`` for the ``bpf_lsm_active`` check.+ * - ``CONFIG_FUNCTION_TRACER``, ``CONFIG_DYNAMIC_FTRACE``,+ ``CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS``+ - BPF trampolines, which every LSM program attaches through.+ * - ``CONFIG_DEBUG_INFO_BTF``+ - CO-RE, the ABI check, the check of the pinned guard links.+ * - ``CONFIG_PERF_EVENTS``+ - The ``perf_event_alloc`` hook.+ * - ``CONFIG_KEYS``, ``CONFIG_ASYMMETRIC_KEY_TYPE``,+ ``CONFIG_ASYMMETRIC_PUBLIC_KEY_SUBTYPE``,+ ``CONFIG_X509_CERTIFICATE_PARSER``,+ ``CONFIG_PKCS7_MESSAGE_PARSER``,+ ``CONFIG_SYSTEM_DATA_VERIFICATION``+ - The keyrings, certificates and CMS verification.+ * - ``CONFIG_CRYPTO_MLDSA``, ``CONFIG_CRYPTO_SHA512``,+ ``CONFIG_CRYPTO_SHA256``+ - ML-DSA-87 certificates and signatures; the SHA-512 digest in the+ CMS signed attributes; SHA-256 digests.+ * - ``CONFIG_TCG_TPM`` and a driver, ``CONFIG_TCG_TIS`` or+ ``CONFIG_TCG_CRB``+ - The TPM.+ * - ``CONFIG_MD``, ``CONFIG_BLK_DEV_DM``, ``CONFIG_DM_VERITY``,+ ``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG``, ``CONFIG_BLK_DEV_LOOP``,+ ``CONFIG_EXT4_FS``+ - The runtime and config images.+ * - ``CONFIG_EXT4_FS_SECURITY``+ - Security extended attributes when the state is on ext4.+ * - ``CONFIG_TMPFS``, ``CONFIG_TMPFS_XATTR``+ - The label on ``/run/shirudo``.+ * - ``CONFIG_BLK_DEV_INITRD``+ - The initrd ``init`` runs in.++``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_SECONDARY_KEYRING`` and+``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_PLATFORM_KEYRING`` widen the keys+that verify a config; see :doc:`config-images`. ``CONFIG_SECCOMP=n``+is handled: the seal then sees no seccomp state. The attach kinds of+upatches can need further options; see :doc:`/upatches/attach-kinds`.++``testing/vm/build-kernel.sh`` enforces its own list with+``require_config``, which also covers what the test fixtures and the test+VM need.++Kernel command line+-------------------++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Parameter+ - Why+ * - ``bpf.keyring_unsealed=1``+ - The kernel leaves ``.bpf`` open for ``init`` to enroll and seal,+ and refuses user keyrings for signed loads. Without it, the+ keyring is sealed empty at boot and ``init`` fails.+ * - ``dm_verity.keyring_unsealed=1``+ - The kernel leaves ``.dm-verity`` open for ``init`` to enroll the+ config verification certificate and seal.+ * - ``lsm=`` including ``bpf``+ - When ``CONFIG_LSM`` does not include it.++``shirudo-gen-initrd --print-cmdline`` prints the two keyring parameters.+Both belong on the UKI's authenticated command line.diff --git a/Documentation/internals/kernel-patches.rst b/Documentation/internals/kernel-patches.rstnew file mode 100644index 00000000..76cad275--- /dev/null+++ b/Documentation/internals/kernel-patches.rst@@ -0,0 +1,139 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Kernel developers, security reviewers++Carried kernel patches+======================++The kernel patches in ``kernel/`` of the shirudo tree. The test kernel+build applies them; a production kernel needs the same changes.++Summary+-------++.. list-table::+ :header-rows: 1+ :widths: 34 22 22 22++ * - Patch+ - Author+ - In bpf-next+ - Architectures+ * - ``0001-x86-ftrace-Mark-jmp-mode-by-clearing-bit-63-of-the-trampoline-address.patch``+ - Daniel Borkmann+ - No+ - x86-64+ * - ``0002-tpm-Let-LSMs-inspect-userspace-commands.patch``+ - KP Singh+ - No+ - All++"In bpf-next" was checked against the bpf-next tree at commit+``4169c9c90532``: ``include/linux/ftrace.h`` there still marks jmp mode+with bit 0, and ``include/linux/lsm_hook_defs.h`` has no ``tpm_command``+hook.++How the test kernel applies them+--------------------------------++``make -C testing kernel`` passes ``KERNEL_PATCHES``, which defaults to+``kernel/`` when that directory holds patches.+``testing/vm/build-kernel.sh`` applies each patch in name order with+``git apply --index`` and commits it, and skips a patch whose reverse+already applies. A patch that applies neither way fails the build.++x86 ftrace jmp mode+-------------------++Subject+ x86/ftrace: Mark jmp mode by clearing bit 63 of the trampoline+ address++Fixes+ ``0c3772a8db1f`` ("x86/ftrace: Implement DYNAMIC_FTRACE_WITH_JMP"),+ first released in v6.19.++Files+ ``arch/x86/kernel/ftrace_64.S``, ``include/linux/ftrace.h``,+ ``kernel/trace/Kconfig``.++What it changes+ With ``CONFIG_DYNAMIC_FTRACE_WITH_JMP``, which only x86-64 selects,+ ``ftrace_call_replace()`` emits a ``jmp`` instead of a ``call`` when+ bit 0 of the target is set, the mark of a direct trampoline entered+ by a jump. The same code patches the call of the ftrace callback in+ ``ftrace_caller``, ``ftrace_regs_caller`` and the ftrace trampolines,+ but a callback is a C function and can start at an odd address. It+ does with gcc 13 and ``CONFIG_CC_OPTIMIZE_FOR_SIZE=y``: gcc 13 has no+ ``-fmin-function-alignment``, and ``-falign-functions=16`` does not+ apply to functions optimized for size. The call then becomes a jump+ to the byte before the callback, which decodes as another instruction+ and swallows part of the callback's prologue; the callback runs+ without a return address and returns through the saved registers.+ The patch marks jmp mode by+ clearing bit 63 instead, which is set in every x86-64 kernel text+ address, so no callback can carry the mark, and a marked address+ that is used without being unmarked is not canonical and faults.++Why shirudo needs it+ The list callback ``ftrace_ops_list_func()`` is installed whenever two+ ``ftrace_ops`` are registered, and every+ ``update_ftrace_direct_mod()`` registers a stub ops for the sites it+ modifies. Detaching one of several BPF LSM programs from a busy hook+ is such an update. shirudo puts several programs on the same hooks,+ ``bpf2`` and ``seal`` share nine, and an upatch unload detaches+ programs from hooks that other tasks are running. The test kernel's+ slim configuration sets ``CONFIG_CC_OPTIMIZE_FOR_SIZE=y``.++Without it+ On an affected x86-64 build, a task that runs the hook during the+ trampoline update can take a kernel page fault on an instruction+ fetch, and the kernel oopses. Builds whose callbacks start at even+ addresses, and other architectures, are not affected.++TPM command LSM hook+--------------------++Subject+ tpm: Let LSMs inspect userspace commands++Files+ ``drivers/char/tpm/tpm-dev-common.c``,+ ``include/linux/lsm_hook_defs.h``, ``include/linux/security.h``,+ ``security/security.c``.++What it changes+ ``tpm_common_write()``, the write handler of both ``/dev/tpm0`` and+ ``/dev/tpmrm0``, calls a new hook,+ ``security_tpm_command(file, command, command_len)``, after it has+ copied the command from userspace and validated the header, and+ before it sends or queues the command. ``command_len`` is the length+ the header declares, so trailing bytes of the write are not part of+ the decision; the command stays in the device buffer until the hook+ returns. The patch also refuses a header whose declared length is+ smaller than the header itself.++Why shirudo needs it+ The key that authorizes extensions of shirudo's NV register lives in+ the TPM and is recreatable by any process that knows its public input,+ which the identity map holds. A guard on the key cannot work, so+ ``lsm/tpm_command`` guards the command: it refuses+ ``TPM2_NV_Extend`` of the frozen index to tasks without runtime+ authority. A check when the device is opened would miss descriptors+ opened earlier or inherited from another process; the hook sees every+ command. :doc:`measurement-register` explains the writer.++Without it+ The kernel's BTF has no ``bpf_lsm_tpm_command``, so the ``bpf2``+ object fails to load and ``init`` fails at "loading enforcement". The+ boot is not stopped, and the target runs without enforcement, as+ :doc:`boot-flow` describes.++Related+-------++- :doc:`kernel-interfaces` for the other kernel requirements.+- :doc:`/contribute/testing` for building and booting the test kernel.diff --git a/Documentation/internals/measurement-register.rst b/Documentation/internals/measurement-register.rstnew file mode 100644index 00000000..76f8a265--- /dev/null+++ b/Documentation/internals/measurement-register.rst@@ -0,0 +1,442 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: Kernel developers, security reviewers++Measurement register and attestation+====================================++shirudo records every change to a target's BPF state in a TPM register+that root on the target cannot rewrite or append to, and the TPM signs+that register on request. This page explains the register, its write+policy and binding, the events and the eventlog, the evidence, what the+operator's verifier computes, the separate config PCR, and the limits.+``util/chain.c``, ``util/tpm.c``, ``util/tpm_wire.c``,+``util/eventlog.c`` and ``util/attest.c`` are the reference.++Problem+-------++The operator needs to know which upatches a target runs. The target's+own report is worth nothing against root, which can make ``shirudo+status`` print anything. A file log is root's to edit. What is needed is+a record that only grows, that resets only when the machine starts over,+that only shirudo's own successful operations can extend, and that a key+root cannot use signs.++Why the obvious approaches fail+-------------------------------++A PCR only grows and resets with the TPM, but the PCRs are shared with+firmware, the boot loader, systemd and IMA, and a stock system has no+free static one; PCR 23 is resettable by software. An NV index of type+extend behaves like a PCR of one's own, which is what systemd's NvPCRs+use. Their write policy lets any process append, though. For shirudo+that is not enough: a public append lets root measure a load that never+happened, and evidence would then vouch for a state the kernel is not in.++We use an NV extend index like systemd does, and add an authorized+writer: an extension needs a signature from a TPM-held key, and the+kernel refuses the extension command itself to every task without+runtime authority.++Register+--------++The register is NV index ``0x01818E00`` (``SHIRUDO_NV_INDEX``, which a+build may change), holding one SHA-256 digest. Its attributes are+``0x0E060048``:++- ``TPM2_NT_EXTEND``: a write of ``d`` sets the index to+ ``SHA256(old || d)``, as a PCR extend does.+- ``TPMA_NV_CLEAR_STCLEAR``: contents and ``TPMA_NV_WRITTEN`` clear at+ every TPM reset and restart, so the register starts from 32 zero bytes+ and holds the history of one TPM boot.+- ``TPMA_NV_POLICYWRITE``: the only way to write is a policy session+ that satisfies the write policy.+- ``TPMA_NV_OWNERREAD`` and ``TPMA_NV_AUTHREAD``: anyone can read and+ certify it with an empty password.+- ``TPMA_NV_NO_DA`` and ``TPMA_NV_ORDERLY``: failed authorizations do+ not count toward dictionary-attack lockout, and the TPM writes the+ index back to NV memory only at an orderly shutdown.++The index's TPM name is ``000b`` followed by the SHA-256 of its public+area: handle, name algorithm, attributes, policy digest and size.+``TPMA_NV_WRITTEN`` is one of the attributes, so the index has one name+before its first write and another after it. The written name is the one+the record, the anchor and every later comparison use.++Write policy+~~~~~~~~~~~~++The write policy is ``PolicyOR(written, init)``, followed by+``PolicySigned`` and ``PolicyCommandCode(TPM2_CC_NV_Extend)``:++``written``+ ``PolicyNvWritten(YES)``. Every extension after the first takes this+ branch. It cannot initialize an index that was recreated and is+ unwritten.++``init``+ ``PolicyNvWritten(NO)`` followed by ``PolicyPCR`` over PCRs 9 and 11,+ with the SHA-256 of the values both held when ``init`` bound the+ register. It admits the first write of a TPM boot, and only while+ both PCRs still hold those values.++``PolicySigned`` names the boot's NV writer key and the policy reference+``shirudo-nv-writer-v1``. The writer signs the SHA-256 of the session's+TPM nonce, a zero expiration, the command hash and the reference. The+command hash covers ``TPM2_CC_NV_Extend``, the index name twice (as auth+handle and as index) and the event. The TPM checks that exact command+hash when it executes the extension, so a signature authorizes one event+on one index in one session.++NV writer+~~~~~~~~~++The writer is an RSA-3072 RSASSA SHA-256 primary key in the owner+hierarchy with object attributes ``0x00040072``: ``fixedTPM``,+``fixedParent``, ``sensitiveDataOrigin``, ``userWithAuth`` and ``sign``.+``init`` creates it from 32 random bytes in the ``unique`` field, and+freezes those bytes and the resulting 384-byte modulus in the identity+map. Each later command recreates the primary from the frozen input,+compares the public key with the frozen one, has the TPM sign the+authorization and flushes the key. The private key never leaves the TPM,+and nothing is kept in a persistent handle or a file.++The input is not secret. Any process can recreate the same key and have+the TPM sign. What protects the register is ``lsm/tpm_command``: the+kernel shows every command written to ``/dev/tpm0`` or ``/dev/tpmrm0`` to+that hook, and it refuses ``TPM2_NV_Extend`` of the frozen index to tasks+without runtime authority, including through descriptors opened before+``init`` or inherited from another process. The hook needs the carried+kernel patch described in :doc:`kernel-patches`.++A new host boot chooses new input and so a new key. A TPM reset within+the same host boot keeps the input, and so the key. A TPM clear changes+the owner seed, and the frozen key can no longer be recreated.++Binding at boot+---------------++``init`` binds the register once per TPM boot, normally from the initrd,+after it has restored the archived upatches (:doc:`boot-flow`):++#. Recreate the attestation key and compare its name with the one frozen+ in the identity map, so the register is bound in the TPM ``init``+ recorded.+#. Read the TPM's reset count. When this boot's eventlog already holds an+ ``init`` record for that count, the register was bound: if the index+ is written under the recorded name, ``init`` reuses it and adds no+ event; if it is gone, unwritten or renamed, ``init`` refuses with+ ``tampered`` and binds nothing before the next TPM reset.+#. Otherwise read PCR 9 and PCR 11 (``pcr_before``, ``phase_before``),+ compute both policy branches, the policy digest and the two names in+ software, and define the index with the owner authorization,+ replacing an index that is already written or has another name. The+ name the TPM reports must equal the computed one.+#. Extend the index with the ``init`` event through the ``init`` branch.+ The session's policy digest is read back and compared with the+ software policy before the extension.+#. Extend PCR 9 with SHA-256 of the anchor string+ ``nvpcr-init:shirudo:0x1818e00:<written name>``, systemd's+ ``nvpcr-init`` format. From then on PCR 9 no longer holds+ ``pcr_before``, so the ``init`` branch cannot be satisfied again before+ the next TPM reset. Once systemd measures ``leave-initrd``, PCR 11 no+ longer holds ``phase_before`` either.+#. Write the ``init`` record: both PCR values, whether the initrd was+ running (``bound_in``), the written name, the anchor and its digest,+ the register value, the reset count and the writer's public modulus.++Consequences follow. An index undefined and recreated under the same+policy cannot be written, because PCRs 9 and 11 have moved. One recreated+under another policy has a name the record does not know. And the+register value is a function of the trust set, the restored set, the+tree root and the events since boot, which the operator can compute.++Extending later+~~~~~~~~~~~~~~~++Every later extension recreates the attestation key and compares its+name, requires this boot's ``init`` record, recomputes the policy from+the recorded PCR values and writer key, and requires the live index to be+written, to carry the recorded name and policy, and the TPM's reset count+to equal the recorded one. A missing register is ``tpm_error``; a+register that is not the recorded one is ``tampered``.++Events+------++Every extension is a 32-byte SHA-256 digest that starts with a+NUL-terminated tag, so no event of one kind can be read as another. In+the formulas, ``\0`` is the NUL that ends the tag.++.. list-table::+ :header-rows: 1+ :widths: 18 52 30++ * - Event+ - Digest+ - Made by+ * - ``init``+ - ``SHA256("shirudo-init\0" || cert_sha256 || set_digest ||+ tree_root)``+ - ``init``, once per TPM boot+ * - ``upatch_load``+ - ``SHA256("shirudo-upatch\0" || payload_sha256 || name)``+ - ``upatch load``, ``bpm`` installs+ * - ``upatch_unload``+ - ``SHA256("shirudo-unload\0" || payload_sha256 || name)``+ - ``upatch unload``, ``bpm`` removals, revocation purges+ * - ``tree_op``+ - ``SHA256("shirudo-tree\0" || seq || operation_digest)``, ``seq``+ as eight big-endian bytes+ - ``bpm tree sync``+ * - ``key_revoke``+ - ``SHA256("shirudo-key-revoke\0" || cert_sha256)``+ - live config activation that revokes an enrolled key++``cert_sha256`` in the ``init`` event covers the BPF trust set in effect:+the SHA-256 of the certificate's DER when the set has one member, else+the SHA-256 over the members' DER digests in sorted order.+``set_digest`` is the SHA-256 of one line ``<payload_sha256 hex>+<name>\n`` per restored upatch, sorted by name. ``tree_root`` is the+upatch tree's projection root at boot, or 32 zero bytes without a tree.++Boot restore is one event however many upatches it restores, and the+root file system's ``init`` adds none. Every operation after that is its+own event. A live revocation extends ``key_revoke`` after it unlinks the+key and before it purges what the key signed; each loaded upatch it+purges follows as an ``upatch_unload`` with the reason ``key_revoke``.+Revocations a config carries at boot are not individual events; the+``init`` event's trust set reflects them.++Eventlog+--------++``/var/lib/shirudo/eventlog`` holds one JSON line per extension: the+event digest and type, the boot ID, and the fields the digest was+computed from. Each line is appended with ``fsync``, and a partial append+is truncated away. The file is sealed like the rest of the state tree.+:doc:`/reference/formats/eventlog` gives the format.++The ``init`` run in the initrd writes its record to+``/run/shirudo/eventlog.pending``, which crosses the switch to the root+file system with ``/run``. Every reader treats the pending record+as part of this boot's log. The root file system's ``init`` appends it to+the eventlog and removes the pending file, and so does the first append+that comes earlier. A record already in the eventlog is not appended+twice.++"This boot" is every line with the running boot ID from the last ``init``+record on. Replaying those lines from 32 zero bytes must reproduce the+live register. Readers load the whole log and the pending record into+memory and refuse a total above 8 MiB. ``eventlog.max_bytes`` in the+config image, unlimited by default, makes ``init``, ``upatch load`` and+``upatch unload`` refuse with ``eventlog_full`` before they load anything+or touch the TPM; revocations and tree operations do not check it.++Lock between extend and append+------------------------------++The register and the eventlog advance together only while one process at+a time extends and appends. Two measuring commands that each held a lock+of their own could interleave extend, extend, append, append, and leave a+log that replays the events in the other order. Every measuring command,+an upatch load or unload, a live revocation and a tree operation,+therefore holds ``/var/lib/shirudo/eventlog.lock`` from its extension to+its append.++The order of extension and state change is chosen per operation. A load+loads, archives and then extends; a failed archive copy or a refused+extension undoes the load, so no upatch runs unmeasured. An unload+extends first and detaches after, so a stopped process leaves a register+that records more than happened, never less. An append that fails after+a successful extension is reported as a desync for the operator to+reconcile.++``init`` binds the register and writes its record without taking this+lock.++Evidence+--------++``shirudo attest`` asks the TPM for two signed statements and collects+what a verifier needs to check them. It needs no enrollment state on the+target and leaves none.++The attestation key is a primary under the endorsement hierarchy with a+fixed template: ECC NIST P-256, ECDSA with SHA-256, ``restricted`` and+``sign``, no authorization value and no policy. A primary with a fixed+template is derived from the endorsement seed, so the same TPM always+yields the same key and the same name. ``restricted`` means the key signs+only structures the TPM itself produced.++The evidence document carries:++- a ``TPM2_Quote`` over the SHA-256 bank of the selected PCRs, by default+ 0 to 7, 9 and 11 to 15, plus the config PCR, with the verifier's nonce;+- a ``TPM2_NV_Certify`` of the register's 32 bytes with the same nonce,+ which names the index and so binds the value to its public area;+- the attestation key's public area and name, and the endorsement key's+ public area and name;+- this boot's eventlog records;+- the endorsement certificate from NV ``0x01C0000A`` (ECC) or+ ``0x01C00002`` (RSA) when the TPM holds one;+- the credential the TPM recovered, when the request carried a+ challenge;+- the firmware and systemd measurement logs, so that a verifier can+ replay the PCRs it pins;+- the config history (see below).++Credential activation+~~~~~~~~~~~~~~~~~~~~~++A signature by a key name proves nothing until the name is tied to a+TPM. ``shirudo attest challenge`` on the operator takes the endorsement+key from an evidence document, checks that it is the TCG default template+under the endorsement policy and, when vouched for by ``--ek-ca``,+``--ek-name`` or explicitly by ``--trust-presented-ek``, computes in+software what ``TPM2_MakeCredential`` computes: a random 32-byte+credential protected for the endorsement key and bound to the+attestation key's name. ``shirudo attest --challenge`` on the target has+the TPM run ``TPM2_ActivateCredential`` under a ``PolicySecret`` session+on the endorsement hierarchy; the TPM releases the credential only when+the attestation key it loaded has the name the challenge was made for.+``shirudo attest verify --expect-credential`` checks the value. Together+with the signature checks, this shows that the key that signed is a+restricted key in the TPM that holds the endorsement key.++What verify and predict compute+-------------------------------++``shirudo attest verify`` and ``shirudo attest predict`` run on the+operator and touch no TPM. ``verify`` prints one line per check and a+verdict. It checks, in this order:++#. the nonce;+#. the attestation key: a restricted signing key with the required+ attributes, its name matching its public area, and with ``--ak-name``+ the pinned name; the endorsement key's template and name, and with+ ``--ek-name`` and ``--expect-credential`` the pinned key and the+ credential;+#. the quote: signature, signer, nonce, that it covers exactly the listed+ PCRs, and that the listed values hash to the quoted digest;+#. the register certification: signature, signer, nonce, the certified+ name and value equal to the listed ones, and the same TPM reset count+ and firmware version as the quote;+#. with ``--expect-config-root`` and ``--expect-config-pcr``, the config+ history;+#. the binding: this boot has an ``init`` record, the document names the+ verifier's own NV handle and PCRs 9 and 11, and the name a register+ bound to the recorded PCR values and writer key must have, computed in+ software, equals both the certified and the recorded name; each+ ``--expect-bind-pcr`` value equals the recorded one;+ ``--require-initrd`` requires ``bound_in`` to be ``initrd``;+#. the reset: one ``init`` record for the certified reset count;+#. the replay: this boot's records fold from zero to the certified value,+ and every event after ``init`` carries the digest its own fields+ produce;+#. the anchor: the recorded anchor digest is that of the anchor string+ for the recorded name, and the quoted PCR 9 equals ``pcr_before``+ extended by it; further PCR 9 measurements are a note unless+ ``--strict-anchor`` makes them a failure;+#. the expected state: with ``--cert``, ``--upatch``, ``--expect`` and+ ``--tree-root``, the ``init`` event equals the predicted one; the+ register equals ``--expect-chain``, or the predicted value at boot, or,+ with events after boot, ``--allow-runtime-events`` decides; each+ ``--expect-pcr`` matches the quote.++``predict`` prints ``set_digest``, ``init_event`` and+``register_at_boot`` from the certificates, the artifacts and the tree+root, using the target's own functions, and ``register_after_events``+for ``--event`` arguments. With ``--bind-pcr=9=<hex>``,+``--bind-pcr=11=<hex>`` and ``--writer-public=<hex>`` it also prints the+register's name, the anchor string and ``pcr9_after_anchor``.+:doc:`/reference/cli/attest-verify` and+:doc:`/reference/cli/attest-predict` list the options.++Config PCR+----------++Config activations are measured into a separate PCR, not into the+register. The runtime image's bootstrap settings choose it with+``config.pcr``: any static SHA-256 PCR from 0 to 15 except 9 and 11. A+config image cannot change the choice.++Each event is ``SHA256("shirudo-config-root-v1\0" || kind ||+root_hash)``, with the kind as a big-endian 32-bit number, 1 for the boot+event and 2 for a live update, and the 32-byte binary root hash. The+first event of a TPM boot records the PCR's value before it as+``initial_pcr``; the journal under ``/var/lib/shirudo/config-update``+records the sequence, the TPM's reset and restart counts and the root of+each event. :doc:`config-images` explains activation.++Evidence includes the config PCR in the quote and the config history.+``verify`` with ``--expect-config-root`` and ``--expect-config-pcr``+derives each event digest, requires one boot event followed by updates in+sequence for the quoted TPM boot, a replay from ``initial_pcr`` that+reaches the quoted PCR value, and the expected root as the selection.++Limits+------++These are properties of the design as implemented.+:doc:`/security/threat-model` gives their consequences.++The TPM transport is not authenticated.+ shirudo opens the TPM by device path, ``/dev/tpmrm0`` unless the+ runtime settings name another device, and uses unsalted, unbound+ policy sessions. The attestation key name check rejects a TPM that+ reports a different name, but the name is public, so a substitute+ transport could replay it. Only evidence signed by a pinned+ attestation key settles which TPM answered.++Rebinding depends on the record.+ ``init`` decides that the register is already bound this boot from+ the eventlog, which it reads through the caller's view of the file+ system. Without a record for the current reset count, it binds the+ register again, with a warning when the index was already written,+ and PCR 9 then carries both anchors. A verifier that pins both+ binding PCRs to their initrd values with ``--expect-bind-pcr``+ rejects such evidence.++Owner authorization can remove the register.+ A process with the owner authorization, empty on many TPMs, can+ undefine the index. Extensions then fail and ``init`` refuses to bind+ again before the next TPM reset. This denies service; it does not+ erase what evidence already showed.++The verifier checks what it is asked to check.+ Without ``--ak-name`` the signer is only noted. Without ``--cert`` or+ ``--expect-chain`` no state is compared, and a verdict of ``ok``+ shows internal consistency only. ``--require-initrd`` reads the+ record's own ``bound_in``; ``--expect-bind-pcr=11`` is what proves an+ initrd binding. ``--allow-runtime-events`` accepts any well-formed+ events after boot.++The config PCR has no writer restriction.+ Any process that can send ``TPM2_PCR_Extend`` can extend the config+ PCR, and then every target command except ``shirudo status`` and+ ``shirudo image status`` refuses until a reboot because the PCR no+ longer replays.++PCR 11 needs a measured UKI boot.+ systemd measures the initrd phases only on a measured UKI boot.+ Without them PCR 11 does not move, ``init`` warns, and a verifier has+ only the anchor in PCR 9 to tell an initrd binding from a later one.++The evidence is classical.+ TPMs sign with ECDSA P-256 and the writer is RSA-3072, while the+ artifacts the evidence describes are signed with ML-DSA-87.++Related+-------++- :doc:`/concepts/background/tpm` for TPM PCRs, NV indices and+ sessions.+- :doc:`/concepts/measurement-register` for the concept.+- :doc:`/operate/attest` for attesting a target.+- :doc:`/reference/formats/eventlog` for the eventlog format.diff --git a/Documentation/internals/seal.rst b/Documentation/internals/seal.rstnew file mode 100644index 00000000..6b2a3342--- /dev/null+++ b/Documentation/internals/seal.rst@@ -0,0 +1,262 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: Kernel developers, security reviewers++Seal labels and task marks+==========================++shirudo keeps state that has to survive a reboot on a writable file+system, under ``/var/lib/shirudo``. This page explains how the ``seal``+BPF object keeps root from changing that state: labels that mark the+inodes to protect, task marks that say which processes may change them,+and the places where the mechanism stops.++Problem+-------++The archived upatches that boot restore loads, the eventlog, the package+and tree state, the image cache and the config activation journal cannot+live on a read-only image, because shirudo changes them. Several of them+are not signed: the activation journal, the tree cursor and the package+state decide what shirudo restores, skips or reports. Root can write any+file, so without more, root could edit them.++Why the obvious approaches fail+-------------------------------++File ownership and modes do not stop root. A check on the caller's user+ID or capabilities does not either, because the attacker is root.++A check on the caller's executable fails too. A path names whatever root+puts there. An inode identity can be copied around with an overlay,+replaced with ``PR_SET_MM_EXE_FILE``, or reached by a process that root+starts from that executable under a tracer or with a preloaded library.+A label on the caller's executable is a value root can copy onto any+binary.++We need two separate facts: which inodes are shirudo's, and which+processes run shirudo's code. Labels answer the first and task marks the+second, and a label never authorizes a caller.++Task marks+----------++A task mark is an entry in ``shirudo_tasks``, a task storage map that+both enforcement objects share. A task with a mark has runtime+authority, and every guard that lets shirudo do what it refuses to+others tests for it.++A mark is granted only by a successful exec from the authenticated+runtime image. ``lsm.s/bprm_check_security`` stages a candidate on each+binary handler pass and keeps the last one. The candidate is trusted+when all of these hold:++- the file is a direct inode, not an overlay copy: the real data inode+ the kernel reports for the file is the file's own inode;+- the inode is on a read-only superblock whose block device is recorded+ as the runtime device, with the same device number and disk sequence;+- the task is not traced;+- the task has no seccomp filter.++A traced exec of a runtime file is refused (``ExecTraced``), and so is+one with a seccomp filter, because a tracer or a filter installed before+the exec would control the trusted process. ``lsm.s/bprm_committed_creds``+commits the candidate when the exec succeeds. A failed exec never reaches+that hook and leaves the existing mark alone. A successful exec of a file+that is not on the runtime image commits an untrusted candidate and so+clears the mark. ``lsm/task_alloc`` copies a parent's mark to every+child.++The device record that the exec check consults comes from+``lsm.s/bdev_setintegrity``: it records a dm-verity device as runtime+when its root hash equals the runtime root the UKI authenticated, which+``init`` froze in the identity map. :doc:`config-images` explains the+images.++Every executable on the runtime image is equally eligible. The image+holds the ``shirudo`` binary, its loader and libraries when it is linked+dynamically, and any ``--extra-binary`` the operator added; each extra+binary is a further holder of runtime authority.++Bootstrap seed+~~~~~~~~~~~~~~++``init`` in the initrd runs before any runtime image is recorded, so it+cannot have earned a mark by exec. Before it freezes ``shirudo_tasks``,+it writes a bootstrap mark for its own process through a pidfd. The+bootstrap mark has the same authority as an exec mark. It is also exempt+from the executable-memory checks of ``lsm/mmap_file`` and+``lsm/file_mprotect``, because the initrd binary is not on the runtime+image. The seed lives as long as that process and the children it forks;+the root file system's ``init`` runs from the runtime image and earns its+mark by exec.++Protecting marked tasks+~~~~~~~~~~~~~~~~~~~~~~~++A mark is only worth as much as the integrity of the process that holds+it. ``lsm/ptrace_access_check`` refuses every ptrace access to a marked+task (``SealPtrace``), which also covers ``/proc/<pid>/mem``,+``pidfd_getfd()`` and ``process_vm_readv()``. ``lsm/perf_event_alloc``+refuses a perf event bound to a marked task (``SealPerf``).+``lsm/mmap_file`` and ``lsm/file_mprotect`` refuse a marked task+executable memory that is writable or that does not come from the+runtime image. ``bpf2`` makes every exec of a runtime file a secure-exec,+so the dynamic loader ignores ``LD_PRELOAD`` and its kin, and refuses+``PR_SET_MM_EXE_FILE`` and ``PR_SET_MM_MAP`` to tasks without+authority.++Labels+------++A label is the extended attribute ``security.bpf.shirudo`` on an inode+under ``/var/lib/shirudo``. Its value is a fixed 64-character string, the+SHA-256 of the attribute name, the same on every target. The value is+public and carries no authority. The seal treats an inode that has the+attribute, with any value, as protected.++The first ``init`` labels the tree. When ``/var/lib/shirudo`` itself has+no label and enforcement is not yet attached, ``init`` labels every+regular file and directory on that file system under it. After that,+shirudo labels each inode as it creates it, and ``init`` never labels an+entry again: an unlabelled entry, or an entry of a kind shirudo never+makes, is someone else's and is logged and ignored. With enforcement+attached, ``init`` refuses a state root without a label, because that is+a tree bound over the path rather than the one it sealed.++``init`` also labels ``/run/shirudo``, so that the init record it leaves+there for the root file system is sealed from its creation. The runtime+and config images carry no labels; dm-verity protects them.++What the seal checks+--------------------++For a labelled inode, these operations need runtime authority:++- a write open (``SealWrite``);+- unlink (``SealUnlink``);+- rename of it, or rename over it (``SealRename``);+- truncate, chmod, chown and timestamp changes through+ ``inode_setattr`` (``SealSetattr``);+- setting or removing any extended attribute (``SealXattr``).++Setting the attribute ``security.bpf.shirudo`` itself needs runtime+authority on every inode, labelled or not (``SealLabel``), so root cannot+label an inode of its own as shirudo's.++A directory with a cached mark takes new entries only from a task with+runtime authority: ``inode_create``, ``inode_mkdir``, ``inode_symlink``,+``inode_mknod``, ``inode_link`` and a rename into it (``SealEntry``). A+label stops writes to an inode, but a rename or a hard link brings an+inode in with its contents, and a symbolic link sends whoever follows it+elsewhere. ``inode_copy_up`` refuses the overlay copy-up of a marked inode+(``SealCopyUp``): a write through an overlay mounted over sealed state+would otherwise land in the upper directory and leave the sealed inode as+it was.++Reading the label+~~~~~~~~~~~~~~~~~++The seal reads the label with the ``bpf_get_file_xattr()`` and+``bpf_get_dentry_xattr()`` kfuncs. Both first check that the calling+task may read the inode. If the seal refused every operation whose label+read failed, it would refuse every write-only open and every unlink of a+file the caller cannot read, on every file system. So these results count+as unlabelled and the operation goes ahead: no label (``ENODATA``), no+security extended attributes on the file system (``EOPNOTSUPP``), and a+label the caller may not read (``EACCES``, ``EPERM``). A label of any+length, any other error, and a failure to allocate the scratch buffer+the kfunc writes into require runtime authority.++Labelling at creation+---------------------++A file shirudo creates must carry its label from the moment it exists;+a window in which it has none is a window in which the seal does not+protect it. ``lsm/inode_init_security`` runs inside the file system's+creation transaction and gives the new inode its parent's label with+``bpf_inode_init_xattr()``. If it cannot add the label, it refuses the+creation: no inode is better than one of shirudo's without its label.++That hook cannot sleep, so it cannot read the parent's extended+attribute. It uses a cached mark instead: ``seal_dir_marks``, inode+storage that records a directory's label. A directory gets its mark when+any task opens it and its label is read, when an extended attribute on it+changes, and when it is created under a marked parent. A directory open+whose label read finds nothing removes the mark.++shirudo's writers keep the mark in place. They open the parent directory+and create files relative to that descriptor, which holds the inode in+memory for the duration, and they set the label from userspace as well+when the kernel could not. After the seal attaches, ``init`` walks the+state tree once more; the walk opens every directory and fills the marks.++shirudo's readers do not trust an entry because it is there. They open+each path component without following symbolic links and require every+entry under a labelled directory to carry its parent's label; anything+else is reported as a foreign entry and refused. A path a caller names+for shirudo to write, such as ``--report`` or ``--out``, must be an+unlabelled regular file outside any labelled directory, so a task with+runtime authority cannot be pointed at sealed state.++Limits+------++These are properties of the mechanism as it is. The+:doc:`/security/threat-model` states their consequences.++Directory eviction+ A mark is a cache. When the kernel evicts a directory's inode,+ under memory pressure or through ``vm.drop_caches``, its mark goes+ with it until the next open of that directory. In that window,+ creation, links and renames into the directory are not checked, and+ ``inode_init_security`` adds no label.++Hard links to labelled inodes+ ``inode_link`` checks the destination directory's mark, not the+ source inode. Root can hard-link a labelled file into an unsealed+ directory on the same file system. shirudo replaces state by writing+ a new file and renaming it over the old one, so the old inode stays+ reachable through that link. While a directory's mark is absent, such+ a link can be made inside a sealed directory, where it carries a+ valid label.++Label reads under another LSM+ The kfuncs' read permission check runs every LSM's+ ``inode_permission`` hook for the calling task. A policy of another+ LSM that lets a task write or unlink a file but not read it makes a+ labelled inode look unlabelled to the seal, and the same failure on+ a directory open removes the directory's mark.++Operations without a check+ The seal does not attach ``inode_rmdir``, ``inode_file_setattr`` or+ the ACL hooks ``inode_set_acl`` and ``inode_remove_acl``. Root can+ remove an empty labelled directory, set the immutable or append-only+ flag on sealed files with ``chattr``, and change their POSIX ACLs.++Bind mounts+ No mount guard covers the state file system, and shirudo's opens+ follow mount points. A bind mount over a sealed path makes shirudo+ read and write what lies under the mount.++Existing descriptors+ The seal checks operations when they start. A descriptor opened for+ writing, or a writable mapping, that exists before a file is+ labelled keeps working; the seal revokes nothing.++Below the file system+ The hooks see VFS operations. Writes to the block device under the+ file system, or to the disk while the target is down, do not pass+ through them. Across a reboot, signatures and the measurement+ register protect what matters, not the seal.++Related+-------++- :doc:`/concepts/background/xattrs` for extended attributes and the+ ``security.bpf.`` namespace.+- :doc:`enforcement` for every hook and its counter.+- :doc:`/security/tamper-counters` for the ``Seal*`` counters.diff --git a/Documentation/internals/signed-loader.rst b/Documentation/internals/signed-loader.rstnew file mode 100644index 00000000..2b9e1de8--- /dev/null+++ b/Documentation/internals/signed-loader.rst@@ -0,0 +1,256 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: Kernel developers, security reviewers++Signed loader path+==================++Root on a Linux host can normally load any BPF program. This page+explains how shirudo takes that away while keeping BPF usable for+upatches: what the operator signs, which ``bpf()`` calls a load makes,+which kernel checks decide each of them, how an unload works, and where+the mechanism stops.++Problem+-------++Every upatch is BPF, so shirudo cannot switch BPF off. It needs a kernel+that accepts BPF the operator signed and refuses BPF from anyone else,+root with every capability included. Root can issue any system call, so+the decision has to sit where root cannot step around it.++Why a check in userspace fails+------------------------------++The obvious design puts a privileged service in front of ``bpf()``: the+service checks a signature and then makes the system call. The check and+the load are then two steps in two places. Root does not have to ask the+service; it calls ``bpf()`` itself, and the kernel cannot tell the vetted+call from the other one. A userspace check also checks a file, while the+kernel loads bytes that root can change between the two.++We need the kernel to verify the signature on the same call that loads+the code, over the bytes it loads.++What the operator signs+-----------------------++The operator does not ship the upatch program itself. ``shirudo build``+compiles the source, and libbpf's gen_loader turns the object into a+loader: a ``BPF_PROG_TYPE_SYSCALL`` program whose instructions make the+``bpf()`` calls that create the upatch's maps and load its programs. The+loader's data blob carries everything those calls need, the payload+programs' instructions included. The builder appends signed sections to+the data (the upatch name, the attach metadata, the unload target and the+decoders) and signs ``loader_insns || data`` with ML-DSA-87 as a detached+CMS signature. The ``.upatch`` container carries the loader instructions,+the data, the signature, and in its header the name and+``payload_sha256``, which is SHA-256 of ``loader_insns || data``.+:doc:`/reference/formats/upatch-format` has the byte layout.++One signature therefore covers every instruction that ends up attached,+because the payload instructions are part of the signed data.++Metadata map+------------++The kernel cannot verify a signature over data it has not seen, so the+data travels to the kernel before the loader does, in an array map that+only this loader can use. The target creates the map, ``__loader.map``,+with one element whose value is the data blob. It sets+``excl_prog_hash`` to SHA-256 of the loader instructions, which makes the+map exclusive: the verifier refuses to bind it to any program whose+digest differs. It writes the data and freezes the map, so nothing can+change the value after the check.++``BPF_PROG_LOAD`` passes the map in ``fd_array`` with ``fd_array_cnt``+set to 1. With ``fd_array_cnt`` set, the verifier binds the map at the+start of the load and verifies the signature over the instructions+followed by the frozen value of each such map. The kernel refuses a signed load+whose bound map is not an array, not frozen, has active writers or is not+exclusive.++Calls a load makes+------------------++``shirudo upatch load`` runs these steps. The first column says who makes+the call: userspace, which ``lsm/bpf`` sees with ``kernel`` false, or the+loader inside the kernel, which ``lsm/bpf`` sees with ``kernel`` true.++.. list-table::+ :header-rows: 1+ :widths: 12 30 58++ * - Caller+ - Call+ - What decides it+ * - userspace+ - pre-flight+ - The kernel ABI check passes, the ``.bpf`` keyring serial equals+ the frozen identity record, and ``lsm_link`` is pinned. With+ ``--expect-chain``, the register equals the given value.+ * - userspace+ - read and parse the file+ - The file is read once into ``/var/lib/shirudo/incoming``. The+ signed name must equal the header name, ``payload_sha256`` must+ equal SHA-256 of ``loader_insns || data``, and the signed attach+ metadata must parse. Each ``uprobe.multi`` target is opened and+ its GNU build ID compared before any BPF loads.+ * - userspace+ - ``BPF_MAP_CREATE`` of ``__loader.map``+ - ``lsm/bpf`` allows it to a task with runtime authority, else+ ``EACCES`` (``MapCreate``).+ * - userspace+ - ``BPF_MAP_UPDATE_ELEM``, ``BPF_MAP_FREEZE``+ - ``lsm/bpf``, runtime authority (``MapWrite``).+ * - userspace+ - ``BPF_PROG_LOAD`` of the loader+ - ``lsm/bpf`` at system call entry: the type must be+ ``BPF_PROG_TYPE_SYSCALL`` and ``signature_size`` non-zero. Inside+ ``bpf_check()``, the kernel resolves ``fd_array``, verifies the+ signature against the keyring ``keyring_id`` names, then calls+ ``lsm/bpf_prog_load``, then runs the verifier's analysis.+ * - userspace+ - ``BPF_PROG_TEST_RUN`` of the loader+ - ``lsm/bpf``, runtime authority (``ProgRun``). The loader then+ runs in the kernel.+ * - loader+ - ``BPF_MAP_CREATE``, ``BPF_MAP_UPDATE_ELEM``, ``BPF_MAP_FREEZE``,+ ``BPF_PROG_LOAD`` through ``bpf_sys_bpf()``+ - ``lsm/bpf`` and ``lsm/bpf_prog_load`` see ``kernel`` true and+ allow. The verifier checks each payload program as usual.+ * - userspace+ - ``BPF_LINK_CREATE`` or ``BPF_RAW_TRACEPOINT_OPEN``, per program+ - ``lsm/bpf``, runtime authority (``ProgAttach``). shirudo then+ compares the link the kernel reports with the signed metadata and+ refuses ``attach_scope_mismatch`` when they differ.+ * - userspace+ - ``BPF_OBJ_PIN`` of each link and map+ - ``lsm/bpf``, runtime authority (``ObjPin``), and the bpffs inode+ guards.+ * - userspace+ - archive, extend, append+ - The artifact is copied to ``/var/lib/shirudo/upatches/``, the+ register is extended with the load event and the eventlog takes+ the record. A failed copy or a refused extension undoes the load.++``shirudo bpm`` installs, upgrades and tree operations skip the+pre-flight row (they pass ``--no-precheck``); the keyring comparison runs+again inside the load, so those paths keep it.++The loader returns the descriptors of what it created in its context+buffer, and the command attaches and pins them. Links are created in+userspace because gen_loader emits no link creation and+``bpf_sys_bpf()`` has no ``BPF_OBJ_PIN``. Each link is pinned at+``/run/shirudo/bpffs/upatches/<name>/link``, or ``link_<n>`` for several,+serializers under ``serializers/`` and maps under ``maps/`` beside it. A+dot in the name is written as ``~d`` there. The directory carries the+``security.bpf.shirudo.payload`` extended attribute with the payload+digest, which only a task with runtime authority can set.+:doc:`kernel-interfaces` lists the attributes each call sets.++Telling the loader apart from root+----------------------------------++A signature check alone is not enough. The loader calls back into+``bpf()`` to create maps and load programs, and those calls look like the+ones root would make. The ``lsm/bpf`` and ``lsm/bpf_prog_load`` hooks+receive a ``bool kernel`` argument. It is true when the call comes+through a kernel pointer, which is how ``bpf_sys_bpf()`` issues the+loader's calls, and false for a system call from userspace. Calls with+``kernel`` true are allowed: they come from a loader the kernel already+verified and that an authorized task is running. Userspace calls are+filtered.++Admission in lsm/bpf_prog_load+------------------------------++The kernel records the result of its signature check on the program:+``prog->aux->sig.verdict``, ``sig.keyring_type`` and+``sig.keyring_serial``. ``lsm/bpf_prog_load`` runs after that check and+reads them. A userspace load is admitted only when the verdict is+``BPF_SIG_VERIFIED`` and the keyring kind is ``BPF_SIG_KEYRING_BPF``. A+program the kernel did not verify, such as one whose load sets a+signature size but no signature, is refused ``LoadUnverified``. A program+verified against the built-in, secondary or platform keyring is refused+``LoadKeyringKind``; the kernel verifies such a signature, so the kind+check is what keeps those keyrings out.++The hook also compares a non-zero serial with the keyring serial ``init``+froze. For the ``.bpf`` keyring the kernel records serial 0, because it+resolves that keyring without taking a reference, so this comparison+never runs and ``LoadKeyring`` does not count. The kind check pins the+keyring: there is one ``.bpf`` keyring, and ``init`` sealed it around the+trusted set. A caller-supplied user keyring never reaches the hook: with+``bpf.keyring_unsealed=1`` on the command line, which shirudo requires,+the kernel refuses any ``keyring_id`` other than the system selectors and+``KEY_SPEC_BPF_KEYRING`` with ``EPERM``.++Root without the key fails earlier than this. Creating the metadata map+needs runtime authority, so a root process with a validly signed+``.upatch`` cannot even prepare the load, and running a loaded loader+needs runtime authority too.++Unload directives+-----------------++An unload directive is a ``.upatch`` whose header marks it as an unload.+Its signed sections name the upatch it removes and the payload digest+that upatch must have. ``shirudo upatch unload`` loads the directive's+loader through the same ``BPF_PROG_LOAD`` as a load, so the kernel+verifies its signature against ``.bpf`` exactly as it verifies a load.+The command never runs that loader.++The detach is userspace work. The command reads the payload digest from+the extended attribute on the pin directory and compares it in constant+time with the signed one; a mismatch, or an attribute it cannot read, is+``payload_mismatch``. It then extends the register with the unload event,+and only then removes the map pins, the link pins and the directory, and+the archived copy. A process stopped between the two leaves a register+that records an unload that did not finish, never a detach the register+does not know. A missing pin directory is ``already_unloaded`` and+extends nothing.++Removing the pins detaches because a pin is the only reference shirudo+keeps to a link, and the link detaches when its last reference goes.+``lsm/bpf`` refuses ``BPF_OBJ_GET`` and ``BPF_LINK_GET_FD_BY_ID`` to+tasks without runtime authority, and ``lsm/file_open`` refuses to open a+pin as a file, so root cannot take a second reference to a shirudo link+by pin or by id. ``BPF_LINK_DETACH`` is refused to every userspace+caller, shirudo included.++Limits+------++The unload directive authorizes the detach, but it does not perform it.+The detach runs in userspace because ``bpf_sys_bpf()`` offers no detach+or unpin command; ``bpf/unload.c`` is a placeholder for the in-kernel+version. An unload directive is bound to the upatch name and payload+digest, not to the key that signed the load.++The ``kernel`` argument is true for every call through a kernel pointer,+which includes BPF that kernel code loads with ``kern_sys_bpf()``, such+as a light skeleton in a module. shirudo admits those as it admits a+loader's calls. A signed loader can issue every command+``bpf_sys_bpf()`` allows, ``BPF_MAP_GET_FD_BY_ID`` and+``BPF_LINK_CREATE`` among them, and the guards do not limit what it does+with them: an upatch does what its signer wrote.++The two enforcement objects are loaded without a signature from the+authenticated initrd; their trust comes from the boot chain. Pins keep+upatches attached, so the pins depend on the private bpffs staying+mounted, which the mount guards in :doc:`enforcement` protect.++:doc:`/security/threat-model` states the residual risks.++Related+-------++- :doc:`/concepts/background/bpf-signing` for the kernel's signed BPF+ support.+- :doc:`enforcement` for every hook and counter.+- :doc:`kernel-interfaces` for the exact ``bpf()`` attributes.+- :doc:`/reference/formats/upatch-format` for the container.diff --git a/Documentation/key-lifecycle.rst b/Documentation/key-lifecycle.rstdeleted file mode 100644index fc29bb81..00000000--- a/Documentation/key-lifecycle.rst+++ /dev/null@@ -1,165 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--Key lifecycle-=============--shirudo's trust rests on the operator's ML-DSA-87 signing keys and-their self-signed certificates. This guide covers them from creation-to retirement: what they sign, where the certificates go, how targets-come to trust one and then another, how to rotate a key without a gap-in protection, and what to do when one is compromised. The-`threat-model <threat-model.rst>`__ says why the mechanisms are shaped-the way they are; this document says what to do.--1) The keys in the system----------------------------The operator signing key- ML-DSA-87 (FIPS 204), the only algorithm shirudo signs with.- ``shirudo genkey`` writes ``signing_key.pem`` (mode 0600) and- ``cert.der`` into ``/var/lib/shirudo/keys`` or ``--keys-dir``, and- refuses to overwrite an existing pair without ``--force``. The key- signs every upatch, every unload directive, every package index,- every tree publication and every vouch for another certificate.- It lives on the operator and never on a target. An organisation- may have several, one per team or per era; a target can trust them- all at once.--The certificate- A self-signed X.509 v3 certificate over the signing key, valid for- ten years from creation. Certificates are all a target holds, and- everything a target trusts chains to them: the kernel verifies- every signed loader against the set ``init`` enrolled in the bpf- keyring, and ``shirudo bpm`` verifies package indexes and tree- publications against the certificate a repository was registered- with. The digest of the enrolled set enters every boot's ``init``- event, so an operator who predicts a register value with ``shirudo- attest predict`` predicts it for exactly those certificates. A- certificate is named by its fingerprint, the SHA-256 of its public- key, which ``shirudo bpm key fingerprint`` and ``shirudo keys``- print.--The attestation and endorsement keys- These belong to the target's TPM, not to the operator: the- attestation key is a fixed-template P-256 primary the operator pins- by name at enrolment, and the endorsement key is the TPM's own,- vouched for by the manufacturer's certificate. Their lifecycle is- the TPM's; the `tpm <tpm.rst>`__ document covers both.--Transport certificates- The WebPKI certificates of registries and collectors authenticate- the transport and nothing else; the artifacts carry their own- signatures. They are the infrastructure's to manage.--``shirudo keys`` shows what a host holds: the certificate and, on an-operator, the key on disk; on a target the trusted set with each-member's voucher, and the kernel keyring that holds it once ``init``-has run. Two roles may share a host for development; production-operators and targets do not.--2) Enrollment, revocation and rotation-----------------------------------------The initial BPF certificate is inside the authenticated runtime image.-Additional certificates and their existing vouch signatures are in the-config image's ``keys/trusted/``; revocation records are in-``keys/revoked/``. A config signature approves that filesystem but does not-replace the BPF trust chain: a new BPF key still needs a valid vouch.--Shirudo enrolls the authorized BPF trust set at boot, then installs the-existing reject-all keyring restriction. That restriction cannot be replaced-or bypassed by trusted image callers. There is no live key enrollment and-no new keyring restriction or key-lifetime kernel hooks are required.--To enroll a key, create its vouch on the operator and include the certificate-and vouch in the signed config selected for the next boot. Reboot is required-before the live keyring can use the new signer. Live update refuses a-candidate requiring a signer absent from the keyring before measuring it;-it does not accept that candidate as pending enrollment. To revoke a key,-include its certificate under ``keys/revoked/<fingerprint>.der`` in a new-signed config. Activation unlinks it and purges affected upatches. The config-PCR records the selected trust settings and the NV register records each-purged upatch's unload. Target ``keys add``, ``bpm key add`` and-``keys revoke`` are refused; there is no target-local override. Removing-a certificate file alone is not a revocation.--The current CLI does not stage a new signer for the next boot. The saved-activation record selects its cached bundle ahead of the initial-``config.image`` default, so changing that default and rebooting is-insufficient on an already initialized target. A complete operational-rollout for changing that boot selection is not provided by this CLI;-provisioning must account for the existing selection without discarding its-journal. Do not use the refused live-update path as a staging operation.--The config PCR records the selected trust settings; the boot enrolls keys.-Merely omitting a certificate from a newer image does not revoke a key already-enrolled during this boot; use an explicit revocation record. Vouch-verification retains the historical chain to the initial runtime-certificate. Revoking a key for BPF signature verification does not erase-its earlier authorization of a successor or remove the immutable vouch-anchor.--The config verification certificate is a separate bootstrap trust choice.-It lives in authenticated runtime ``shirudo.conf`` as a reference to a-certificate inside that image. Replacing it requires a new runtime image,-an updated authenticated boot hash and reboot. Provide a config that the-new certificate verifies before rebooting. A config update cannot rotate-its own verification key.--Shirudo accepts older correctly signed config images. Revocation-freshness therefore depends on selecting the intended config; neither its-signature nor its PCR measurement prevents rollback. This is a deferred-policy, not permanent local revocation storage.--3) Preparing a new signer----------------------------Generate the new key on its operator and have an already trusted operator-vouch for its public certificate::-- shirudo genkey --keys-dir new-operator-keys- shirudo keys vouch new-operator-keys/cert.der \- --keys-dir current-operator-keys -o new-cert.vouch- shirudo bpm key fingerprint new-operator-keys/cert.der--Put the certificate and vouch at ``keys/trusted/<fingerprint>.der`` and-``keys/trusted/<fingerprint>.vouch`` in the config source. Build and sign the-image, then provision it as part of the authenticated boot rollout. A running-target refuses live config requiring an unenrolled signer. It must reboot-with the intended boot selection before accepting BPF from that key.--Keep both keys while rolling out newly signed upatches and repository-certificates. Once the new key is enrolled and its upatches replace the old-ones, deliver a config with the old certificate at-``keys/revoked/<fingerprint>.der``. Activation removes the old live key and-purges upatches it signed. Preserve earlier vouches needed to validate the-chain. Check the expected config root and predicted upatch register in-attestation, not just the target's local status.--4) Custody-------------* The signing key belongs on a host with the controls of a certificate- authority: offline or isolated, with access limited to the people- who publish. The operator role needs no network beyond the registry- it pushes to.-* The key is a PEM file protected by file permissions; shirudo does- not use PKCS#11 or an HSM. Keep the directory on an encrypted- volume and back it up encrypted, with the certificate beside it.-* Keep separate pairs for development, staging and production fleets- with ``--keys-dir``, and never enrol a development certificate on a- production target. The test suites generate throwaway pairs of- their own.-* A vouch extends the trust of every target that holds the vouching- key. Treat ``keys vouch`` like a signing operation: run it on the- operator host, for a certificate whose holder you have verified out- of band, and keep the vouch with the certificate it is for; it is- useless for any other.-* Record each certificate's fingerprint and the ``init_event`` of the- sets the fleet runs (``status --json`` on a target, ``attest- predict`` on the operator), and check them wherever a certificate is- copied: into the initrd, into a registry registration, into an- inventory.-* Treat a key that left the operator host, even once, as compromised.diff --git a/Documentation/operate/attest.rst b/Documentation/operate/attest.rstnew file mode 100644index 00000000..88451b14--- /dev/null+++ b/Documentation/operate/attest.rst@@ -0,0 +1,400 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators, SecOps++Attest targets+==============++``shirudo status`` is the target's own account of itself, and a target+that root controls can say anything. Attestation gives you an account+the target cannot forge: the TPM signs the measurement register and the+PCRs for a nonce you chose, and you check the signature and the values+on the operator host against what you installed.++This page enrolls a target once, then collects and verifies evidence.+The checks only mean something when you pin the values the target+reports about itself, so the verification step lists the options you+must pass.++Before you begin+----------------++- The operator package on the operator host. ``attest verify``,+ ``attest predict`` and ``attest challenge`` run there, offline. They+ need no TPM. A target running shirudo refuses any argument that starts+ with ``--cert``, so do not run them on a target.+- A target that completed init: ``shirudo status`` reports ``ok``.+ :doc:`/operate/read-status` explains the report.+- On the target, ``shirudo`` is the runtime image's binary, as+ :ref:`runtime-invocation` sets up.+- For enrollment: the PEM bundle of your TPM manufacturer's+ endorsement key issuers, or the endorsement key name from an+ inventory you trust.+- Your records of what the target runs: the certificates it enrolled,+ the upatches it restored at boot, every load and unload since, and the+ root hash of the config you activated.++What a verifier must pin+------------------------++``shirudo attest verify`` checks that the evidence is consistent and+signed by a TPM. Whether it is the right TPM and the right state is up+to the options you pass. Without them, any TPM that signs a consistent+document passes, as `A verify that pins nothing`_ shows.++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Option+ - What it pins+ * - ``--ak-name=<ak-name>``+ - The attestation key that signed the quote and the register+ certification is the one you enrolled. Required: without it, any+ TPM's key passes.+ * - ``--expect-bind-pcr=9=<pcr9>`` and ``--expect-bind-pcr=11=<pcr11>``+ - The PCR values the register was bound to at init. PCR 11 holds the+ ``enter-initrd`` phase only while the initrd runs, so the PCR 11+ value proves that init bound the register from the initrd.+ Required. Without them, verify recomputes the register's name from+ the values the target recorded about itself.+ * - ``--require-initrd``+ - The init record says the binding was made in the initrd. The+ record is the target's own word, so this option does not replace+ ``--expect-bind-pcr=11``.+ * - ``--expect-chain=<register>``, or ``--cert=`` with ``--upatch=``+ - The register equals the value you predicted for the certificates,+ the boot set and the events you expect. One of the two is+ required. Without either, no state is checked.+ * - ``--expect-config-root=<config-root>`` with+ ``--expect-config-pcr=<config-pcr>``+ - The config the target activated is the one you approved, recorded+ in the PCR the runtime bootstrap file names. Required. The first+ option needs the second.+ * - ``--ek-name=<ek-name>``+ - The endorsement key in the evidence is the enrolled one.+ * - ``--expect-credential=<credential>``+ - The attestation key activated the credential you made for it+ under the endorsement key. Used at enrollment. Needs+ ``--ak-name``.+ * - ``--allow-runtime-events``+ - With ``--cert=``, accepts any number of loads, unloads,+ revocations and tree operations after boot, as long as each one+ replays and derives from its own fields. It does not compare them+ with anything you expect. Pin runtime events with+ ``--expect-chain`` instead.+ * - ``--strict-anchor``+ - Nothing was extended into PCR 9 after the register's anchor.+ Without it, verify notes further measurements and passes.++Enroll a target+---------------++Enroll a target once per TPM. You record the name of its attestation+key and prove that the key sits in the same TPM as an endorsement key+you trust.++1. Choose a nonce on the operator host:++ .. code-block:: console++ operator$ openssl rand -hex 32++2. Collect evidence on the target, with that nonce:++ .. code-block:: console++ target# shirudo attest --nonce=<nonce> --out=enroll.json++ ``<nonce>`` is the hex string from step 1. The command prints nothing+ on success and writes the file with mode ``0600``. Copy+ ``enroll.json`` to the operator host.++3. Read the names of the attestation key and the endorsement key:++ .. code-block:: console++ operator$ jq -r .ak.name enroll.json+ operator$ jq -r .ek.name enroll.json++4. Make a credential challenge for that attestation key under the+ endorsement key:++ .. code-block:: console++ operator$ shirudo attest challenge --evidence=enroll.json \+ --ak-name=<ak-name> --ek-ca=<ek-issuers.pem> --out=challenge.json++ ``<ak-name>`` is the name from step 3. ``<ek-issuers.pem>`` is your+ manufacturer's issuer bundle. The endorsement certificate in the+ evidence must chain to it. A TPM without an endorsement certificate,+ as virtual TPMs usually are, needs ``--ek-name=<ek-name>`` from an+ inventory you trust instead. ``--trust-presented-ek`` waives the+ check and proves only that the same TPM answers each time. The+ command prints its checks, then ``challenge: challenge.json`` and+ ``credential: <credential>``. Keep the credential on the operator+ host.++5. Copy ``challenge.json`` to the target and answer it, with a new+ nonce:++ .. code-block:: console++ target# shirudo attest --nonce=<nonce-2> --challenge=challenge.json \+ --out=answer.json++ The TPM can recover the credential only when the attestation key and+ the endorsement key are in it. The command refuses with+ ``attest: the challenge was refused (tampered?)`` otherwise.++6. Verify the answer on the operator host:++ .. code-block:: console++ operator$ shirudo attest verify --evidence=answer.json --nonce=<nonce-2> \+ --ak-name=<ak-name> --ek-name=<ek-name> --expect-credential=<credential>++ The report must contain+ ``ok: attestation key: activated the credential made for it under the endorsement key``+ and end with ``verdict: ok``.++7. Record ``<ak-name>`` and ``<ek-name>`` for this target in your+ inventory. Every later verification pins them.++Predict the register+--------------------++Compute the register value the target should hold from your own+records, never from the target's eventlog.++1. Read the payload digest of every upatch you loaded after boot:++ .. code-block:: console++ operator$ shirudo upatch info --json <upatch> | jq -r .payload_sha256++ ``<upatch>`` is the ``.upatch`` file you loaded.++2. Predict the register:++ .. code-block:: console++ operator$ shirudo attest predict --cert=cert.der --cert=own.der \+ --event=load:basic=46f3d9f5f6568bddb7692cad28e99a86a3104192d8a2251f9ef9ec6d593c2035+ set_digest: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855+ init_event: cb206abf8e514bc714fc69f372d464d2c7512f1489431aed2319551c5ed34b9a+ register_at_boot: d1bdb80f7c0cfc1560f0a5a0b974d282bfd05fc95852b7649d59a054b450aa51+ register_after_events: ff0eb201e073fdeeba80a4b268f039bea58ec6dd2998e6651c4834ee99f3e103++ Pass one ``--cert=`` for each certificate the target enrolled: the+ runtime primary and each vouched certificate of the selected config,+ without the revoked ones. Pass one ``--upatch=`` for each upatch the+ target restored at boot. Pass one ``--event=`` for each change after+ boot, in+ order: ``load:<name>=<payload-sha256>``,+ ``unload:<name>=<payload-sha256>``,+ ``revoke:<label>=<cert-sha256>`` or ``tree:<seq>=<digest>``.++ ``set_digest`` covers the boot set, ``init_event`` is the init+ record's digest and ``register_at_boot`` is the register right after+ init. ``register_after_events`` is the value to pin with+ ``--expect-chain``. Without events, pin ``register_at_boot``. The+ test target in the example enrolled two certificates, ``cert.der`` and+ ``own.der``, restored no upatch at boot and loaded one after.++Collect evidence+----------------++1. Choose a fresh nonce on the operator host:++ .. code-block:: console++ operator$ openssl rand -hex 32++2. Collect the evidence on the target:++ .. code-block:: console++ target# shirudo attest --nonce=<nonce> --out=ev.json++ The evidence holds the TPM quote of PCRs 0 to 7, 9 and 11 to 15, the+ certified register, this boot's eventlog records and the config+ activation history. ``--pcrs=`` selects other PCRs. The command+ refuses while a config activation is pending or cannot be verified,+ and when the register is not bound this boot.++3. Copy ``ev.json`` to the operator host.++Verify evidence+---------------++1. Get the binding values for the UKI the target booted: the PCR 9 and+ PCR 11 values at the moment init bound the register. Record them from+ a boot of the same UKI on a host you trust, where they are the+ ``tpm.pcr_before`` and ``tpm.phase_before`` fields of+ ``shirudo status --json``. systemd's+ ``systemd-measure calculate --phase=enter-initrd`` also computes the+ PCR 11 value from the UKI's sections.++2. Verify the evidence with every value pinned:++ .. code-block:: console++ operator$ shirudo attest verify --evidence=ev.json --nonce=<nonce> \+ --ak-name=<ak-name> --ek-name=<ek-name> \+ --expect-bind-pcr=9=<pcr9> --expect-bind-pcr=11=<pcr11> \+ --require-initrd --expect-chain=<register> \+ --expect-config-root=<config-root> --expect-config-pcr=<config-pcr>++ ``<register>`` is the value from `Predict the register`_.+ ``<config-root>`` is the content of ``<prefix>.roothash`` of the config+ you activated. ``<config-pcr>`` is ``config.pcr`` of the runtime+ bootstrap file.++3. Check the exit status: 0 for ``verdict: ok``, 1 for ``verdict: FAIL``+ and 2 for a usage error or a file that is not an evidence document.++The report prints one line per check, ``ok:`` or ``FAIL:``, and+``note:`` lines that check nothing. This is a real report from a test+target, verified with ``--ak-name`` and ``--expect-chain`` only:++.. code-block:: console++ operator$ shirudo attest verify --evidence=ev.json --nonce=$NONCE \+ --ak-name=<ak-name> --expect-chain=<register>+ ok: nonce matches the request+ ok: attestation key: restricted, fixed to this TPM+ ok: attestation key: name matches its public area+ ok: attestation key: the pinned key+ ok: endorsement key: name matches its public area+ ok: endorsement key: TCG default template under the endorsement policy+ ok: quote: ECDSA signature by the attestation key+ ok: quote: signed by the key as an endorsement primary+ ok: quote: carries the nonce+ ok: quote: covers the PCRs the document lists+ ok: quote: PCR digest matches the listed values+ ok: register: ECDSA signature by the attestation key+ ok: register: signed by the key as an endorsement primary+ ok: register: carries the nonce+ ok: register: certification names the listed index+ ok: register: certified contents match the listed value+ ok: quote and certification are of one TPM reset+ ok: config: config root history matches the quoted PCR+ note: config root has no operator approval; use --expect-config-root with --expect-config-pcr+ note: config records a selection; direct TPM writer protection is deferred+ ok: eventlog: this boot has an init record+ ok: register: the document names index 0x01818E00 and PCRs 9 and 11+ ok: register: public area is bound to PCRs 9 and 11 as recorded+ note: binding: made in the initrd+ ok: eventlog: one init record for this TPM reset (1 this boot)+ ok: register: init record is of the TPM's current reset count+ ok: eventlog: 2 records replay to the certified value+ ok: anchor: record digest matches the index name+ ok: anchor: PCR 9 equals the recorded value extended by the anchor+ ok: state: register equals the expected value+ note: event after boot: upatch_load basic+ verdict: ok++Read it in groups:++- The nonce, attestation key and endorsement key lines say the TPM you+ enrolled signed this evidence for your request.+- The quote and register lines say the PCR values and the register+ value are what the TPM certified, in one TPM reset.+- The config lines replay the config activation history to the quoted+ config PCR. The note says no root was pinned: this run left out+ ``--expect-config-root``.+- The eventlog and binding lines replay this boot's records to the+ certified register and recompute the register's name from the PCR+ values it was bound to. ``note: binding: made in the initrd`` is the+ target's own claim. With ``--expect-bind-pcr``, the report adds+ ``binding: PCR 9 held the expected value`` and the same line for+ PCR 11, which check the binding against values you know.+- ``state: register equals the expected value`` is the line that ties+ the evidence to your records. The ``event after boot`` notes list what+ changed the register since init.++With ``--expect-config-root``, the config line checks that the last+activation recorded is your root.++What failure looks like+~~~~~~~~~~~~~~~~~~~~~~~++A wrong or stale nonce fails the first check, and the verdict follows:++.. code-block:: console++ operator$ shirudo attest verify --evidence=ev.json --nonce=<wrong-nonce> \+ --ak-name=<ak-name>+ FAIL: nonce matches the request+ ok: attestation key: restricted, fixed to this TPM+ ...+ verdict: FAIL++A target whose state differs from your records fails the state lines.+This report is from a second test target. The verifier expected the boot+set only, but a load and an unload happened after boot:++.. code-block:: console++ operator$ shirudo attest verify --evidence=ev.json --nonce=$NONCE \+ --ak-name=<ak-name> --cert=cert.der --require-initrd --strict-anchor+ ...+ ok: binding: made while the initrd ran+ ok: eventlog: one init record for this TPM reset (1 this boot)+ ok: register: init record is of the TPM's current reset count+ ok: eventlog: 3 records replay to the certified value+ ok: anchor: record digest matches the index name+ ok: anchor: PCR 9 equals the recorded value extended by the anchor+ FAIL: state: init event covers the expected certificate, set and tree root+ FAIL: state: 2 events after boot change the register+ note: event after boot: upatch_load shirudo-test-basic+ note: event after boot: upatch_unload shirudo-test-basic+ verdict: FAIL++The init event line fails too, because that target enrolled two+certificates and the verifier passed one. A failed state check does not+tell you which side is wrong. Compare the notes with your records before+you conclude anything, and follow :doc:`/operate/incident-tampered` when+the target ran something you did not install.++A verify that pins nothing+~~~~~~~~~~~~~~~~~~~~~~~~~~++Evidence from the second test target above, verified with only the+evidence and the nonce:++.. code-block:: console++ operator$ shirudo attest verify --evidence=ev.json --nonce=$NONCE+ attest verify: no --ak-name; the signer is not pinned+ ok: nonce matches the request+ ok: attestation key: restricted, fixed to this TPM+ ok: attestation key: name matches its public area+ note: attestation key not pinned: name 000b6e354140b22198138167393ecd1233cfc27e8b16ef0b2b60cce88563c5588dbc+ ...+ note: no expected state given; the register value is e57e1428ab398e758b63f8eda52bac87b5d85c1368c2d8d786ed446448e46239+ note: event after boot: upatch_load shirudo-test-basic+ note: event after boot: upatch_unload shirudo-test-basic+ verdict: ok++The verdict is ``ok`` and the exit status 0, but the run proves only+that some TPM signed a consistent document for this nonce. A consistent+document from any TPM passes, whatever the target runs. Treat a+verification without ``--ak-name`` and without an expected state as no+verification.++Next steps+----------++- :doc:`/operate/incident-tampered` when a target refuses with+ ``tampered`` or fails verification.+- :doc:`/reference/cli/attest`, :doc:`/reference/cli/attest-verify`,+ :doc:`/reference/cli/attest-predict` and+ :doc:`/reference/cli/attest-challenge` for every option.+- :doc:`/concepts/measurement-register` and+ :doc:`/internals/measurement-register` for what the register records.+- :doc:`/security/threat-model` for what attestation does not cover.diff --git a/Documentation/operate/backup-recovery.rst b/Documentation/operate/backup-recovery.rstnew file mode 100644index 00000000..b3b6e238--- /dev/null+++ b/Documentation/operate/backup-recovery.rst@@ -0,0 +1,364 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Back up, recover and decommission a target+==========================================++shirudo refuses to paper over a state it cannot vouch for, so several+failures have one way out: a reboot. One has no way out in place. This+page lists what to back up, how to get a target out of each state that+blocks it, and how to take a target out of service.++Every procedure here works with shirudo as it is. Where no recovery+exists, the page says so.++Before you begin+----------------++- Root on the target. On the target, ``shirudo`` stands for the runtime+ image's binary, ``/run/shirudo/runtime/usr/bin/shirudo``+ (:ref:`runtime-invocation`).+- For a decommission, the operator host that builds and signs the+ target's UKI.++What to back up+---------------++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Item+ - Why it matters+ * - ``/var/lib/shirudo/eventlog``+ - The target's measurement history across boots. Nothing else holds+ it, so it is evidence you cannot recreate.+ * - ``/var/lib/shirudo/config-update/``+ - The config activation journal: each activation with its TPM reset+ and restart counts. Evidence, tied to this target's TPM.+ * - ``/var/lib/shirudo/images/``+ - The runtime image and every config bundle the target has+ activated, named by root hash. The operator holds the originals.+ * - ``/var/lib/shirudo/upatches/`` and ``/var/lib/shirudo/bpm/``+ - The upatch archive that ``init`` restores at boot, the installed+ packages and the tree state. The registry holds the packages.+ * - ``/etc/shirudo/``+ - Host files: ``bpm/environment``, ``map-export.env``, and+ ``shirudo.conf`` when the dracut module takes the initrd's+ bootstrap file from there.+ * - ``/etc/systemd/system/shirudo*.d/``+ - The runtime drop-ins of the shirudo units.+ * - On the operator host+ - The signing keys (:doc:`keys`), the image source directories and+ bootstrap files, the UKI build inputs, and each target's+ attestation key name, endorsement key pin and expected values+ (:doc:`attest`).++Back up a target+~~~~~~~~~~~~~~~~++The seal stops writes to ``/var/lib/shirudo`` but not reads, so root can+copy the state while enforcement is up.++#. Archive the state and the host configuration:++ .. code-block:: console++ target# tar --create --gzip --file=<archive> /var/lib/shirudo \+ /etc/shirudo /etc/systemd/system++ ``<archive>`` is a path outside ``/var/lib/shirudo``, for example+ ``/root/shirudo-state.tar.gz``.++#. Save the journal of shirudo's messages:++ .. code-block:: console++ target# journalctl -t shirudo -o export > <journal-file>++#. Copy both files off the target.++Restore+~~~~~~~++shirudo has no restore command, and while enforcement is up the seal+refuses root's writes into ``/var/lib/shirudo``. You cannot restore files+into a running target. Rebuild a lost target instead:++#. Provision it again (:doc:`boot-integration`, :doc:`initialize`).+#. Install its packages from the registry (:doc:`deliver-packages`).+#. Keep the old eventlog, journal and activation journal with your+ records as the history of the old installation.++Do not copy an eventlog, an activation journal or the tree state+``/var/lib/shirudo/bpm/upatch-tree/`` onto another target. The tree+state records how far its own target got in the tree, and another+target would skip every operation up to that point.++Plan for eventlog growth+------------------------++The eventlog grows by one record for each boot, upatch load and unload,+key revocation and tree operation. shirudo never rotates or truncates+it, has no command to, and the seal stops root from doing it. In the+test VM, the init record of a target with two certificates takes 1975+bytes and a load adds 336:++.. code-block:: console++ target# shirudo status+ ...+ Eventlog: /var/lib/shirudo/eventlog (2 entries, 2311 bytes)+ ...++Every command that reads the eventlog reads all of it, plus the pending+record of the initrd, and refuses when the two exceed 8 MiB (8388608+bytes). ``eventlog.max_bytes`` in the signed config sets a lower cap: at+the cap, ``upatch load`` and ``upatch unload``, and the package and tree+commands built on them, refuse with ``eventlog_full``.+``init`` checks the same cap and the same read limit before it binds the+register, so a target whose eventlog reaches either one fails ``init`` at+every boot (:ref:`backup-recovery-init-failed`). At about 2 KB per boot,+that takes a few thousand boots with no other events, and fewer with+loads and tree operations.++Watch ``assets.eventlog_bytes`` in ``shirudo status --json`` or the+keepalive (:doc:`telemetry`), and decommission and reprovision a target+well before it reaches the limit.++Nothing removes old bundles from ``/var/lib/shirudo/images`` either.+Each config you activate stays there under its root hash, so size config+images with the ``--size`` option of ``shirudo-gen-image``.++Recover a target+----------------++A config activation is pending+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Symptoms:++- ``shirudo status`` reports ``reboot-pending`` with the reason ``a+ config activation is pending until the next reboot``.+- ``shirudo image status`` prints ``"pending":true`` and exits 1.+- Every other command prints ``shirudo: image state: Operation now in+ progress`` and exits 1.++Cause: ``shirudo image update`` stopped after it saved the pending+selection, or ``init`` failed after it recorded this boot's activation+(:ref:`backup-recovery-init-failed`).++#. Read why in the journal:++ .. code-block:: console++ target# journalctl -b -t shirudo++#. Reboot when it suits you. shirudo never reboots a node itself, and+ the node keeps running in this state with enforcement up.++#. Check after the reboot that ``shirudo status`` reports ``ok`` and+ ``shirudo image status`` prints ``"pending":false`` and+ ``"consistent":true``.++At the next boot, ``init`` verifies the pending selection, records a+fresh boot activation and completes. There is no command that clears a+pending activation in the same boot, and the seal stops you from+removing the journal.++.. _backup-recovery-init-failed:++init failed after it recorded the boot's activation+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++``init`` records the boot's config activation before it restores the+archived upatches and binds the TPM register. A failure in either step+leaves the activation pending. The journal shows one of:++.. code-block:: text++ init: boot-restore failed; further changes and attestation remain blocked+ init: incomplete -- LSM active and upatches loaded, but TPM register not advanced++In this state the LSM is attached and enforcement is up. The upatches+restored before the failure stay loaded, the register is not bound, and+``shirudo status`` reports ``reboot-pending`` with the ``ChainIntact``+detail ``no register bound this boot (init incomplete)``. Every command+that reads target state is refused, except ``status`` and ``image``.++A second ``init`` in the same boot does not help. It stops with:++.. code-block:: text++ image: activation is pending; further changes are blocked+ init: loading authenticated boot settings failed: Operation now in progress++#. Find the step that failed in the journal of both runs:++ .. code-block:: console++ target# journalctl -b -u shirudo-initrd.service -u shirudo.service++#. Fix the cause. A cause in the boot inputs needs new boot inputs+ (:doc:`boot-integration`). An archived upatch that fails to load+ needs the next procedure.++#. Reboot.++An archived upatch no longer loads at boot+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++The usual cause is a new kernel on which an upatch fails with+``verifier_rejected``, ``attach_target_missing`` or+``kernel_abi_unsupported``. The journal shows ``boot-restore: failed to+apply <file>`` before the ``init`` lines above. ``init`` restores the+archive in name order and stops at the first failure without unloading+what it already loaded.++``init`` restores the same archive at every boot, so a reboot fails the+same way. These do not work:++- A second ``init``: it refuses the pending activation.+- ``shirudo bpm uninstall`` and ``shirudo upatch unload``: every command+ that reads target state is refused, except ``status`` and ``image``.+- Deleting the file from ``/var/lib/shirudo/upatches``: the seal refuses+ it.++What works is to remove the upatch from a boot on which it loads:++#. Boot a kernel on which the upatch loads, usually the previous one,+ from a UKI that names the runtime image still in+ ``/var/lib/shirudo/images``.+#. Check that ``shirudo status`` reports ``ok``.+#. Remove the upatch. Uninstall its package with+ ``shirudo bpm uninstall <package>``, unload it with its unload+ directive (:doc:`/reference/cli/upatch-unload`), or, for an upatch+ from the tree, publish a ``delete`` operation and let the tree sync+ apply it.+#. Boot the new kernel.++If no kernel loads the upatch, shirudo offers no recovery in place.+Decommission the target and provision it again. To avoid the state,+make sure every archived upatch loads on a new kernel before you reboot+into it (:doc:`upgrade`).++TPM reset or restarted without a reboot+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++The activation journal records the TPM's reset and restart counts. When+either changes while the system runs, as on a resume from hibernation:++- Every command that reads target state, except ``status`` and+ ``image``, prints ``shirudo: image state: Stale file handle`` and+ exits 1. ``init``, ``genkey``, ``build``, ``help`` and ``version``+ skip that check.+- ``shirudo status`` reports ``tampered`` with the reason ``the selected+ config cannot be verified against its records``, and ``ConfigActive``+ reads ``the config activation record does not belong to this TPM boot+ (tamper?)``.+- The register can be gone, which ``ChainIntact`` reports as a warning.++If you know the TPM was reset, reboot. Do not run ``init`` again: after a+TPM reset it binds the register from the root file system, which a+verifier that pins PCR 11 rejects, and after a restart alone it refuses+to bind and leaves a config activation pending. If you do not know why+the counts changed, handle the target as in :doc:`incident-tampered`+before you reboot. :doc:`hardening` covers turning hibernation off.++Decommission a target+---------------------++Enforcement cannot be switched off while the target runs: the LSM links+are held by pins in the private bpffs that only shirudo could remove,+and shirudo has no command that removes them. Taking a target out of+service is a reboot into a boot path without shirudo.++#. Optional: uninstall every package, so the eventlog records each+ unload:++ .. code-block:: console++ target# shirudo bpm uninstall <package>++#. Save the eventlog and the journal as the target's last record, as in+ the backup procedure above.++#. Stop and disable the timers:++ .. code-block:: console++ target# systemctl disable --now shirudo-keepalive.timer \+ shirudo-map-export.timer shirudo-bpm-repo-update.timer \+ shirudo-bpm-tree-sync.timer++#. Disable the root service:++ .. code-block:: console++ target# systemctl disable shirudo.service++#. Remove the runtime drop-ins you installed (:ref:`unit-drop-ins`) and+ reload systemd:++ .. code-block:: console++ target# systemctl daemon-reload++#. Remove the target package, which removes the binary, the units and+ the dracut module:++ .. code-block:: console++ target# apt remove shirudo-target++ On RPM-based systems, run ``dnf remove shirudo-target``.++#. On the operator host, build and sign a UKI whose initrd does not+ contain the shirudo dracut module and whose kernel command line+ carries neither ``bpf.keyring_unsealed=1`` nor+ ``dm_verity.keyring_unsealed=1``, and make it the target's default+ boot entry. Without the module, ``shirudo-initrd.service`` does not+ run. Without the parameters, the kernel seals the ``.bpf`` and+ ``.dm-verity`` keyrings empty at boot. Regenerating the initrd on the+ target alone changes nothing a UKI boots. If the shirudo installer+ added the parameters, it wrote them through ``grubby``, to+ ``/etc/default/grub.d/shirudo.cfg`` or to ``/etc/kernel/cmdline``;+ remove them there too.++#. Reboot the target.++#. Check that the kernel left the ``.bpf`` keyring sealed:++ .. code-block:: console++ target# cat /sys/module/bpf/parameters/keyring_unsealed++ The file reads ``N``. ``/run/shirudo`` does not exist.++#. Remove the state. The seal stopped root from doing this before the+ reboot:++ .. code-block:: console++ target# rm -rf /var/lib/shirudo /etc/shirudo++#. On the operator host, retire the target: remove its attestation key+ name, endorsement key pin and expected values from your verifier's+ records, so that no evidence from it passes verification again.++The register's NV index ``0x01818E00`` stays defined in the TPM. If the+TPM goes to another use, remove the index with the owner hierarchy's+authorization, for example with ``tpm2_nvundefine 0x01818E00`` from+tpm2-tools.++Next steps+----------++- :doc:`troubleshooting` for messages by symptom.+- :doc:`incident-tampered` when ``status`` reports ``tampered``.+- :doc:`upgrade` to change the kernel without stranding an upatch.+- :doc:`/reference/files` for every file shirudo keeps.diff --git a/Documentation/operate/boot-integration.rst b/Documentation/operate/boot-integration.rstnew file mode 100644index 00000000..212ec312--- /dev/null+++ b/Documentation/operate/boot-integration.rst@@ -0,0 +1,490 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Boot integration+================++A production target starts shirudo from an authenticated initrd, before+any workload runs. The initrd verifies a dm-verity runtime image that+holds the trusted ``shirudo`` binary, and a signed config image that+holds the settings you may change later. This page takes one target+from operator keys to a verified first boot.++The procedure builds the images on the operator host, places them on the+target, generates the initrd with the shirudo dracut module, and builds a+signed UKI that carries the initrd and the kernel command line.+:doc:`/internals/boot-flow` explains what happens at boot, and+:doc:`/internals/config-images` explains the images.++Before you begin+----------------++- A target that meets :doc:`/operate/system-requirements`, with the+ kernel options and command line from :doc:`/operate/hardening`+ planned.+- The target package installed on the target. It installs the static+ ``shirudo`` binary, the systemd units, ``shirudo-gen-initrd`` and the+ dracut module ``90shirudo``. dracut must be installed.+- The operator package, ``mkfs.ext4`` and ``veritysetup`` on the operator+ host. The operator package installs the image generators in+ ``/usr/libexec/shirudo/gen-image/`` and the helper in+ ``/usr/libexec/shirudo/shirudo-build``. In a checkout they are+ ``tools/gen-image/`` and ``tools/shirudo-build/shirudo-build``.+- The static target binary of the build you deploy: ``shirudo-target``+ from ``make target`` in a checkout, or ``/usr/bin/shirudo`` from the+ target package. Use the same build on the target and in the runtime+ image.+- The BPF signing certificate and the config signing key, created as+ described in :doc:`/operate/keys`. They may be the same key.+- Tooling to build and sign a UKI for Secure Boot, for example systemd's+ ``ukify``.++On the operator host, put the generators and the helper where the+commands below find them:++.. code-block:: console++ operator$ export PATH=/usr/libexec/shirudo/gen-image:$PATH+ operator$ export SHIRUDO_BUILD=/usr/libexec/shirudo/shirudo-build++Bootstrap files+---------------++A target reads two different bootstrap files. Both are called+``shirudo.conf`` on the target, and they take different keys.++.. list-table::+ :header-rows: 1+ :widths: 22 30 48++ * - File+ - Where it ends up+ - Keys+ * - Runtime bootstrap file+ - ``etc/shirudo/shirudo.conf`` in the runtime image, read as+ ``/run/shirudo/runtime/etc/shirudo/shirudo.conf``+ - Required: ``config.image``, ``config.verification_key``,+ ``config.pcr``. Optional: ``tpm.tcti``, ``tpm.owner_auth``,+ ``tls.classical_hosts``. A ``runtime.*`` key is refused.+ * - UKI bootstrap file+ - ``/etc/shirudo/shirudo.conf`` in the initrd, inside the signed UKI+ - Required: ``runtime.image``, ``runtime.root_hash``. Optional:+ ``tpm.owner_auth``.++You write the runtime bootstrap file first, because it goes into the+runtime image. The UKI bootstrap file names the root hash of that image,+so you can write it only after the runtime image exists.+:doc:`/reference/formats/configuration` describes every key.++When the TPM owner hierarchy has a password, set ``tpm.owner_auth`` in+both files. Init reads it from the UKI file when it creates the TPM+writer key in the initrd, and from the runtime file when it defines the+register and in every later command. Give the UKI file mode ``0600``+before you generate the initrd: init refuses an owner password from a+file that another user could read.++Build the config image+----------------------++The config image holds the settings you can replace later with+``shirudo image update``. Its ``etc/shirudo/shirudo.conf`` is mandatory+and accepts only ``eventlog.max_bytes`` and ``map_export.*`` keys.++1. Create the source tree of the config image on the operator host:++ .. code-block:: console++ operator$ mkdir -p config-root/etc/shirudo++2. Write ``config-root/etc/shirudo/shirudo.conf``:++ .. code-block:: ini++ eventlog.max_bytes = 0++ shirudo refuses a config image whose file holds any other key, a line+ longer than 1023 bytes, or a line that is not a comment and has no+ ``=``. Repository definitions, the upatch tree subscription, node+ labels and further trusted keys go in the same tree. :doc:`/operate/deliver-packages` and+ :doc:`/operate/keys` describe them. The tree holds only regular files+ and directories, at most 65536 entries and 32 levels deep.++3. Build and sign the image:++ .. code-block:: console++ operator$ shirudo-gen-image --source config-root --output initial \+ --keys-dir <config-keys-dir> --kind config++ ``<config-keys-dir>`` holds ``signing_key.pem`` and ``cert.der`` of the+ config signing key. The generator writes ``initial.img``,+ ``initial.verity``, ``initial.roothash`` and ``initial.p7s`` and+ prints the root hash. It refuses to overwrite existing files and a+ source tree that holds a private key, a symbolic link or a special file.++4. Check the signature offline:++ .. code-block:: console++ operator$ shirudo image verify initial --cert <config-keys-dir>/cert.der++ The command prints the root hash again. ``image verify`` takes exactly+ this argument order.++Build the runtime image+-----------------------++1. Write the runtime bootstrap file, ``runtime.conf``:++ .. code-block:: ini++ config.image = /var/lib/shirudo/images/initial+ config.verification_key = /run/shirudo/runtime/etc/shirudo/config-cert.der+ config.pcr = 14+ tpm.tcti = device:/dev/tpmrm0++ ``config.image`` names the config image's prefix on the target. It must+ be below ``/var/lib/shirudo/images/``. Init uses it only on the first+ boot: from then on the activation record selects the config.+ ``config.verification_key`` must be a path inside the runtime image,+ and ``shirudo-gen-runtime`` puts the config certificate at the path+ shown. ``config.pcr`` is the TPM PCR that records config activations:+ 0 to 15, except 9 and 11. Choose a PCR that nothing extends after the+ initrd has run, because a later extension makes every command but+ ``status`` refuse until the next reboot. :doc:`/operate/hardening` discusses+ the choice. The test VM uses 14. A target needs a ``device:`` TCTI.++2. Build the runtime image and the drop-in for ``shirudo.service``:++ .. code-block:: console++ operator$ shirudo-gen-runtime --binary <target-binary> \+ --bootstrap-conf runtime.conf --cert <bpf-cert> \+ --config-cert <config-keys-dir>/cert.der --output runtime \+ --keys-dir <config-keys-dir> --unit-output runtime-service.conf++ ``<target-binary>`` is the static target binary. ``<bpf-cert>`` is the+ primary BPF signing certificate, which the image carries as+ ``keys/cert.der``. The generator writes ``runtime.img``,+ ``runtime.verity``, ``runtime.roothash`` and ``runtime.p7s``, prints the+ root hash on standard output and the runtime invocation on standard+ error, and writes the drop-in to ``runtime-service.conf``.++ Every executable on the runtime image runs with shirudo's authority.+ Add one with ``--extra-binary`` only when it should have that+ authority, and never add a shell or an interpreter.++3. Read the runtime root hash:++ .. code-block:: console++ operator$ cat runtime.roothash++Write the UKI bootstrap file+----------------------------++1. Write ``uki-bootstrap.conf`` with the runtime root hash:++ .. code-block:: ini++ runtime.image = /var/lib/shirudo/images/runtime+ runtime.root_hash = <runtime-root-hash>++ ``<runtime-root-hash>`` is the 64-character content of+ ``runtime.roothash``. ``runtime.image`` is the runtime image's prefix as+ the initrd sees it. The initrd checks the image against this hash and+ refuses any other.++Place the images on the target+------------------------------++Place the images before the first boot with enforcement. Once init has+run, the seal refuses root's writes and new entries under+``/var/lib/shirudo``.++1. Create the image directory on the target's root file system:++ .. code-block:: console++ target# install -d -m 0700 -o root -g root /var/lib/shirudo/images++2. Copy the runtime image into it:++ .. code-block:: console++ target# install -m 0644 runtime.img runtime.verity runtime.roothash \+ /var/lib/shirudo/images/++ The runtime image needs these three files. Its root hash comes from the+ UKI, so the target does not use ``runtime.p7s``.++3. Copy the config image into it:++ .. code-block:: console++ target# install -m 0644 initial.img initial.verity initial.roothash \+ initial.p7s /var/lib/shirudo/images/++ A config image needs all four files.++``/var/lib/shirudo`` must be a directory on the root file system, or on a+file system the initrd mounts below ``/sysroot`` (``x-initrd.mount``).+``shirudo-initrd.service`` remounts ``/sysroot`` read-write, because init+writes the activation record there before it extends the config PCR.++.. _unit-drop-ins:++Install the unit drop-ins+-------------------------++The shipped units start the installed binary, ``/usr/bin/shirudo`` from+the package. On an enforcing target that binary has no runtime authority, and shirudo refuses it before it does+anything. Every target service needs a drop-in that runs the runtime+image's binary instead. ``shirudo-initrd.service`` needs none: it runs in+the initrd, from the binary the UKI authenticates.++1. Install the drop-in that ``shirudo-gen-runtime`` wrote:++ .. code-block:: console++ target# install -D -m 0644 runtime-service.conf \+ /etc/systemd/system/shirudo.service.d/runtime.conf++ For the static binary its directives are:++ .. code-block:: ini++ [Service]+ EnvironmentFile=+ ExecStart=+ ExecStart=/run/shirudo/runtime/usr/bin/shirudo init++2. Write ``/etc/systemd/system/shirudo-keepalive.service.d/runtime.conf``:++ .. code-block:: ini++ [Service]+ ExecStart=+ ExecStart=/run/shirudo/runtime/usr/bin/shirudo status --otel --include-system++3. Write ``/etc/systemd/system/shirudo-map-export.service.d/runtime.conf``:++ .. code-block:: ini++ [Service]+ ExecStart=+ ExecStart=/run/shirudo/runtime/usr/bin/shirudo upatch map --all++4. Write ``/etc/systemd/system/shirudo-bpm-repo-update.service.d/runtime.conf``:++ .. code-block:: ini++ [Service]+ ExecStart=+ ExecStart=-/run/shirudo/runtime/usr/bin/shirudo bpm repo update+ ExecStart=/run/shirudo/runtime/usr/bin/shirudo bpm upgrade++ The leading ``-`` keeps the upgrade running when one registry cannot+ be reached, as in the shipped unit.++5. Write ``/etc/systemd/system/shirudo-bpm-tree-sync.service.d/runtime.conf``:++ .. code-block:: ini++ [Service]+ ExecStart=+ ExecStart=/run/shirudo/runtime/usr/bin/shirudo bpm tree sync++6. Reload systemd:++ .. code-block:: console++ target# systemctl daemon-reload++For a dynamically linked binary, use the invocation that+``shirudo-gen-runtime`` printed, which runs the binary through the+image's own loader and libraries, in place of+``/run/shirudo/runtime/usr/bin/shirudo``.+:doc:`/reference/systemd-units` lists the units and their schedules.++The deb and rpm packages enable ``shirudo.service`` and the four timers+for the next boot. Their message "To enforce now: systemctl start+shirudo.service" does not apply: the unit runs only when the initrd has+mounted the runtime image at ``/run/shirudo/runtime``.++Build the initrd+----------------++1. Generate the initrd on the target:++ .. code-block:: console++ target# shirudo-gen-initrd --bootstrap-conf uki-bootstrap.conf \+ --cert <bpf-cert> --kver <kernel-release> \+ --output /boot/initrd-shirudo-<kernel-release>.img++ ``<kernel-release>`` is the release of the kernel the UKI boots.+ ``<bpf-cert>`` is the primary BPF signing certificate. The initrd+ carries it for the pre-flight check and for the unit's start+ condition. The initrd embeds the installed ``/usr/bin/shirudo``,+ ``uki-bootstrap.conf`` as ``/etc/shirudo/shirudo.conf``,+ ``shirudo-initrd.service`` enabled, the TPM drivers and the dm-verity,+ loop and ext4 modules.++ With ``--bootstrap-conf`` or ``--cert``, the generator runs dracut with+ a configuration of its own and ignores ``/etc/dracut.conf`` and+ ``/etc/dracut.conf.d/``. Pass further dracut options after ``--``.++2. Check the result:++ .. code-block:: console++ target# shirudo-gen-initrd --check /boot/initrd-shirudo-<kernel-release>.img++ The check fails unless the archive holds the binary, the certificate,+ the bootstrap file, the unit and its enablement,+ ``systemd-pcrphase-initrd.service`` and ``/etc/initrd-release``.++The generator also says that the kernel command line lacks+``bpf.keyring_unsealed=1`` and ``dm_verity.keyring_unsealed=1`` when the+running kernel was booted without them. The next step adds them.++Build and sign the UKI+----------------------++1. Print the kernel parameters the initrd needs:++ .. code-block:: console++ target# shirudo-gen-initrd --print-cmdline+ bpf.keyring_unsealed=1 dm_verity.keyring_unsealed=1++2. Build a UKI from the kernel image, the initrd and a command line that+ carries both parameters, and sign it for Secure Boot.++ Without the parameters the kernel seals both keyrings empty at boot,+ and init fails. The command line also needs ``bpf`` in the ``lsm=``+ list, unless ``CONFIG_LSM`` has it already, and the settings from+ :doc:`/operate/hardening`.++3. Install the UKI on the target's EFI system partition and make it the+ default boot entry.++The UKI must boot through systemd's stub, so that+``systemd-pcrphase-initrd.service`` measures the ``enter-initrd`` phase+into PCR 11 before init binds the measurement register. Without a+measured UKI, init logs that PCR 11 holds no phase measurement, and a+verifier cannot tell an initrd binding from a later one.++No other unit may seal ``.bpf`` or ``.dm-verity`` before+``shirudo-initrd.service`` runs, for example systemd's+``systemd-keyring-setup`` where your systemd ships it. Init refuses a+keyring that another task restricted, and fails.++.. _runtime-invocation:++Run shirudo on the target+-------------------------++On a production target, the only ``shirudo`` with runtime authority is+the binary on the runtime image, ``/run/shirudo/runtime/usr/bin/shirudo``.+shirudo's LSM programs grant that authority to a process when it executes+a file from the authenticated runtime image. Any other copy of the+binary, the package's ``/usr/bin/shirudo`` included, is refused before+the command starts:++.. code-block:: console++ target# /usr/bin/shirudo status+ shirudo: image state: Permission denied++The exit status is 1. No wrapper ships for interactive use. Define an+alias in your root shell:++.. code-block:: console++ target# alias shirudo=/run/shirudo/runtime/usr/bin/shirudo++The operate pages write ``target# shirudo`` for this binary. A+dynamically linked runtime binary runs through the image's loader, with+the invocation that ``shirudo-gen-runtime`` prints. Of the target+commands, only ``version`` and ``help`` work from another copy.++Boot and verify+---------------++1. Reboot the target into the UKI:++ .. code-block:: console++ target# systemctl reboot++2. Read the status report:++ .. code-block:: console++ target# shirudo status+ Host: docs+ Roles: target+ Mode: production+ Status: ok+ Version-ID: 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0++ Conditions:+ TYPE STATUS DETAIL+ LsmAttached OK lsm/bpf link present and pinned+ KeyringSealed OK serial=420195959 in the BPF keyring, pin matches+ ChainIntact OK live register == eventlog replay+ TpmMeasured OK NV index 0x01818E00 readable+ ConfigActive OK config 12dbf3c75083.. is active+ ...+ TPM Measurement:+ TPM: reachable (device:/dev/tpmrm0)+ NV index: 0x01818E00 (anchored in PCR 9)+ ...+ Bound in: initrd+ Chain vs eventlog: matches+ ...++ Check for ``Mode: production``, ``Status: ok``, five ``OK``+ conditions and ``Bound in: initrd``. ``ConfigActive`` names the first+ 12 hex digits of the active config root. :doc:`/operate/read-status`+ explains every section.++3. Check the config activation:++ .. code-block:: console++ target# shirudo image status+ {"root_hash":"12dbf3c750834908c0f6510481e35fbb0cc76cf6b1896de524304535e63aff0f","pcr":14,"sequence":1,"reset_count":1,"restart_count":0,"pending":false,"consistent":true}++ ``root_hash`` is the root of ``initial``, ``pcr`` is ``config.pcr``,+ ``pending`` is ``false`` and ``consistent`` is ``true``. The command+ exits 1 when the activation is pending or inconsistent.++4. Read both init runs in the journal:++ .. code-block:: console++ target# journalctl -b -u shirudo-initrd.service -u shirudo.service++ The initrd run ends with+ ``tpm: register bound in the initrd and extended (index 0x01818E00,+ PCR 9 anchored, <n> upatches in set)`` and+ ``init: complete (LSM active, writable state sealed)``. The root run+ logs ``tpm: register already bound this boot; chain unchanged`` and+ completes. :doc:`/operate/initialize` describes both runs and what to+ do when one fails.++Next steps+----------++- :doc:`/operate/initialize` to check init after every boot and handle+ its failures.+- :doc:`/operate/attest` to enroll the target's attestation key.+- :doc:`/operate/deliver-packages` to deliver upatches from a registry.+- :doc:`/operate/upgrade` to replace the runtime image or the kernel.diff --git a/Documentation/operate/bug-report.rst b/Documentation/operate/bug-report.rstnew file mode 100644index 00000000..38a3d542--- /dev/null+++ b/Documentation/operate/bug-report.rst@@ -0,0 +1,236 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Report a bug+============++Collect what the maintainers need to reproduce a problem, remove what+identifies your hosts, and file it as a GitHub issue. This page is for+bugs. A suspected vulnerability goes to :doc:`/security/reporting`+instead, privately.++Before you begin+----------------++- Decide whether the problem is a vulnerability: a way to load BPF that+ no trusted key signed, to detach or bypass enforcement, to change+ sealed state, or to make evidence verify for a state the target is not+ in. Report those as :doc:`/security/reporting` describes, and do not+ open a public issue.+- If a command refused with ``tampered`` or ``shirudo status`` reports+ ``tampered``, preserve the evidence first, as+ :doc:`/operate/incident-tampered` describes, and do not reboot the+ target before it is safe.+- Reproduce the problem on the ``main`` branch. shirudo has no releases+ yet (:doc:`/reference/versions`).+- Root on the target. On a target, ``shirudo`` is the binary on the+ runtime image (:doc:`/operate/boot-integration`).+- A directory on the target for the files, here ``bug/``, outside+ ``/var/lib/shirudo``. shirudo refuses to write a report into sealed+ state.++Collect on the target+---------------------++1. Record the version and the version ID:++ .. code-block:: console++ target# shirudo version > bug/version.txt++ It prints two lines, for example::++ shirudo (58d3fa7-dirty-rc0, "Social BPF Coding")+ version-id: 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0++2. Save the status with the system block and the eventlog:++ .. code-block:: console++ target# shirudo status --json --include-system --include-eventlog \+ > bug/status.json++ The ``system`` block holds the kernel release, version and build ID,+ and every ``CONFIG_*`` value from ``/boot/config-<release>`` when that+ file exists. :doc:`/reference/formats/status-json` lists the fields.++3. Save the pre-flight checks:++ .. code-block:: console++ target# shirudo init --check-only > bug/preflight.txt++ ``--check-only`` runs the pre-flight checks and stops there.++4. Save the report of the command that fails. ``upatch load`` and+ ``upatch unload`` write one with ``--report``:++ .. code-block:: console++ target# shirudo upatch load --report=bug/load-report.json <upatch>++ ``<upatch>`` is the artifact that fails to load. ``bpm tree sync``+ prints its report to standard output, or to ``--report=<path>``. Run+ a command again only to get its report. Never repeat a command that+ refused with ``tampered``.++5. Save shirudo's journal of this boot:++ .. code-block:: console++ target# journalctl --boot --identifier=shirudo \+ --output=short-iso-precise > bug/journal.txt++ shirudo logs under the identifier ``shirudo``, from the initrd's+ ``init`` on. For a problem in an earlier boot, pass that boot, for+ example ``--boot=-1``.++6. Save the kernel's messages of this boot:++ .. code-block:: console++ target# journalctl --boot --dmesg --output=short-iso-precise \+ > bug/kernel.txt++7. Record the kernel command line and the active LSMs:++ .. code-block:: console++ target# cat /proc/cmdline /sys/kernel/security/lsm > bug/cmdline.txt++8. If ``kernel_config`` in ``status.json`` is empty, because there is no+ ``/boot/config-<release>``, save the configuration the kernel carries+ instead:++ .. code-block:: console++ target# zcat /proc/config.gz > bug/config.txt++ This needs ``CONFIG_IKCONFIG_PROC``. Otherwise take the configuration+ from the kernel build.++9. Add the kernel tree, the commit and the patches applied to it. A+ release number does not identify a bpf-next kernel, see+ :doc:`/operate/system-requirements`.++Collect on the operator host+----------------------------++Collect these when the problem involves a build, a package, a+publication or a verification:++1. Record the operator's version:++ .. code-block:: console++ operator$ shirudo version > bug/operator-version.txt++2. Record the package and the toolchain:++ .. code-block:: console++ operator$ dpkg-query --show shirudo-operator >> bug/operator-version.txt+ operator$ openssl version >> bug/operator-version.txt+ operator$ clang --version >> bug/operator-version.txt++ On an RPM-based host use ``rpm --query shirudo-operator``. The+ ``shirudo-build`` helper has no version command. Note which one ran:+ ``SHIRUDO_BUILD`` if set, else ``/usr/libexec/shirudo/shirudo-build``,+ else the first on ``PATH``.++3. Save the exact command line, its complete output and its exit status.++4. For a problem with an artifact, save what it declares:++ .. code-block:: console++ operator$ shirudo upatch info --json <upatch> > bug/upatch-info.json++ Attach the artifact itself only if you may share the program it+ carries.++5. For a problem with ``attest verify`` or ``attest predict``, save the+ command and its report. Attach the evidence document only after you+ have read the next section.++Remove what identifies your hosts+---------------------------------++None of the files above contains the TPM owner password or a registry or+collector credential. ``shirudo config`` prints ``tpm.owner_auth`` as+redacted and has no credential settings. They do contain values that+identify your hosts and your infrastructure:++.. list-table::+ :header-rows: 1+ :widths: 34 36 30++ * - Value+ - Where+ - Identifies+ * - Host name+ - ``system.hostname``, the journal+ - The host+ * - ``machine_id``, ``boot_id``+ - ``status.json``. ``boot_id`` also in the evidence document+ - The host and the boot+ * - Attestation key name, endorsement key and its certificate+ - The evidence document, ``attest`` command lines+ - The TPM. Its endorsement key is unique to it+ * - The firmware event log and systemd's measurement log+ - ``logs`` in the evidence document+ - The firmware, its boot entries, and what systemd measured, which+ can include the machine ID+ * - Certificate SHA-256 values and fingerprints+ - ``status.json`` and the eventlog in it+ - Your signing keys+ * - Registry hosts and repositories, OTLP endpoint, S3 URI, tenant ID+ - The journal of the bpm and export units, ``shirudo config``+ - Your infrastructure+ * - Addresses, user names, paths+ - The journal, the kernel messages+ - Hosts and people++Replace each value with the same placeholder everywhere it appears, so+that the files stay consistent with each other.++Never attach these files:++- ``/etc/shirudo/shirudo.conf`` from the initrd or from the runtime+ image. Both carry ``tpm.owner_auth``.+- ``/etc/shirudo/bpm/environment`` and ``/etc/shirudo/map-export.env``.+ They carry registry and collector credentials.+- Registry authentication files.+- The operator's key directory, ``/var/lib/shirudo/keys`` by default or+ the one ``--keys-dir`` names. It holds the private signing key.++File the issue+--------------++1. Open https://github.com/shirudo-dev/shirudo/issues/new.+2. Write a title that names the command or component and the symptom,+ for example ``upatch load: verifier_rejected for a kprobe upatch``.+3. Describe what you did, what you expected and what happened, and give+ the shirudo commit, the version IDs of the target and the operator,+ and the kernel tree and commit.+4. Attach the files from ``bug/`` and submit the issue.++Verify+------++Open the issue and read each attachment once more for a value from the+table above. If one slipped through, delete the attachment and attach a+cleaned copy.++Next steps+----------++- :doc:`/operate/troubleshooting` for known symptoms and their causes.+- :doc:`/reference/failure-categories` for the category and phase in a+ report.+- :doc:`/operate/interoperability` when the problem involves other+ software on the target.diff --git a/Documentation/operate/deliver-packages.rst b/Documentation/operate/deliver-packages.rstnew file mode 100644index 00000000..ae1d0091--- /dev/null+++ b/Documentation/operate/deliver-packages.rst@@ -0,0 +1,415 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Deliver packages+================++Targets pull signed packages from OCI registries. You publish a package+on the operator host, and every target that follows the repository+installs or upgrades it on its own. This page shows how to point targets+at a repository, how to install, upgrade and remove packages by hand,+and how the timers and the upatch tree deliver them without you.++How a package reaches a target+------------------------------++Delivery is a pull in four steps:++#. On the operator host, ``shirudo bpm push`` publishes the package and+ a signed entry in the repository index ``shirudo/bpm-index:stable``.+#. On the target, ``shirudo bpm repo update`` fetches that index from+ each repository, verifies its signature against the repository's+ certificate and caches it under+ ``/var/lib/shirudo/bpm/repos/<name>/index.json``.+#. ``shirudo bpm upgrade`` installs, for every package installed from a+ repository, the highest version in the cached index that is newer+ than the installed one.+#. The install checks the package archive against the digest in the+ index, refuses a package whose ``cert.der`` does not carry the public+ key of ``/var/lib/shirudo/keys/cert.der``, and loads each upatch the+ way ``shirudo upatch load`` does. The kernel verifies each loader's+ signature against the ``.bpf`` keyring, and shirudo measures each load+ into the TPM register.++``shirudo-bpm-repo-update.service`` runs ``bpm repo update`` and then+``bpm upgrade``. Its timer starts it at boot and again 60 seconds after+each run ends. A version you push to a repository index therefore+reaches every target that follows the repository about a minute later,+with nobody logged in. Treat every push to an index as a fleet-wide+rollout.++What is configured where+------------------------++A target reads its package inputs from the signed config image, not from+the host's ``/etc/shirudo``. Copies of these files on the host root file+system have no effect while a config image is active.++.. list-table::+ :header-rows: 1+ :widths: 30 40 30++ * - Input+ - Location on the target+ - How you change it+ * - Repository definitions+ - ``etc/shirudo/bpm/registries.d/<name>.conf`` in the config image+ - New signed config, ``shirudo image update``+ * - Repository certificates+ - ``etc/shirudo/bpm/keys/`` in the config image+ - New signed config, ``shirudo image update``+ * - Subscription to the upatch tree+ - ``etc/shirudo/bpm/upatch-tree.conf`` in the config image+ - New signed config, ``shirudo image update``+ * - Node labels for tree selectors+ - ``etc/shirudo/node.labels`` in the config image+ - New signed config, ``shirudo image update``+ * - Hosts allowed classical TLS key exchange+ - ``tls.classical_hosts`` in the runtime image's+ ``etc/shirudo/shirudo.conf``+ - New runtime image and a reboot+ * - Registry credentials and transport+ - ``/etc/shirudo/bpm/environment`` on the host+ - Root on the target, no signature+ * - Installed packages+ - ``/var/lib/shirudo/bpm/state.json``+ - ``bpm install``, ``bpm upgrade``, ``bpm uninstall``++While a config image is active, the target refuses local changes to+these inputs. ``bpm config register add``, ``remove`` and ``rm`` exit 1+with ``image mode: change repository definitions and keys in a signed+config image, then run `shirudo image update```. ``bpm key add`` exits 1+with ``image mode: add vouched BPF signers to the signed config selected+for boot and reboot to enroll them``.++systemd reads ``/etc/shirudo/bpm/environment`` for the two package+services. The file can set registry credentials (``BPM_OCI_USERNAME``+with ``BPM_OCI_PASSWORD``, ``BPM_OCI_BEARER_TOKEN``,+``REGISTRY_AUTH_FILE``, ``DOCKER_CONFIG``), cleartext transport+(``BPM_OCI_SCHEME=http``) and an extra CA certificate+(``BPM_OCI_CA_FILE``). It is host state outside the signed config, and+root on the target can change it. The signatures on the index, the+package and the upatches do not depend on it, but the transport does.+:doc:`/reference/environment` lists every variable, and+:doc:`/security/threat-model` describes what root on the target can do+with it.++Before you begin+----------------++- An initialized target (:doc:`initialize`) whose services run the+ runtime binary (:ref:`unit-drop-ins`).+- On the target, ``shirudo`` stands for the runtime image's binary,+ ``/run/shirudo/runtime/usr/bin/shirudo`` (:ref:`runtime-invocation`).+- A package published to a repository (:doc:`/start/guides/publish-package`).+- On the operator host, the source directory of the target's config+ image and the key that signs config images.++Add a repository+----------------++#. In the config source directory, create+ ``etc/shirudo/bpm/registries.d/<name>.conf``:++ .. code-block:: text++ endpoint = oci://<registry-host>+ key_file = /etc/shirudo/bpm/keys/<name>.der++ ``<name>`` is the repository name that ``bpm install`` uses.+ ``<registry-host>`` is the registry's host name with an optional port+ and no path. ``key_file`` names a certificate inside the config+ image. The target refuses any other absolute path.++#. Copy the certificate whose key signs the repository index, the one+ you pass to ``bpm push``, to ``etc/shirudo/bpm/keys/<name>.der`` in+ the same directory.++#. Build, sign and activate the config, as described in+ :ref:`deliver-packages-config-update`.++#. List the repositories the target reads:++ .. code-block:: console++ target# shirudo bpm config register list++ The command prints one repository name per line.++#. Fetch the repository's index now instead of waiting for the timer:++ .. code-block:: console++ target# shirudo bpm repo update <name>++ The command prints nothing when it succeeds. When it fails, it prints+ ``bpm repo update: <reason>`` and exits 1. Without ``<name>`` it+ updates every repository, continues past one that fails and exits 1+ at the end.++.. _deliver-packages-config-update:++Change the signed config+------------------------++Every change to repositories, the tree subscription, node labels and+export settings is a new signed config image that the target activates+while it runs.++#. Build and sign the image from the config source directory:++ .. code-block:: console++ operator$ /usr/libexec/shirudo/gen-image/shirudo-gen-image \+ --source <config-root> --output <prefix> \+ --keys-dir <config-keys-dir> --kind config++ ``<config-root>`` is the source directory. It must contain+ ``etc/shirudo/shirudo.conf``, which accepts only ``eventlog.max_bytes``+ and ``map_export.*`` keys, and it must not contain symbolic links or+ special files. ``<prefix>`` is the output path without a suffix: the+ command writes ``<prefix>.img``, ``<prefix>.verity``,+ ``<prefix>.roothash`` and ``<prefix>.p7s`` and refuses to replace an+ existing file. ``<config-keys-dir>`` holds the key whose certificate+ the runtime image names in ``config.verification_key``. The path is+ the operator package's. From a checkout, run+ ``tools/gen-image/shirudo-gen-image`` and add ``--builder`` with the+ path of ``shirudo-build``.++#. Verify the bundle offline:++ .. code-block:: console++ operator$ shirudo image verify <prefix> --cert <config-cert>++ ``<config-cert>`` is the config verification certificate in DER. The+ command prints the root hash.++#. Copy the four files to the target, or serve them over HTTPS under one+ URL prefix.++#. Activate the config on the target:++ .. code-block:: console++ target# shirudo image update <prefix>++ ``<prefix>`` is the local path prefix of the four files, or their+ ``https://`` URL prefix. The command fetches and verifies the bundle,+ extends the config PCR and switches to the new config.++#. Check the activation:++ .. code-block:: console++ target# shirudo image status+ {"root_hash":"12dbf3c750834908c0f6510481e35fbb0cc76cf6b1896de524304535e63aff0f","pcr":14,"sequence":1,"reset_count":1,"restart_count":0,"pending":false,"consistent":true}++ This output is from a target that runs its boot config. After an+ update, ``root_hash`` is the root that ``image verify`` printed and+ ``sequence`` is higher. ``pending`` must be ``false`` and+ ``consistent`` must be ``true``. The command exits 1 otherwise. If an+ activation stays pending, follow :doc:`backup-recovery`.++Install a package+-----------------++#. Install the package from a repository:++ .. code-block:: console++ target# shirudo bpm install <name>/<package>++ ``<name>`` is the repository name and ``<package>`` the package name.+ Without a version, the command installs the highest version in the+ cached index. Append ``@<version>`` to choose one. The command loads+ each upatch of the package and prints what ``shirudo upatch load``+ prints.++#. Check that the package is installed:++ .. code-block:: console++ target# shirudo bpm list++ The command prints one line per installed package: its name, its+ version and the repository it came from, or ``direct`` for an+ ``oci://`` install.++#. Check that its upatches are loaded:++ .. code-block:: console++ target# shirudo upatch list+ upatches (/var/lib/shirudo/upatches):+ loaded type kind payload-sha256 name+ yes load bpf 8aee7072a1a15e4d.. shirudo-test-basic++ This target holds one upatch, loaded by hand. A package's upatches+ appear the same way, one line each.++``bpm install`` does nothing and exits 0 when a package of that name is+already installed, whatever its version. The repository timer moves an+installed package to the highest version in its index at its next run,+so ``@<version>`` does not hold a package at that version.++A package can also be installed straight from a registry reference:++.. code-block:: console++ target# shirudo bpm install oci://<registry-host>/<repository>:<tag>++No signed index covers such an install: the registry decides which+package the tag names. Its upatches still load only when a key in the+``.bpf`` keyring signed them. ``bpm upgrade`` leaves direct installs+alone.++Upgrade packages+----------------++#. Refresh the cached indexes:++ .. code-block:: console++ target# shirudo bpm repo update++#. Upgrade every package that has a newer version in its index:++ .. code-block:: console++ target# shirudo bpm upgrade++ ``bpm upgrade`` reads only the cached indexes. For each package it+ runs the old version's unload directives in reverse name order and+ then loads the new version's upatches. When a load fails, it unloads+ what it loaded, tries to load the old version again and exits 1.+ Packages it upgraded before the failure stay upgraded.++#. Check the versions with ``shirudo bpm list``.++The repository timer runs both steps every minute, so you need them only+to upgrade before the timer does.++Uninstall a package+-------------------++#. Uninstall the package:++ .. code-block:: console++ target# shirudo bpm uninstall <package>++ The command runs the package's unload directives in reverse name+ order, removes the package's files and removes it from the installed+ state. Each unload is measured. When an unload fails, the command+ prints ``bpm uninstall: unload <path> failed`` and stops.++#. Check that ``shirudo bpm list`` no longer lists it and that+ ``shirudo upatch list`` no longer shows its upatches.++Removing a package from its index does not uninstall it from targets:+``bpm upgrade`` skips an installed package that its index no longer+lists.++Follow the upatch tree+----------------------++The upatch tree is a signed, ordered list of ``add`` and ``delete``+operations that you append on the operator host with+``shirudo bpm tree append``. Each operation can carry selectors on the+kernel release, kernel build ID, architecture, kernel configuration and+node labels, so one publication serves a mixed fleet.++#. In the config source directory, create+ ``etc/shirudo/bpm/upatch-tree.conf``:++ .. code-block:: text++ endpoint = oci://<registry-host>/<repository>+ reference = <reference>++ ``<repository>`` is the tree's repository and ``<reference>`` the+ tag ``bpm tree append`` published to, ``stable`` unless you chose+ another.++#. If operations select on labels, write the target's labels to+ ``etc/shirudo/node.labels``, one ``<key>=<value>`` per line.++#. Build, sign and activate the config+ (:ref:`deliver-packages-config-update`).++#. Preview what a sync would apply:++ .. code-block:: console++ target# shirudo bpm tree sync --dry-run++ The command prints a JSON report with the counts ``selected``,+ ``skipped``, ``applied`` and ``module_skipped`` and the sequence+ number ``last_seq`` the target has reached. A dry run changes+ nothing.++``shirudo-bpm-tree-sync.timer`` runs ``bpm tree sync`` 60 seconds after+boot and every 60 seconds after that. Without a tree configuration the+command exits 0 and does nothing. Each applied operation is measured.++Keep these rules of the tree in mind:++- A sync moves the target's cursor past an operation whose selectors do+ not match. The target never applies that operation later, even when+ its labels or kernel change.+- An ``add`` whose attach target is in a kernel module that is not+ loaded is recorded as ``skipped: module not loaded``, and the cursor+ moves past it.+- The target verifies tree publications only against the runtime+ image's primary certificate, ``keys/cert.der``. A vouched key cannot+ sign them, and revoking the primary in the signed config does not stop+ them. :doc:`keys` describes the limit.++Timers and locks+----------------++.. list-table::+ :header-rows: 1+ :widths: 34 34 32++ * - Timer+ - Runs+ - When+ * - ``shirudo-bpm-repo-update.timer``+ - ``bpm repo update``, then ``bpm upgrade``+ - At boot, then 60 s after each run ends+ * - ``shirudo-bpm-tree-sync.timer``+ - ``bpm tree sync``+ - 60 s after boot, then every 60 s++Both services run the host's ``shirudo`` unless you installed the+runtime drop-ins (:ref:`unit-drop-ins`). An enforcing target refuses+that binary, so without the drop-ins nothing is delivered.++``bpm install``, ``upgrade``, ``uninstall``, ``repo update`` and+``tree sync`` take ``/var/lib/shirudo/locks/bpm.lock`` and wait for it+without a time limit. Every ``shirudo`` command on a target also holds+the config operation lock for its whole run, and a command that waits+longer than 30 seconds for it fails. A long download therefore delays+the status keepalive and the map export, and a keepalive can fail while+it runs. :doc:`troubleshooting` has the message.++Every command except ``status`` is refused while a config activation is+pending, ``bpm uninstall`` included. :doc:`backup-recovery` describes+that state.++Next steps+----------++- :doc:`/start/guides/publish-package` to publish a package.+- :doc:`/upatches/publishing` for packages, indexes and the tree on the+ operator side.+- :doc:`telemetry` to export what the installed upatches collect.+- :doc:`/reference/cli/bpm` for every ``bpm`` option.+- :doc:`/reference/formats/bpm-formats` for the index, package and tree+ formats.diff --git a/Documentation/operate/deployment-checklist.rst b/Documentation/operate/deployment-checklist.rstnew file mode 100644index 00000000..51c80478--- /dev/null+++ b/Documentation/operate/deployment-checklist.rst@@ -0,0 +1,173 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Deployment checklist+====================++Everything a production target needs, in the order you set it up. Each+item names the page that does it.++Plan+----++.. list-table::+ :header-rows: 1+ :widths: 6 54 40++ * - #+ - Item+ - Page+ * - 1+ - Hardware with a TPM 2.0, a kernel with the signed BPF loader+ interface, the BPF LSM and the dm-verity keyring, and systemd and+ dracut in the initrd.+ - :doc:`/operate/system-requirements`+ * - 2+ - Kernel configuration and command line chosen from the hardening+ checklist, including the PCR for config measurements.+ - :doc:`/operate/hardening`+ * - 3+ - Operator host with the operator package, ``veritysetup`` and+ ``mkfs.ext4``. It never runs as a target.+ - :doc:`/operate/system-requirements`+ * - 4+ - BPF signing key and config signing key created, with their+ custody decided.+ - :doc:`/operate/keys`++Build on the operator host+--------------------------++.. list-table::+ :header-rows: 1+ :widths: 6 54 40++ * - #+ - Item+ - Page+ * - 5+ - Initial config image built and signed. Its+ ``etc/shirudo/shirudo.conf`` holds only ``eventlog.max_bytes`` and+ ``map_export.*`` keys.+ - :doc:`/operate/boot-integration`+ * - 6+ - Repository definitions, the upatch tree subscription and node+ labels placed in the config image.+ - :doc:`/operate/deliver-packages`+ * - 7+ - Collector endpoint in the config image's ``map_export.*`` keys.+ - :doc:`/operate/telemetry`+ * - 8+ - Runtime bootstrap file written with ``config.image``,+ ``config.verification_key``, ``config.pcr`` and ``tpm.tcti``.+ - :doc:`/operate/boot-integration`+ * - 9+ - Runtime image built with the static target binary, the BPF+ certificate and the config certificate. Its root hash and the+ ``shirudo.service`` drop-in kept.+ - :doc:`/operate/boot-integration`+ * - 10+ - Version ID of the target binary recorded.+ - :doc:`/operate/upgrade`+ * - 11+ - UKI bootstrap file written with ``runtime.image`` and+ ``runtime.root_hash``.+ - :doc:`/operate/boot-integration`++Prepare the target+------------------++.. list-table::+ :header-rows: 1+ :widths: 6 54 40++ * - #+ - Item+ - Page+ * - 12+ - Target package and dracut installed.+ - :doc:`/operate/boot-integration`+ * - 13+ - Runtime and config images placed in ``/var/lib/shirudo/images``+ before the first boot with enforcement.+ - :doc:`/operate/boot-integration`+ * - 14+ - Drop-ins installed for ``shirudo.service``,+ ``shirudo-keepalive.service``, ``shirudo-map-export.service``,+ ``shirudo-bpm-repo-update.service`` and+ ``shirudo-bpm-tree-sync.service``.+ - :ref:`unit-drop-ins`+ * - 15+ - Environment files ``/etc/shirudo/map-export.env`` and+ ``/etc/shirudo/bpm/environment`` reviewed.+ - :doc:`/operate/hardening`+ * - 16+ - Initrd generated with ``shirudo-gen-initrd --bootstrap-conf`` and+ passed ``shirudo-gen-initrd --check``.+ - :doc:`/operate/boot-integration`+ * - 17+ - UKI built with ``bpf.keyring_unsealed=1`` and+ ``dm_verity.keyring_unsealed=1`` on its command line, signed for+ Secure Boot and installed as the default entry.+ - :doc:`/operate/boot-integration`++Boot and enroll+---------------++.. list-table::+ :header-rows: 1+ :widths: 6 54 40++ * - #+ - Item+ - Page+ * - 18+ - First boot completed: ``status`` reports ``ok``, ``Bound in:+ initrd``, and ``image status`` reports no pending activation.+ - :doc:`/operate/initialize`+ * - 19+ - Attestation key name recorded and the target's endorsement key+ checked with a credential challenge.+ - :doc:`/operate/attest`+ * - 20+ - Expected PCR 9 and PCR 11 values at binding, the expected register+ and the approved config root recorded for the verifier.+ - :doc:`/operate/attest`+ * - 21+ - First packages installed and their delivery through the timers+ observed.+ - :doc:`/operate/deliver-packages`++Run+---++.. list-table::+ :header-rows: 1+ :widths: 6 54 40++ * - #+ - Item+ - Page+ * - 22+ - Alerts on the ``status`` field of ``status --json``, on tamper+ counters and on a missing keepalive, not on the exit status.+ - :doc:`/operate/read-status`, :doc:`/operate/telemetry`+ * - 23+ - Attestation scheduled with a fresh nonce and the verifier's+ required flags.+ - :doc:`/operate/attest`+ * - 24+ - Backup of ``/var/lib/shirudo`` and of the operator's build inputs.+ - :doc:`/operate/backup-recovery`+ * - 25+ - Incident procedure for a ``tampered`` target agreed with the+ security team.+ - :doc:`/operate/incident-tampered`+ * - 26+ - Upgrade procedure for shirudo and the kernel tried on a canary+ target, with the previous UKI kept as a boot entry.+ - :doc:`/operate/upgrade`diff --git a/Documentation/operate/hardening.rst b/Documentation/operate/hardening.rstnew file mode 100644index 00000000..1be9873b--- /dev/null+++ b/Documentation/operate/hardening.rst@@ -0,0 +1,245 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators, SecOps++Hardening checklist+===================++shirudo keeps root from loading BPF, changing its state and extending+its register. It relies on the kernel and the boot chain for the rest:+root with a way to write kernel memory, replace the kernel or talk to the+TPM directly goes around every check shirudo makes. This checklist lists+what a production target needs beyond :doc:`/operate/system-requirements`,+and says for each item whether shirudo checks it.++The ``Checked`` column reads:++- ``init fails``: init refuses to bring enforcement up without it.+- ``warns``: init logs a warning and continues.+- ``enforced``: shirudo's LSM programs enforce it themselves.+- ``no``: nothing in shirudo checks it. Only your build, your boot chain+ or attestation catch a target without it.++:doc:`/security/threat-model` explains the threats behind each item.++Kernel configuration+--------------------++.. list-table::+ :header-rows: 1+ :widths: 30 52 18++ * - Item+ - Why+ - Checked+ * - Lockdown in integrity mode: ``CONFIG_SECURITY_LOCKDOWN_LSM`` with+ ``lockdown`` in the LSM list and ``lockdown=integrity``, or+ ``CONFIG_LOCK_DOWN_KERNEL_FORCE_INTEGRITY``+ - Without lockdown, root keeps ways to write kernel memory or+ reconfigure hardware that shirudo has no hook for: ``/dev/mem``,+ MSRs, I/O ports, PCI resources, debugfs, ACPI table overrides and+ hibernation images. Module signature enforcement alone does not+ close them. Do not use confidentiality mode: it withholds+ ``bpf_probe_read_kernel()`` from BPF programs, which shirudo's own+ programs need, so they would not load.+ - no+ * - Module signature enforcement: ``CONFIG_MODULE_SIG_FORCE`` or+ ``module.sig_enforce=1``, or lockdown, which also refuses unsigned+ modules+ - An unsigned module runs in the kernel with no BPF involved.+ - no+ * - ``CONFIG_STRICT_DEVMEM`` and ``CONFIG_IO_STRICT_DEVMEM``, or no+ ``/dev/mem`` at all+ - Limits ``/dev/mem`` when lockdown is not in force.+ - no+ * - ``CONFIG_BLK_DEV_WRITE_MOUNTED=n``+ - The seal acts on file operations. Root writing to the block+ device under ``/var/lib/shirudo`` changes sealed state without+ any of them. With the option off, the kernel refuses writes to a+ mounted block device.+ - no+ * - No hibernation: ``CONFIG_HIBERNATION=n``, ``nohibernate`` or+ lockdown+ - Resuming from a hibernation image replaces kernel memory with+ what the image holds. shirudo refuses kexec loads, but it does not+ refuse hibernation.+ - no+ * - Kexec+ - A kexec boots a kernel and initrd of root's choosing while the+ TPM keeps this boot's register and PCRs.+ - enforced: no task loads a kexec image or initramfs, counted as+ ``Kexec``+ * - 64-bit userspace only: ``CONFIG_COMPAT=n``, and on x86-64+ ``CONFIG_IA32_EMULATION=n`` and ``CONFIG_X86_X32_ABI=n``+ - shirudo's LSM programs are written for 64-bit callers.+ - no+ * - ``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG=y``+ - The kernel checks the config image's signature only with this+ option.+ - init fails: the config image cannot be mapped+ * - ``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_SECONDARY_KEYRING=n`` and+ ``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_PLATFORM_KEYRING=n``+ - The kernel tries the built-in trusted keys, the secondary keyring+ and the platform keyring before ``.dm-verity``. Every key in them+ can sign a config the target activates: the platform keyring holds+ firmware keys, and the secondary keyring takes further keys at+ runtime when a trusted key signed them. The built-in keys always+ count, including the module signing key of the kernel build, so+ keep that key in the same custody as the config key.+ - no+ * - The ``tpm_command`` LSM hook from ``kernel/0002`` in the shirudo+ tree+ - The hook lets shirudo refuse extensions of its register by+ other processes.+ - init fails: ``lsm/tpm_command`` cannot attach+ * - ``CONFIG_I2C_CHARDEV=n`` and ``CONFIG_SPI_SPIDEV=n``, or neither+ reaching the TPM's bus+ - The ``tpm_command`` hook sees only commands written through the+ kernel's TPM driver. Root with ``i2c-dev`` or ``spidev`` access to+ the TPM's bus sends commands past it.+ - no+ * - An IOMMU confining device DMA+ - A device that root can program, or one plugged in, can otherwise+ write kernel memory by DMA.+ - no++Kernel command line+-------------------++.. list-table::+ :header-rows: 1+ :widths: 30 52 18++ * - Item+ - Why+ - Checked+ * - ``bpf.keyring_unsealed=1``+ - Without it, the kernel seals ``.bpf`` empty at boot and init cannot+ enroll the BPF signers.+ - init fails+ * - ``dm_verity.keyring_unsealed=1``+ - Without it, the kernel seals ``.dm-verity`` empty at boot and init+ cannot enroll the config certificate.+ - init fails+ * - ``bpf`` in the LSM list+ - The LSM programs attach only when the BPF LSM is active.+ - init fails: pre-flight ``bpf_lsm_active``+ * - An authenticated command line, in the signed UKI, that the boot+ loader cannot replace+ - Root who can change the command line can drop the parameters+ above, or mask the initrd unit with+ ``rd.systemd.mask=shirudo-initrd.service``, and boot the target+ without enforcement.+ - no++Boot chain+----------++.. list-table::+ :header-rows: 1+ :widths: 30 52 18++ * - Item+ - Why+ - Checked+ * - A signed UKI that carries the shirudo initrd, booted with Secure+ Boot and measured boot+ - The UKI authenticates the initrd, its bootstrap file and the+ runtime image's root hash.+ - no+ * - The ``enter-initrd`` phase measured into PCR 11 before init+ - The PCR 11 value is how a verifier tells a binding made in the+ initrd from a later one. systemd measures the phase only for a+ UKI booted through its stub.+ - warns: ``tpm: PCR 11 holds no phase measurement``+ * - No unit seals ``.bpf`` or ``.dm-verity`` before+ ``shirudo-initrd.service``, for example systemd's+ ``systemd-keyring-setup``, which systemd 263 adds+ - Init must install the keyrings' restriction itself.+ - init fails: the keyring carries a restriction init did not+ install+ * - Monitoring for a target that boots without enforcement+ - A failed or skipped ``shirudo-initrd.service`` does not stop the+ boot. The target comes up with the verdict ``lsm-off`` and no+ register.+ - no: ``shirudo status`` and attestation show it+ * - Only shirudo's own executables on the runtime image+ - Every executable on the runtime image runs with shirudo's+ authority. Never add a shell, a debugger or an interpreter with+ ``--extra-binary``.+ - no++TPM+---++.. list-table::+ :header-rows: 1+ :widths: 30 52 18++ * - Item+ - Why+ - Checked+ * - A config PCR that nothing extends after the initrd: not IMA's PCR,+ 10 by default, and not PCR 15, which systemd extends with the+ machine ID, file systems and encrypted volumes+ - Any extension of the config PCR after init blocks every command+ but ``status`` until the next reboot, and ``status`` reports+ ``tampered``.+ - partly: init refuses PCRs 9, 11 and above 15, and ``status``+ detects a later extension+ * - A ``device:`` TCTI+ - A software TPM or another TCTI is for development.+ - init fails: an active target refuses any other TCTI+ * - Custody of the TPM owner password, when the TPM has one+ - The password is in the UKI's initrd and readable by root in the+ runtime image.+ - no+ * - Protection of the TPM device node+ - shirudo opens the TPM by its device path and does not+ authenticate the answers to its own commands. Evidence that+ :doc:`/operate/attest` verifies is signed by the TPM's attestation+ key and does not depend on that path.+ - no++Host files+----------++.. list-table::+ :header-rows: 1+ :widths: 30 52 18++ * - Item+ - Why+ - Checked+ * - ``/etc/shirudo/map-export.env`` and+ ``/etc/shirudo/bpm/environment`` empty, or owned by root with mode+ ``0600`` and reviewed+ - The timer services read them, and they are host files outside the+ signed config. Their variables reach processes with shirudo's+ authority: ``BPM_OCI_SCHEME=http`` switches registry traffic to+ cleartext, ``BPM_OCI_CA_FILE`` adds a trusted CA, and the+ ``OTEL_EXPORTER_OTLP_*`` variables name an export destination when+ the config names none. Signatures still protect what a target+ installs.+ - partly: the overrides ``SHIRUDO_KEYS_DIR``, ``SHIRUDO_TPM_TCTI``,+ ``SHIRUDO_TPM_OWNER_AUTH``, ``SHIRUDO_EVENTLOG_PATH``,+ ``SHIRUDO_EVENTLOG_PENDING_PATH``, ``SHIRUDO_INITRD_RELEASE`` and+ ``SHIRUDO_SYSROOT`` are refused+ * - ``/etc/shirudo/init.env`` absent+ - ``shirudo.service`` reads it unless the drop-in from+ ``shirudo-gen-runtime`` clears it, as+ :ref:`unit-drop-ins` installs.+ - no++Related+-------++- :doc:`/operate/system-requirements` for what shirudo needs to run.+- :doc:`/operate/boot-integration` for the UKI, the command line and the+ config PCR.+- :doc:`/operate/attest` for the checks that catch a target booted+ without these items.+- :doc:`/security/threat-model` for the threats and residual risks.diff --git a/Documentation/operate/incident-tampered.rst b/Documentation/operate/incident-tampered.rstnew file mode 100644index 00000000..101ce7e8--- /dev/null+++ b/Documentation/operate/incident-tampered.rst@@ -0,0 +1,220 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators, SecOps++Respond to a tampered target+============================++shirudo reports ``tampered`` when the state it protects is not what it+recorded. Handle every ``tampered`` as an incident: keep the evidence,+get an account from the TPM that the target cannot forge, and compare it+with your own records.++A target reports ``tampered`` in two ways:++- A command refuses with the failure category ``tampered``. A load or+ unload refuses before it touches the kernel when the BPF keyring is not+ the one init froze, when the LSM link is not pinned, or when the+ register differs from the value ``--expect-chain`` gave. The last case+ carries the message ``chain_drift``. A load is also undone when the+ register refuses its extension because it is not the register init+ bound. Init refuses when the register it recorded this boot is gone or+ replaced, or when another task restricted the BPF keyring first.+- ``shirudo status`` reports the verdict ``tampered``: the live register+ differs from the eventlog replay, the BPF keyring is not the one init+ froze or is gone, or the config PCR, the activation records and the+ mounted config disagree.++Do not retry the refused command, with or without an ``--expect-chain``+value read from the target. A value read from the target accepts+whatever changed it. Do not reboot the target before the evidence is+safe: a reboot starts a new register, and the TPM can no longer certify+the state of this boot.++A tamper counter that moved is a different signal: something tried an+operation and the LSM refused it. :doc:`/security/tamper-counters`+explains the counters.++Before you begin+----------------++- Root on the target. On the target, ``shirudo`` is the runtime image's+ binary, as :ref:`runtime-invocation` sets up.+- The operator host with the operator package, and a place off the+ target for the evidence.+- The target's enrolled attestation key name, and the values+ :doc:`/operate/attest` pins: the endorsement key name, the PCR 9 and+ PCR 11 binding values of its UKI, and the approved config root and PCR.+- Your records of what the target should run: the certificates it+ enrolled, the upatches it restored at boot, and every load and unload+ since.++Preserve the evidence+---------------------++1. Stop the timers that change state, so that nothing extends the+ register while you collect evidence:++ .. code-block:: console++ target# systemctl stop shirudo-bpm-repo-update.timer shirudo-bpm-tree-sync.timer++ ``shirudo-bpm-repo-update.timer`` runs ``shirudo bpm upgrade`` every+ 60 seconds, and ``shirudo-bpm-tree-sync.timer`` applies the upatch+ tree every 60 seconds. Both load and unload upatches.++2. Save the target's own account, with this boot's eventlog:++ .. code-block:: console++ target# shirudo status --json --include-eventlog > status.json++ ``status`` runs in every state, and it exits 0 even when the verdict is+ ``tampered``. Keep the file, but do not rely on it: the target wrote+ it.++3. Copy the eventlog, the pending init record and the config activation+ records:++ .. code-block:: console++ target# mkdir evidence+ target# cp /var/lib/shirudo/eventlog evidence/+ target# cp /var/lib/shirudo/config-update/state evidence/+ target# cp /var/lib/shirudo/config-update/events evidence/++ Copy ``/run/shirudo/eventlog.pending`` too when it exists. Use plain+ ``cp``. With ``-a`` or ``--preserve=xattr``, ``cp`` tries to copy the+ seal label to the copy, which the seal refuses and counts as+ ``SealLabel``.++4. Save the journal of this boot:++ .. code-block:: console++ target# journalctl -b -o export > evidence/journal.export++ shirudo logs under the identifier ``shirudo``. The journal holds the+ refusal messages, and an audit line for every measured load and+ unload with the register value after it.++5. Choose a fresh nonce on the operator host:++ .. code-block:: console++ operator$ openssl rand -hex 32++6. Have the TPM sign evidence for that nonce:++ .. code-block:: console++ target# shirudo attest --nonce=<nonce> --out=evidence/evidence.json++ When the config cannot be verified or its activation is pending,+ every command but ``status`` and ``image status`` refuses,+ ``attest`` included, with ``shirudo: image state:`` and the reason. The TPM cannot certify this+ boot's state then. Keep what steps 2 to 4 saved and go to+ `After the investigation`_.++7. Copy ``status.json`` and the ``evidence`` directory to the operator+ host.++Verify with the TPM+-------------------++1. Predict the register from your records, as+ :doc:`/operate/attest` describes. Never take the certificates or the+ events from the target's eventlog: that would check the target+ against itself.++ .. code-block:: console++ operator$ shirudo attest predict --cert=<cert> --upatch=<upatch> \+ --event=load:<name>=<payload-sha256>++ ``<cert>`` is each certificate the target enrolled, ``<upatch>`` each+ upatch it restored at boot, and each ``--event=`` one change after+ boot that you know of. Use ``register_after_events``, or+ ``register_at_boot`` when there are no events.++2. Verify the evidence with every value pinned:++ .. code-block:: console++ operator$ shirudo attest verify --evidence=evidence.json --nonce=<nonce> \+ --ak-name=<ak-name> --ek-name=<ek-name> \+ --expect-bind-pcr=9=<pcr9> --expect-bind-pcr=11=<pcr11> \+ --require-initrd --expect-chain=<register> \+ --expect-config-root=<config-root> --expect-config-pcr=<config-pcr>++ :doc:`/operate/attest` explains each option and the report.++Read the result+---------------++.. list-table::+ :header-rows: 1+ :widths: 30 38 32++ * - Result+ - Meaning+ - Next+ * - ``verdict: ok``+ - The TPM certifies a register that your records explain. For a+ ``chain_drift`` refusal, the value the command expected was out of+ date.+ - Find out who issued the command with that value. Record the+ incident.+ * - ``FAIL`` on ``state:`` lines only+ - The register is a genuine record, but it holds changes your+ records do not cover. The ``event after boot`` notes list them.+ Each was a signed artifact that a process with shirudo's+ authority loaded or unloaded.+ - Match every note with the journal's ``upatch load measured`` and+ ``upatch unload measured`` lines and with your change records,+ timers and tree included. A change nobody authorized means a+ signing key or root on the target is compromised.+ * - ``FAIL`` on ``eventlog:`` replay, ``register:``, ``anchor:`` or+ ``binding:`` lines+ - Something extended or replaced the register outside shirudo's+ records, or bound it outside the initrd.+ - Treat the target as compromised. Keep every file.+ * - ``FAIL`` on the nonce or the attestation key+ - The evidence is not this TPM's answer to your request.+ - Treat the target and the path you collected it on as+ compromised.+ * - ``attest`` refused with ``shirudo: image state:``+ - The config PCR, the activation records and the mounted config+ disagree, or an activation is pending.+ - Keep ``status.json``, the config activation records and the+ journal. The TPM cannot certify this boot.++After the investigation+-----------------------++1. Reboot the target once the evidence is off it. The new boot binds a+ new register and runs init from the initrd again.++2. Verify the new boot with every value pinned, as in+ `Verify with the TPM`_. An upatch that someone loaded with an+ enrolled key is in the archive, and init restores it at boot. The init+ event then covers it, and the verification fails on+ ``state: init event covers the expected certificate, set and tree root``.++3. Remove what you did not authorize: unload an upatch with a signed+ unload directive, or revoke its signer through a signed config as+ :doc:`/operate/keys` describes.++The timers you stopped start again at boot when they are enabled.++Related+-------++- :doc:`/operate/attest` for enrollment and the verification options.+- :doc:`/operate/read-status` for the verdicts and conditions.+- :doc:`/operate/troubleshooting` for the other failure messages.+- :doc:`/reference/failure-categories` for every category.+- :doc:`/security/threat-model` for what the measurement does not cover.diff --git a/Documentation/operate/index.rst b/Documentation/operate/index.rstnew file mode 100644index 00000000..80a99b8b--- /dev/null+++ b/Documentation/operate/index.rst@@ -0,0 +1,38 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++Operate+=======++These pages are for the engineers who deploy, run and troubleshoot+shirudo targets in production. Start with the+:doc:`/operate/deployment-checklist`, which lists every step from the+operator keys to a verified first boot and links the page that does each+one.++On a running target, :doc:`/operate/read-status` tells you what the+target reports about itself, and :doc:`/operate/attest` gets the same+answer signed by the target's TPM. When something fails, start from the+message in :doc:`/operate/troubleshooting`. A ``tampered`` refusal or+verdict is an incident: follow :doc:`/operate/incident-tampered`.++.. toctree::+ :titlesonly:++ system-requirements+ deployment-checklist+ boot-integration+ initialize+ deliver-packages+ keys+ attest+ read-status+ telemetry+ upgrade+ backup-recovery+ troubleshooting+ bug-report+ incident-tampered+ hardening+ interoperabilitydiff --git a/Documentation/operate/initialize.rst b/Documentation/operate/initialize.rstnew file mode 100644index 00000000..d05b4ca4--- /dev/null+++ b/Documentation/operate/initialize.rst@@ -0,0 +1,285 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Initialize a target+===================++``shirudo init`` brings enforcement up on every boot. It runs twice: once+from the initrd, where it does the work, and once from the root file+system, where it checks that work and records it. You do not run it by+hand. This page tells you what each run does, how to check that it+worked, and what to do when it did not.++Before you begin+----------------++- A target set up as described in :doc:`/operate/boot-integration`.+- A root shell on the target. On the target, ``shirudo`` means the+ runtime image's binary, ``/run/shirudo/runtime/usr/bin/shirudo``. See+ :ref:`runtime-invocation`.++What init does+--------------++.. list-table::+ :header-rows: 1+ :widths: 16 22 62++ * - Run+ - Unit and binary+ - What it does+ * - Initrd+ - ``shirudo-initrd.service``, with the binary in the initrd that the+ UKI authenticates+ - Binds ``/sysroot/var/lib/shirudo`` writable at+ ``/var/lib/shirudo``. Mounts the private bpffs. Verifies the+ runtime image against ``runtime.root_hash``, enrolls the config+ certificate in ``.dm-verity`` and seals it. Selects and verifies+ the config image, enrolls the BPF trust set in ``.bpf`` and seals+ it. Labels writable state, attaches the LSM programs, and mounts+ the runtime image at ``/run/shirudo/runtime``. Records a config+ BOOT event in the config PCR, applies the config's revocations,+ restores the archived upatches and binds the measurement register.+ Writes its init record to ``/run/shirudo/eventlog.pending``.+ * - Root file system+ - ``shirudo.service``, with the runtime image's binary through the+ drop-in+ - Checks that the keyring and the runtime image are the ones the+ initrd recorded and that the config activation is complete.+ Appends the pending init record to ``/var/lib/shirudo/eventlog``.+ Adds no register event.++The mounts under ``/run/shirudo`` survive the switch to the root file+system. :doc:`/internals/boot-flow` explains each step and the order.++Check that init worked+----------------------++1. Read the status report:++ .. code-block:: console++ target# shirudo status+ Host: docs+ Roles: target+ Mode: production+ Status: ok+ Version-ID: 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0++ Conditions:+ TYPE STATUS DETAIL+ LsmAttached OK lsm/bpf link present and pinned+ KeyringSealed OK serial=420195959 in the BPF keyring, pin matches+ ChainIntact OK live register == eventlog replay+ TpmMeasured OK NV index 0x01818E00 readable+ ConfigActive OK config 12dbf3c75083.. is active+ ...+ TPM Measurement:+ TPM: reachable (device:/dev/tpmrm0)+ NV index: 0x01818E00 (anchored in PCR 9)+ Chain: e57e1428ab398e758b63f8eda52bac87b5d85c1368c2d8d786ed446448e46239+ Register name: 000be3a552e2219550d2597ab96f3fffdeec0d01ce27cde858e0858ab0cdaba6c045+ Anchored: yes (name on record)+ PCR before init: 0000000000000000000000000000000000000000000000000000000000000000+ Phase at init: 0000000000000000000000000000000000000000000000000000000000000000 (PCR 11)+ Bound in: initrd+ Chain vs eventlog: matches+ Eventlog: /var/lib/shirudo/eventlog (3 entries, 2675 bytes)+ ...++ ``Status: ok`` and five ``OK`` conditions mean that enforcement is+ attached, the ``.bpf`` keyring is the one init sealed, the register+ matches the eventlog and the config is active. ``Bound in: initrd``+ says that the initrd run bound the register.++ ``PCR before init`` and ``Phase at init`` are PCR 9 and PCR 11 as init+ found them. The output comes from the test VM, which boots the kernel+ and initrd without a UKI, so both are zero. A target that boots a+ measured UKI shows its own values, and a verifier pins them as+ :doc:`/operate/attest` describes.++2. Check the fields a script reads:++ .. code-block:: console++ target# shirudo status --json++ .. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Field+ - Value after a good boot+ * - ``status``+ - ``"ok"``+ * - ``mode``+ - ``"production"``+ * - ``keyring_mode``+ - ``"bpf"``+ * - ``tpm.bound_in``+ - ``"initrd"``+ * - ``tpm.chain_matches_eventlog``+ - ``true``+ * - ``tpm.register_rebound``+ - ``false``+ * - ``config.activation_pending``+ - ``false``++ :doc:`/reference/formats/status-json` describes every field.++3. Check that the root run adopted the initrd's record:++ .. code-block:: console++ target# ls /run/shirudo/eventlog.pending++ The file must not exist. When it remains, ``shirudo.service`` did not+ run or failed, and its journal says why.++4. Read both runs in the journal:++ .. code-block:: console++ target# journalctl -b -u shirudo-initrd.service -u shirudo.service++ A complete initrd run logs+ ``tpm: register bound in the initrd and extended (index 0x01818E00,+ PCR 9 anchored, <n> upatches in set)`` and+ ``init: complete (LSM active, writable state sealed)``. The root run+ logs ``tpm: register already bound this boot; chain unchanged (index+ 0x01818E00)`` and the same last line.++To see which prerequisites init checks first, run the pre-flight alone.+It changes no persistent or enforcement state:++.. code-block:: console++ target# shirudo init --check-only+ pre-flight checks:+ root OK+ bpf_lsm_active OK+ bpffs_supported OK+ signed_loader_kernel_abi OK+ cert_on_disk OK+ cert_algorithm OK+ cert_kernel_support OK+ kernel_keyring OK+ embedded_loader OK+ tpm2_reachable OK: TCTI override: device:/dev/tpmrm0+ 10/10 passed (0 failed)++:doc:`/reference/cli/init` describes each check.++When init fails+---------------++A failed initrd run does not stop the boot. ``shirudo-initrd.service`` is+only wanted by ``initrd.target``, and nothing acts on its failure. The+host boots, and what it runs depends on the step where init stopped.+When the initrd lacks the shirudo module or its certificate, init does+not run at all and nothing reports an error.+``shirudo-gen-initrd --check`` detects such an initrd before you boot it.++.. list-table::+ :header-rows: 1+ :widths: 24 38 38++ * - Where init stopped+ - What you see+ - What to do+ * - Before the LSM programs attach: the pre-flight, the image+ settings, the bpffs, verifying the images and enrolling the keys,+ sealing state or loading enforcement.+ - The host runs without enforcement. ``shirudo.service`` is+ skipped, because the runtime image is not mounted. The keepalive+ service cannot start without the runtime binary, so the keepalive+ stops. ``status`` from any copy of the binary reports ``lsm-off``.+ - Read the initrd journal, fix the cause and reboot.+ * - After the LSM programs attach and before the config BOOT event:+ mounting the runtime image or selecting the config.+ - Enforcement is on. Depending on the step, the runtime binary is+ missing, commands fail with ``shirudo: image state: <error>``, or+ ``status`` reports a config condition that does not belong to+ this boot.+ - Keep the journal, fix the cause and reboot. When the journal does+ not explain the state, follow :doc:`/operate/incident-tampered`.+ * - After the config BOOT event: restoring upatches, binding the+ register or completing the boot.+ - Enforcement is on and the config activation stays pending.+ ``status`` reports ``reboot-pending``, and ``ChainIntact`` and+ ``TpmMeasured`` warn that no register is bound. Commands other+ than ``status`` and ``image status`` fail with+ ``shirudo: image state: Operation now in progress``, attestation+ included.+ - Fix the cause and reboot. A reboot without a fix fails at the+ same step.++Do not run ``shirudo init`` again in the same boot. After a failure past+the config BOOT event, init refuses with+``image: activation is pending; further changes are blocked`` and+``init: loading authenticated boot settings failed: Operation now in+progress``. Only a reboot clears the pending activation. A re-run after a+successful init changes nothing.++Do not run init from the root file system to make up for a failed initrd+run either. Workloads have already run without enforcement by then, and+the register would record a binding from the root file system, which a+verifier that pins PCR 11 rejects. Reboot instead.++Failures to restore upatches+~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Init restores the archived upatches in name order and stops at the first+one that fails, with ``boot-restore: failed to apply <file>`` and+``init: boot-restore failed; further changes and attestation remain+blocked``. The upatches it loaded before that one stay loaded, and no+register measures them. The archive is sealed, so the next boot tries+the same upatch again. The usual cause is a kernel on which the upatch+no longer loads. :ref:`boot-restore-lockout` describes the way out.++Register binding failures+~~~~~~~~~~~~~~~~~~~~~~~~~++When init cannot bind the register, it logs+``init: incomplete -- LSM active and upatches loaded, but TPM register+not advanced`` after one of these lines:++.. list-table::+ :header-rows: 1+ :widths: 50 50++ * - Message+ - Cause and action+ * - ``tpm: not usable; shirudo requires a TPM 2.0 (tpm_error)``+ - No usable TPM answered on ``/dev/tpmrm0``. Check the TPM driver in the+ initrd and the firmware's TPM setting.+ * - ``tpm: register 0x01818E00 cannot be bound (tpm_error); ...``+ - The TPM refused the authorization, usually because the owner+ hierarchy has a password that shirudo does not have. Set+ ``tpm.owner_auth`` in both bootstrap files as+ :doc:`/operate/boot-integration` describes. The environment+ variable that the message names is refused on a target.+ * - ``tpm: register extend failed -- chain NOT advanced while LSM+ active (tpm_error); operator must reconcile``+ - The register could not be defined or extended. Read the journal+ for the TPM error before it.+ * - ``tpm: the register this boot recorded is gone or replaced;+ refusing to bind another before the next TPM reset (tampered)``+ - Something removed or replaced the register after init bound it+ this boot. Handle it as an incident:+ :doc:`/operate/incident-tampered`.++The threat model lists the boot paths that leave a target unprotected and+what detects them: :doc:`/security/threat-model`.++Next steps+----------++- :doc:`/operate/read-status` for every section and verdict of the+ status report.+- :doc:`/operate/troubleshooting` for refusals after init.+- :doc:`/operate/attest` to prove the boot to a remote verifier.diff --git a/Documentation/operate/interoperability.rst b/Documentation/operate/interoperability.rstnew file mode 100644index 00000000..c0b7d718--- /dev/null+++ b/Documentation/operate/interoperability.rst@@ -0,0 +1,472 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Interoperability+================++On a target where shirudo enforces, its LSM programs refuse operations+that other software on the host may rely on. This page lists them by+area. Each entry names the mechanism, what the other software sees, the+tamper counter that moves, and what to do. The refusals start when+``init`` attaches the guards in the initrd and last until the next boot.+:doc:`/internals/enforcement` describes every hook, and+:doc:`/security/tamper-counters` every counter.++``lsm/bpf`` runs before the kernel checks capabilities, so unprivileged+processes move counters too. Software that probes for BPF support at+startup, systemd among it, moves several counters on every target, which+is why+:doc:`/operate/read-status` asks you to learn the baseline of your hosts.++Other BPF users+---------------++:Mechanism: After ``init``, a program load from userspace passes+ ``lsm/bpf`` only as a ``BPF_PROG_TYPE_SYSCALL`` loader with a+ signature, and ``lsm/bpf_prog_load`` only when the kernel verified+ that signature against the ``.bpf`` keyring ``init`` froze. Map+ creation, map writes, test runs, attaching and pinning are reserved to+ tasks with runtime authority, which only an exec of a file on the+ runtime image grants. ``lsm/bpf_map`` refuses every map descriptor to+ other tasks. Every ``bpf()`` command that shirudo has not classified+ is refused.+:Still allowed: ``BPF_PROG_GET_FD_BY_ID``, ``BPF_BTF_GET_FD_BY_ID``,+ ``BPF_OBJ_GET_INFO_BY_FD``, the ``*_GET_NEXT_ID`` commands,+ ``BPF_PROG_QUERY``, ``BPF_TASK_FD_QUERY``, and lookups through a map+ descriptor a process already holds. Classic BPF, as seccomp filters+ and ``SO_ATTACH_FILTER`` in libpcap use it, does not go through+ ``bpf()`` and is not affected.+:What to do: Plan a target as a host where only signed upatches run BPF.+ Keep BPF-based agents, network plugins and tracing tools off+ enforcing targets, or ship what they do as upatches+ (:doc:`/upatches/index`). Run one-off investigations with bcc or+ bpftrace on a host that does not enforce.++Each refused call fails with ``EACCES`` (``Permission denied``). The+program load rows apply to every task, the others to tasks without+runtime authority:++.. list-table::+ :header-rows: 1+ :widths: 58 42++ * - Call+ - Counter+ * - ``BPF_PROG_LOAD`` of any type other than ``BPF_PROG_TYPE_SYSCALL``+ - ``LoadNotLoader``+ * - ``BPF_PROG_LOAD`` of a ``BPF_PROG_TYPE_SYSCALL`` program without a+ signature+ - ``LoadUnsigned``+ * - ``BPF_PROG_LOAD`` of a loader whose signature the kernel did not+ verify against the ``.bpf`` keyring ``init`` froze, for example+ one signed by a key the target does not trust+ - ``LoadUnverified``, ``LoadKeyringKind`` or ``LoadKeyring``+ * - ``BPF_MAP_CREATE``+ - ``MapCreate``+ * - ``BPF_MAP_UPDATE_ELEM``, ``BPF_MAP_FREEZE``+ - ``MapWrite``+ * - A writable map descriptor+ - ``MapFdWrite``+ * - ``BPF_OBJ_GET``, ``BPF_MAP_GET_FD_BY_ID``,+ ``BPF_LINK_GET_FD_BY_ID``, a read-only map descriptor, opening a+ pin in shirudo's private bpffs+ - ``ObjGet``+ * - ``BPF_LINK_CREATE``, ``BPF_RAW_TRACEPOINT_OPEN``+ - ``ProgAttach``+ * - ``BPF_OBJ_PIN``+ - ``ObjPin``+ * - ``BPF_PROG_TEST_RUN``+ - ``ProgRun``+ * - The ``PERF_EVENT_IOC_SET_BPF`` ioctl+ - ``PerfAttach``+ * - Every other command, among them ``BPF_TOKEN_CREATE``,+ ``BPF_BTF_LOAD``, ``BPF_LINK_DETACH``, ``BPF_LINK_UPDATE``,+ ``BPF_PROG_ATTACH``, ``BPF_PROG_DETACH``, ``BPF_ITER_CREATE`` and+ ``BPF_MAP_DELETE_ELEM``+ - ``BpfCommand``++What common software sees:++.. list-table::+ :header-rows: 1+ :widths: 24 76++ * - Software+ - Effect+ * - Loaders built on libbpf+ - A recent libbpf first tries to create a BPF token from+ ``/sys/fs/bpf`` (``BpfCommand``), then loads a trivial program to+ see whether loading works (``LoadNotLoader``). The load fails and+ libbpf logs ``Couldn't load trivial BPF program``.+ * - ``bpftool``+ - ``prog show``, ``prog dump``, ``cgroup`` and ``perf`` work,+ because programs and queries stay readable. ``map show``,+ ``link show`` and ``btf show`` stop at the first map or link with+ ``Error: can't get map by id (<id>): Permission denied`` or the+ same for a link. ``net show`` prints that error for every link+ and goes on. Each refused id moves ``ObjGet``. The column of+ owning processes needs an iterator program, whose refusal+ ``bpftool`` does not print but the counters record. ``--bpffs``+ tries every pin in every bpffs mount, and each pin of shirudo's+ moves ``ObjGet``.+ * - ``perf``+ - Counting and sampling without BPF work. Options that load BPF+ programs, such as ``perf stat --bpf-counters``, ``perf record+ --off-cpu`` and ``perf lock contention --use-bpf``, fail. Events+ bound to a shirudo task are refused, see `Debuggers, tracing and+ /proc`_.+ * - bcc, bpftrace+ - Fail at their first map creation or program load. Nothing they+ compile runs.+ * - Cilium and other BPF datapaths+ - The agent cannot create its maps or load its programs, so the+ datapath does not come up.+ * - Tetragon, Falco's eBPF drivers+ - Cannot load their programs. Falco's kernel module driver is a+ kernel module, which shirudo does not gate, see `Module loading+ and kernel live patching`_.+ * - XDP and tc programs from ``ip`` and ``tc``, sched_ext schedulers,+ HID-BPF+ - The program load is refused.+ * - systemd+ - Starts units without its BPF-based settings, see the next section.++systemd's BPF-based settings+----------------------------++:Mechanism: systemd probes whether BPF works when a manager starts: the+ system manager at boot and at every re-execution, including the switch+ from the initrd to the root file system, and every user manager. The+ probes load programs, which ``init`` has already closed off. systemd+ then treats the features as unsupported for the lifetime of that+ manager and starts units without them. This section describes+ systemd 262.+:Symptom: The units start. Their BPF-based restrictions do not hold.+ Each refused probe moves a counter: ``LoadNotLoader`` for the program+ loads, ``MapCreate`` for the map ``RestrictFileSystems=`` creates, and+ ``BpfCommand`` for other commands, such as libbpf's token attempt.+:What to do: Do not rely on these settings on a target. Enforce address+ and interface policy with nftables, or with a signed upatch of the+ ``cgroup_skb`` or ``netfilter`` attach kind+ (:doc:`/upatches/attach-kinds`). No upatch attach kind covers cgroup+ device programs.++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Setting+ - On an enforcing target+ * - ``IPAddressAllow=``, ``IPAddressDeny=``, ``IPAccounting=``,+ ``IPIngressFilterPath=``, ``IPEgressFilterPath=``+ - Not applied. For the first unit that uses them, the manager logs+ ``unit configures an IP firewall, but the local system does not+ support BPF/cgroup firewalling.``+ * - ``DeviceAllow=``, ``DevicePolicy=``+ - Not applied. On cgroup v2 the device controller exists only as a+ ``BPF_PROG_TYPE_CGROUP_DEVICE`` program.+ * - ``BPFProgram=``+ - Not applied.+ * - ``SocketBindAllow=``, ``SocketBindDeny=``,+ ``RestrictNetworkInterfaces=``, ``BindNetworkInterface=``+ - Not applied. The manager logs the failed probe at debug level+ only.+ * - ``RestrictFileSystems=``+ - Not applied. At startup the system manager logs+ ``bpf-restrict-fs: Failed to create BPF map: Permission denied``.++Seccomp filters and shirudo's own commands+------------------------------------------++:Mechanism: The seal grants runtime authority at an exec of a file on+ the runtime image only when the task is not traced and has no seccomp+ filter, so that neither a debugger nor a filter installed beforehand+ controls the new process. ``lsm.s/bprm_check_security`` refuses such+ an exec. A seccomp filter passes to every child and survives exec.+:Symptom: Running the runtime ``shirudo`` fails with ``EACCES``+ (``Permission denied``). No counter moves.+:Affected: systemd unit settings that install a seccomp filter, among+ them ``SystemCallFilter=``, ``SystemCallArchitectures=``,+ ``SystemCallLog=``, ``RestrictAddressFamilies=``,+ ``RestrictNamespaces=``, ``RestrictRealtime=``,+ ``RestrictSUIDSGID=``, ``LockPersonality=``,+ ``MemoryDenyWriteExecute=``, ``PrivateDevices=``, ``ProtectClock=``,+ ``ProtectHostname=yes``, ``ProtectKernelTunables=``,+ ``ProtectKernelModules=`` and ``ProtectKernelLogs=``, on a unit that+ runs shirudo or on any unit whose processes start it. A container with+ a seccomp profile. systemd's ``RestrictFileSystemAccess=``: with it+ enabled, systemd 262 installs a seccomp filter in PID 1, which every+ later process on the host inherits, so no runtime command can run at+ all. This last case is a reading of the systemd 262 source and is not+ tested.+:What to do: Add none of these settings to shirudo's units or to their+ drop-ins (:doc:`/reference/systemd-units`). Do not enable+ ``RestrictFileSystemAccess=`` on a target. Run shirudo commands from a+ root shell or a unit without a seccomp filter.++BPF loaded before init+----------------------++:Mechanism: Before ``init`` attaches ``lsm/bpf`` in the initrd, any+ process can load and attach BPF, and what it attaches stays (R7 in+ :doc:`/security/threat-model`). It stays as long as something holds+ it: a pin, an open descriptor, or an attachment that needs neither,+ such as ``BPF_PROG_ATTACH`` to a cgroup. In-kernel loaders, such as+ the ``bpf_preload`` module, pass the gates at any time (R18).+:Symptom: After ``init``, the owner of such a program can no longer+ detach it with ``bpf()`` (``BpfCommand``), write or delete map+ elements (``MapWrite``, ``BpfCommand``), or reopen its maps and links+ by pin or by id (``ObjGet``). It can still look up elements through a+ map descriptor it holds, close descriptors, and remove its pins from+ any bpffs other than shirudo's, which releases the object when nothing+ else holds it. systemd's manager re-executes at the switch to the root+ file system and sets up its BPF features again after ``init``, so the+ previous section applies to them.+:What to do: Keep the initrd free of BPF loaders you do not trust. The+ initrd is part of the trusted computing base, and its PCR 9 and+ PCR 11 measurements are what a verifier pins (:doc:`/operate/attest`).++systemd-keyring-setup+---------------------++:Mechanism: systemd 263 adds ``systemd-keyring-setup``. It runs in the+ initrd before ``shirudo-initrd.service`` and again on the root file+ system, enrolls certificates of its own, and seals ``.bpf``,+ ``.dm-verity`` and ``.fs-verity`` with a chain restriction, also when+ it has no certificate to enroll. ``init`` enrolls the config+ certificate and the BPF signers itself and seals both keyrings against+ every further key. It refuses a keyring that another task sealed or+ filled first, and shirudo does not adopt the keyrings that tool set+ up.+:Symptom: ``init`` fails in the initrd. It stops at the ``.dm-verity``+ keyring with one of+ ``initrd boot keys: add config verification certificate: <error>``,+ ``initrd boot keys: check dm-verity keyring holds only the config+ certificate: Key was rejected by service`` or, when the tool enrolled+ nothing, ``initrd boot keys: dm-verity keyring sealed empty at boot;+ boot with dm_verity.keyring_unsealed=1: Required key not available``,+ which names the boot parameter even when it is set. ``init: BPF+ keyring initialization failed`` follows. The boot then continues+ without enforcement (U11). If ``init`` ran first, the tool's run on+ the root file system is refused by ``lsm/key_permission`` and moves+ ``KeyringWrite``.+:What to do: Keep ``systemd-keyring-setup`` off targets: do not install+ it in the initrd or on the root file system, or mask its unit in both.++kexec and kdump+---------------++:Mechanism: ``lsm/kernel_load_data`` and ``lsm/kernel_read_file`` refuse+ every kexec image and kexec initramfs to every task, shirudo included,+ through ``kexec_load(2)`` and ``kexec_file_load(2)`` alike. A crash+ kernel goes through the same checks. A kexec would boot a kernel of+ the caller's choosing while the TPM keeps this boot's register and+ PCRs.+:Symptom: The load fails with ``EPERM`` (``Operation not permitted``)+ and moves ``Kexec``. The kdump service cannot load its crash kernel,+ and ``systemctl kexec`` fails.+:What to do: Plan targets without kdump. Use crash capture that needs no+ second kernel, such as pstore, which shirudo does not hook. Reboot+ through the firmware instead of kexec.++Module loading and kernel live patching+---------------------------------------++:Mechanism: shirudo does not gate module loading.+ ``lsm/kernel_load_data`` and ``lsm/kernel_read_file`` let every load+ other than a kexec image or initramfs through. Whether a module loads+ is the kernel's decision: module signature enforcement and lockdown+ (A4 in :doc:`/security/threat-model`). A livepatch module, as kpatch+ or the kernel's ``klp-build`` produce, is a kernel module like any+ other.+:Symptom: None from shirudo.+:What to do: Enforce module signatures, as :doc:`/operate/hardening`+ lists, and sign livepatch modules with a key the kernel trusts. A+ module runs as kernel code outside every shirudo check. Unloading a+ module that a kprobe upatch targets leaves the upatch loaded and+ measured but without effect, a reading of the kernel source (R21).+ shirudo's tests do not cover a livepatch and an upatch on the same+ function.++Other LSMs+----------++:Mechanism: The kernel calls the active LSMs in the order of ``lsm=``,+ or ``CONFIG_LSM`` without it, and stops at the first refusal+ (:doc:`/concepts/background/bpf-lsm`). shirudo's programs pass an+ earlier refusal on unchanged. The pre-flight check ``bpf_lsm_active``+ checks that ``bpf`` is in the list, not where.+:Order: Either order refuses what any active LSM refuses. The order+ decides who sees the attempt. With ``bpf`` after SELinux, AppArmor,+ Smack or Landlock, an operation one of them refuses never reaches+ shirudo's programs and moves no counter. With ``bpf`` before them,+ shirudo's refusal ends the walk and the other LSM does not see or log+ the attempt.+:Seal labels: The seal reads a file's label through a kfunc that checks+ the caller's read permission, and every LSM that implements the+ ``inode_permission`` hook takes part. In the kernel tree, SELinux and+ Smack implement it; AppArmor, Landlock and Yama do not. A policy that+ grants write or unlink but refuses read makes a sealed file look+ unlabeled, and the operation goes through without a counter (U12 in+ :doc:`/security/threat-model`).+:Policies: shirudo ships no SELinux, AppArmor or Smack policy. A policy+ that confines shirudo's processes must allow what they use, among it+ ``bpf()``, mounts under ``/run/shirudo``, loop and device-mapper+ devices, the ``.bpf`` and ``.dm-verity`` keyrings, the TPM device and+ the ``security.bpf.shirudo`` extended attributes.+:What to do: Run no other LSM whose policy root can change at runtime.+ Choose the order by which LSM you want to account for refusals.++Hibernation and suspend+-----------------------++:Mechanism: shirudo does not refuse hibernation. Lockdown in integrity+ mode disables it (A9 in :doc:`/security/threat-model`), and the+ behavior of the register across hibernation is not analyzed. Before a+ suspend, the kernel's TPM driver sends ``TPM2_Shutdown(STATE)`` to a+ TPM 2.0 unless the TPM stays powered, and the TPM counts that in its+ restart count (:doc:`/concepts/background/tpm`). The config activation+ record holds the TPM's reset and restart counts, and shirudo compares+ them with the TPM's before a command runs.+:Symptom: After a resume, shirudo commands refuse with ``shirudo: image+ state: Stale file handle`` and exit 1, and ``shirudo status`` reports+ ``tampered``.+ :doc:`/operate/backup-recovery` describes the state. For suspend to+ RAM this is a reading of the code and of the TPM's counters and is not+ tested.+:What to do: Turn hibernation off as :doc:`/operate/hardening` lists, and+ keep targets from sleeping, for example with ``AllowSuspend=no`` and+ ``AllowHibernation=no`` in ``/etc/systemd/sleep.conf``. After an+ unplanned resume, follow :doc:`/operate/backup-recovery`.++Containers and Kubernetes+-------------------------++:BPF: The gates apply in every namespace. ``BPF_TOKEN_CREATE`` is refused+ (``BpfCommand``), so a bpffs mounted with ``delegate_cmds=`` and its+ kin gives a container nothing. A container may mount a bpffs of its+ own, but nothing can be pinned there (``ObjPin``).+:Device rules: On cgroup v2, container runtimes and systemd enforce+ device access with ``BPF_PROG_TYPE_CGROUP_DEVICE`` programs, and their+ loads are refused (``LoadNotLoader``). How a runtime reacts is up to+ the runtime: test yours on an enforcing target.+:Networking: A network plugin built on BPF cannot run. Use one that does+ not need BPF.+:Mounts: The ``/run/shirudo`` tmpfs, the private bpffs and the runtime+ and config image mounts, and their copies in every other mount+ namespace, cannot be unmounted or remounted one by one, and no task+ without runtime authority mounts over them. The calls fail with+ ``EPERM``, which ``umount(8)`` reports as ``must be superuser to+ unmount``. They move ``BpffsUmount`` or ``BpffsMount`` for the bpffs+ and no counter for the others. An unmount of a mount above them in+ another namespace is refused only when it propagates into the bpffs+ mount of ``init``'s namespace or a mount above it+ (``BpffsUmountAbove``). Tearing a namespace down is not affected. R3+ in :doc:`/security/threat-model` lists the mount operations the guards+ do not see.+:Pins: Directories of the private bpffs stay listable. Opening a pin is+ refused (``ObjGet``).+:What to do: Run shirudo commands on the host, not in a container.+ Inside a container with a seccomp profile they cannot run at all, see+ `Seccomp filters and shirudo's own commands`_.++Debuggers, tracing and /proc+----------------------------++:Mechanism: The seal marks a task at its exec of a runtime file, and a+ fork inherits the mark. ``lsm/ptrace_access_check`` refuses every+ ptrace access check against a marked task, both attach and read+ modes, and ``lsm/perf_event_alloc`` refuses a perf event bound to one.+ An exec of a runtime file by a traced task is refused. The ptrace+ check runs after the kernel's own user and capability checks, so only+ root, or a caller running as the same user, reaches it.+:Symptom: See the table below.+:What to do: Debug shirudo where it does not enforce, such as the test+ VM (:doc:`/contribute/testing`). Expect ``SealPtrace`` in the+ baseline of a host that runs process monitors as root.++.. list-table::+ :header-rows: 1+ :widths: 46 30 24++ * - Action+ - Result+ - Counter+ * - ``gdb --pid``, ``strace --attach`` on a running shirudo command+ - ``EACCES``+ - ``SealPtrace``+ * - Starting shirudo under ``strace`` or ``gdb``+ - The exec fails with ``EACCES``+ - ``ExecTraced``+ * - Reading ``/proc/<pid>/exe``, ``environ``, ``maps``, ``mem`` or+ the ``fd`` links of a shirudo command+ - ``EACCES``+ - ``SealPtrace``+ * - Reading ``/proc/<pid>/stat`` of a shirudo command, as ``ps`` and+ ``top`` do+ - Succeeds, with the fields that need the check zeroed+ - ``SealPtrace``+ * - journald receiving a log line from a shirudo command+ - journald cannot read ``/proc/<pid>/exe``, so the entry has no+ ``_EXE=`` field+ - ``SealPtrace``+ * - ``perf record --pid``, ``perf stat --pid`` on a shirudo command+ - ``EACCES``+ - ``SealPerf``+ * - System-wide ``perf``, tracefs and kprobe events+ - Not refused+ - none++A task-bound perf event that a process opened before the exec that marks+the task is not refused (D9 in :doc:`/security/threat-model`).++TPM tools+---------++:Mechanism: ``lsm/tpm_command`` sees every command written to+ ``/dev/tpm0`` and ``/dev/tpmrm0``. It refuses ``TPM2_NV_Extend`` of+ shirudo's register, NV index ``0x01818E00``, to every task without+ runtime authority. shirudo itself reaches the TPM through+ ``device:/dev/tpmrm0`` by default, the kernel's resource manager, and+ on a target refuses a TCTI that is not a ``device:`` one, which rules+ out a userspace resource manager such as ``tpm2-abrmd``.+:Symptom: ``tpm2_nvextend`` of that index fails: the write to the device+ returns ``EACCES`` and ``TpmExtend`` moves. Every other command works:+ reading PCRs and NV indices, quotes, keys, other NV indices.+:Not refused: Extending PCRs, which a verifier then sees in PCR 9 or the+ config PCR (R4, R11), and undefining the register with the owner+ password, after which measuring commands refuse until the next TPM+ reset (R20).+:What to do: Keep other software from measuring into PCR 9, PCR 11 and+ the config PCR, and keep the owner password from tools that do not+ need it.++Keyrings and keyctl+-------------------++:Mechanism: ``lsm/key_permission`` guards the ``.bpf`` and+ ``.dm-verity`` keyrings and the keys in them. It refuses write,+ set-attribute and unlink to every task without runtime authority, and+ a search through a reference the caller does not possess, which is+ how ``keyctl`` reaches a key by its serial. The kernel's own search+ during signature verification stays open.+:Symptom: ``keyctl add``, ``link``, ``unlink``, ``clear``, ``revoke``,+ ``invalidate``, ``setperm``, ``chown`` and ``restrict_keyring`` on+ these keyrings or their keys fail with ``EACCES`` and move+ ``KeyringWrite``. shirudo does not refuse reading them, as ``keyctl+ show``, ``list``, ``describe`` and ``read`` do.+:What to do: Keep tools that manage these keyrings off targets. They+ conflict with ``init`` as `systemd-keyring-setup`_ does.++Related+-------++- :doc:`/security/threat-model`+- :doc:`/security/tamper-counters`+- :doc:`/operate/hardening`+- :doc:`/operate/read-status`+- :doc:`/operate/troubleshooting`diff --git a/Documentation/operate/keys.rst b/Documentation/operate/keys.rstnew file mode 100644index 00000000..9cc5250e--- /dev/null+++ b/Documentation/operate/keys.rst@@ -0,0 +1,381 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Manage signing keys+===================++A target trusts a small set of keys, and each one enters at a different+time. Some are fixed when the target is first provisioned, some change+with a signed config, and some change only with a new runtime image and a+reboot. This page lists the keys, shows what can change when, and walks+through vouching for a signer and revoking one.++Plan the BPF signers before the first boot. A target that is already+initialized cannot enroll a BPF signer that its first config did not+enroll.++Before you begin+----------------++- The operator host with the operator package, and the key directories+ you created with ``shirudo genkey``. Each holds ``signing_key.pem``+ (mode ``0600``, the signing helper refuses any other mode) and+ ``cert.der``.+- The source tree of the config image the target runs, as built in+ :doc:`/operate/boot-integration`.+- Root on the target. On the target, ``shirudo`` is the runtime image's+ binary, as :ref:`runtime-invocation` sets up.++Key inventory+-------------++.. list-table::+ :header-rows: 1+ :widths: 22 28 50++ * - Key+ - Where the target takes it from+ - What it authorizes+ * - Runtime primary BPF certificate+ - ``keys/cert.der`` in the runtime image, read as+ ``/run/shirudo/runtime/keys/cert.der``+ - Signed loaders of upatches. It is also the only certificate that+ verifies upatch tree publications, whatever the config revokes or+ vouches for.+ * - Vouched BPF certificates+ - ``keys/trusted/<name>.der`` with ``keys/trusted/<name>.vouch`` in+ the config image+ - Signed loaders of upatches. A certificate joins the set when its+ vouch verifies under a certificate already in the set, starting+ from the runtime primary. The set holds at most 16 certificates.+ * - Revocation records+ - ``keys/revoked/<fingerprint>.der`` in the config image+ - Nothing. Each record removes the certificate it holds from the+ set.+ * - Config verification certificate+ - ``etc/shirudo/config-cert.der`` in the runtime image, named by+ ``config.verification_key``+ - Config images. Init enrolls it in the kernel's ``.dm-verity``+ keyring and seals that keyring around it.+ * - Kernel trusted keys+ - The kernel's built-in trusted keyring, and the secondary and+ platform keyrings when the kernel enables them for dm-verity+ - Config images as well. The kernel checks these keyrings before+ ``.dm-verity``, so their keys, including the kernel build's module+ signing key, can sign a config the target activates.+ :doc:`/operate/hardening` lists the kernel options.+ * - Repository index certificates+ - ``etc/shirudo/bpm/keys/`` in the config image, named by+ ``key_file`` in ``etc/shirudo/bpm/registries.d/``+ - The package index of that repository. shirudo does not require+ ML-DSA-87 for them.+ * - Attestation key (AK) and endorsement key (EK)+ - The TPM. Both are primaries under the endorsement hierarchy with+ fixed templates, so one TPM always yields the same keys.+ - The AK signs the evidence. The EK proves at enrollment that the AK+ sits in the same TPM. You record both names when you enroll the+ target, as :doc:`/operate/attest` describes.+ * - NV writer key+ - The TPM. Init creates an RSA-3072 key from a random seed at every+ boot and freezes its public key in the kernel.+ - Extensions of the measurement register. The init record carries+ its public key as ``nv_writer_public``.++The BPF signing keys and the config signing key are ML-DSA-87 keys from+``shirudo genkey``. The config signing key may be one of the BPF signing+keys or a separate key. Keep the private signing keys on the operator+host. A target needs none, and ``shirudo status`` on a target reports+``keys/signing_key.pem absent``.++What can change when+--------------------++.. list-table::+ :header-rows: 1+ :widths: 22 22 26 30++ * - Key+ - First provisioning+ - Signed config (``image update``)+ - New runtime image, UKI and reboot+ * - Runtime primary BPF certificate+ - Set by the runtime image.+ - Cannot change it. The config can revoke it.+ - Changes it. Every certificate in the selected config's+ ``keys/trusted`` must chain from the new primary, or init fails+ before enforcement starts. Every archived upatch must be signed+ by a key in the new set, or the boot restore fails.+ * - Vouched BPF certificates+ - Enrolled from the initial config.+ - Refused when the config adds a certificate that is not in the+ ``.bpf`` keyring.+ - Not enrolled. The boot selects the config the activation record+ names, and that config passed the live check.+ * - Revocation records+ - Applied at boot.+ - Applied at activation.+ - Kept, as part of the selected config.+ * - Config verification certificate+ - Set by the runtime image.+ - Cannot change it.+ - Init fails at that boot, before enforcement starts: the selected+ config carries the old key's signature, and the sealed+ ``.dm-verity`` keyring holds only the new certificate.+ * - Repository index certificates+ - From the initial config.+ - Change at activation.+ - Kept, as part of the selected config.+ * - AK and EK+ - Fixed by the TPM.+ - No change.+ - No change. A different TPM needs a new enrollment.+ * - NV writer key+ - Created at boot.+ - No change.+ - A new key at every boot.++The first provisioning is the first boot with enforcement. Init has no+activation record yet and selects the config that ``config.image`` in the+runtime bootstrap file names. From then on the activation record selects+the config, and changing ``config.image`` has no effect.++Check what a target trusts+--------------------------++1. Show the certificates, the trusted set and the ``.bpf`` keyring:++ .. code-block:: console++ target# shirudo keys+ Cert (/run/shirudo/runtime/keys/cert.der):+ Subject: /CN=shirudo+ Issuer: /CN=shirudo (self-signed)+ Public-key: ML-DSA-87+ Fingerprint: SHA256:d95db97ff4658b96b8b538afef41a25ca9f7a2c4d0abffdb26cbac7b0ba294b9+ SPKI fingerprint: SHA256:d1dc6624ee6bd0c277864fab0a8a15f8509308aa2338768cb772117c157f8d61+ Valid from: 2026-10-29T16:16:30Z+ Valid until: 2036-10-26T16:16:30Z+ Expires in: 9y 364d++ Signing key (/run/shirudo/runtime/keys/signing_key.pem):+ Present: no (target host -- private key lives on the operator)++ Trusted set (2 members, 0 revoked, 0 unvouched):+ 2edb279c05efee6b489a65ae07fd6d402a54b6e495be68f6d364544e9b5a37e2+ sha256 3702e8ffe817ade6151eea338194649cc3a5be1e0b940e462a1a75e52f7095d0+ vouched by d1dc6624ee6bd0c277864fab0a8a15f8509308aa2338768cb772117c157f8d61+ d1dc6624ee6bd0c277864fab0a8a15f8509308aa2338768cb772117c157f8d61 (primary)+ sha256 d95db97ff4658b96b8b538afef41a25ca9f7a2c4d0abffdb26cbac7b0ba294b9++ Keyring (.bpf):+ Serial: 420195959+ Frozen serial: 420195959 (matches)+ Members (2):+ serial=410418068 type=asymmetric shirudo: d10a391a9f1067ed9f64e4ea9b738cf9258b478a+ serial=746517937 type=asymmetric shirudo: 6935ce2048ec5a5ed607db8f5ac1c005c29f32a4++ ``Cert`` is the runtime primary. The trusted set lists each member by+ its SPKI fingerprint, with the SHA-256 of its DER and the member that+ vouched for it. ``Keyring (.bpf)`` is what the kernel verifies signed+ loaders against: the serial init froze, and one key per+ member.++2. Read the same counts from the status report:++ .. code-block:: console++ target# shirudo status+ ...+ Keyring (.bpf):+ Serial: 420195959+ Frozen serial: 420195959 (matches)+ Certificates: 2 trusted, 0 revoked, 0 unvouched, 2 in the bpf keyring+ ...++ ``unvouched`` counts certificates under ``keys/trusted`` without a+ valid vouch. A config with one is refused, so it stays 0 on a target+ that runs a config.++Vouch for a standby signer+--------------------------++A standby signer is a second BPF signing key that the initial config+enrolls, so that you can revoke the primary later and keep signing+upatches. Tree publications stay with the runtime primary, as `Limits`_+explains. Do this before the target's first boot with enforcement.++1. Create the standby key in a directory of its own:++ .. code-block:: console++ operator$ shirudo genkey --keys-dir=<standby-keys-dir>++2. Sign a vouch for its certificate with the primary key:++ .. code-block:: console++ operator$ shirudo keys vouch <standby-keys-dir>/cert.der \+ -o standby.vouch --keys-dir=<primary-keys-dir>++ The command prints the fingerprint of the certificate it vouched for.+ It refuses to vouch for the signing key's own certificate.++3. Put the certificate and the vouch into the config source tree under+ one name:++ .. code-block:: console++ operator$ mkdir -p config-root/keys/trusted+ operator$ cp <standby-keys-dir>/cert.der \+ config-root/keys/trusted/<standby-fingerprint>.der+ operator$ cp standby.vouch \+ config-root/keys/trusted/<standby-fingerprint>.vouch++ ``<standby-fingerprint>`` is the fingerprint that step 2 printed. Init+ pairs ``<name>.der`` with ``<name>.vouch`` by name. It refuses the whole+ config when a certificate under ``keys/trusted`` has no vouch that+ verifies.++4. Build, sign and place the initial config as+ :doc:`/operate/boot-integration` describes.++5. After the first boot, check that ``shirudo keys`` on the target lists+ the standby signer in the trusted set and the ``.bpf`` keyring.++On a target, ``shirudo keys add`` and ``shirudo bpm key add`` refuse to+change the trusted set, and ``shirudo keys revoke`` always refuses. The+signed config is the only way in.++Revoke a signer+---------------++Revocation goes through a signed config. Activation removes the key+from the kernel at once.++1. Print the fingerprint of the certificate to revoke:++ .. code-block:: console++ operator$ shirudo bpm key fingerprint <revoked-cert.der>++ The command prints the 64-character SPKI fingerprint, the same value+ that ``shirudo keys`` prints.++2. Add a revocation record to the config source tree:++ .. code-block:: console++ operator$ mkdir -p config-root/keys/revoked+ operator$ cp <revoked-cert.der> config-root/keys/revoked/<fingerprint>.der++ The file name must be the lowercase fingerprint with ``.der``, and the+ file must hold that certificate. Init and ``image update`` refuse any+ other entry under ``keys/revoked``.++3. Build and sign the config under a new prefix, and check it offline:++ .. code-block:: console++ operator$ shirudo-gen-image --source config-root --output revoke-1 \+ --keys-dir <config-keys-dir> --kind config+ operator$ shirudo image verify revoke-1 --cert <config-keys-dir>/cert.der++4. Copy ``revoke-1.img``, ``revoke-1.verity``, ``revoke-1.roothash`` and+ ``revoke-1.p7s`` to the target.++5. Activate the config on the target:++ .. code-block:: console++ target# shirudo image update <path>/revoke-1++ ``<path>`` is where you copied the files. ``image update`` also takes+ an ``https://`` prefix. It prints nothing on success.++6. Check the result:++ .. code-block:: console++ target# shirudo keys+ target# shirudo status --include-eventlog++ The trusted set no longer lists the key, the revoked count went up, and+ the eventlog shows a ``key_revoke`` record followed by an+ ``upatch_unload`` record for each loaded upatch the key signed.++Leaving a certificate out of a config does not revoke it: its key stays+in the ``.bpf`` keyring until the next boot. Revoke it with a record.++``image update`` validates the whole config before it measures anything.+It refuses a config whose set would be empty after the revocation, a+certificate under ``keys/trusted`` without a valid vouch, and a member+that is not in the ``.bpf`` keyring. A refused config changes nothing.++What a revocation does+~~~~~~~~~~~~~~~~~~~~~~++At activation, in this order:++1. shirudo records an ``UPDATE`` event for the config in the config PCR.+2. When the revoked key is in the ``.bpf`` keyring, shirudo unlinks it,+ extends the measurement register with a ``key_revoke`` event and+ appends the record to the eventlog.+3. For every archived upatch the revoked key signed, shirudo unloads it+ when it is loaded, with a measured ``upatch_unload`` event whose+ reason is ``key_revoke``, and removes it from the archive. An archived+ upatch that is not loaded is removed without an event.++At a later boot with the same config, the revocation is not a separate+event. Init enrolls the runtime primary in any case, because the boot+needs it until the config is active, and unlinks it again when the+config revokes it. It removes the archived upatches the revoked keys+signed before it restores the archive. The init event covers the set+after revocation, so ``shirudo attest predict`` takes the remaining+certificates only. :doc:`/operate/attest` shows how to predict the+register, and ``--event=revoke:<label>=<cert-sha256>`` adds a revocation+made after boot.++Limits+------++These limits follow from the code as it is. :doc:`/security/threat-model`+discusses the residual risks.++- A signer that the first config did not enroll cannot be added to an+ initialized target. ``image update`` refuses the config with+ ``image: BPF signer was not enrolled at boot; reboot with the new+ trusted key set required``, and a reboot does not select it either. No+ supported procedure resets the activation record. Enroll standby+ signers at first provisioning.+- A config signed by a new config verification key cannot be activated+ on an initialized target. Live activation verifies it under the+ current ``.dm-verity`` keyring, and a new runtime image fails at boot+ as the table above shows.+- Tree publications verify only against the runtime primary+ certificate. Revoking the primary in the config does not stop the+ target from accepting tree publications that the primary signed, and a+ vouched signer cannot sign them. Moving tree publishing to another key+ takes a new runtime image.+- A vouch carries no time. A vouch made by a key that was later revoked+ still admits the certificate it vouches for. The config signer decides+ which certificates are under ``keys/trusted``, so after a compromise,+ revoke the certificates that only the compromised key vouched for as+ well.+- A certificate's validity dates do not end its trust. shirudo verifies+ vouches and index and tree signatures without checking them.+- Any key the kernel trusts for dm-verity signs a valid config. A config+ can change repositories, the tree subscription, export destinations and+ revocations.++Next steps+----------++- :doc:`/operate/attest` to enroll a target and verify evidence.+- :doc:`/operate/deliver-packages` for repositories and their keys.+- :doc:`/reference/cli/keys` and :doc:`/reference/cli/image` for the+ command options.+- :doc:`/security/cryptography` for the algorithms.diff --git a/Documentation/operate/read-status.rst b/Documentation/operate/read-status.rstnew file mode 100644index 00000000..2a1edc75--- /dev/null+++ b/Documentation/operate/read-status.rst@@ -0,0 +1,667 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators, SecOps++Read shirudo status+===================++``shirudo status`` is the target's own report on its enforcement, its+``.bpf`` keyring, its measurement register and its signed config. It is+the first command to run on a target that misbehaves, and the keepalive+timer sends the same data to your collector. It is the target's account+of itself: anyone with root on the target can lie to a reader of this+report, so it proves nothing to a third party. TPM-signed evidence does,+see :doc:`/operate/attest`.++This page walks through a healthy report section by section, then+explains every verdict and what to do about it.++Before you begin+----------------++- You need root on the target.+- On the target, ``shirudo`` means the binary on the runtime image,+ ``/run/shirudo/runtime/usr/bin/shirudo``. Any other copy is refused.+ :ref:`runtime-invocation` shows how to set this up.++Print the report+----------------++1. Print the human report:++ .. code-block:: console++ target# shirudo status++2. To add this boot's eventlog to the report, print it with+ ``--include-eventlog``:++ .. code-block:: console++ target# shirudo status --include-eventlog++:doc:`/reference/cli/status` lists the other sections you can add+(``--include-system``, ``--include-kernellog``, ``--include-modules``,+``--show-full``).++Read the report+---------------++This is the report of a healthy production target with one upatch+loaded, captured from the test VM:++.. code-block:: console++ target# shirudo status+ Host: docs+ Roles: target+ Mode: production+ Status: ok+ Version-ID: 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0++ Conditions:+ TYPE STATUS DETAIL+ LsmAttached OK lsm/bpf link present and pinned+ KeyringSealed OK serial=420195959 in the BPF keyring, pin matches+ ChainIntact OK live register == eventlog replay+ TpmMeasured OK NV index 0x01818E00 readable+ ConfigActive OK config 12dbf3c75083.. is active++ Tamper attempts (refused this boot):+ LoadNotLoader 27 program load that is not a signed loader+ MapCreate 1 map creation by another executable+ BpfCommand 12 detach, update, delete or unclassified bpf() command+ SealPtrace 7 ptrace of a shirudo task++ Keyring (.bpf):+ Serial: 420195959+ Frozen serial: 420195959 (matches)+ Certificates: 2 trusted, 0 revoked, 0 unvouched, 2 in the bpf keyring+ 2edb279c05efee6b489a65ae07fd6d402a54b6e495be68f6d364544e9b5a37e2+ d1dc6624ee6bd0c277864fab0a8a15f8509308aa2338768cb772117c157f8d61 (primary)++ upatches loaded (1):+ NAME LOCATION MAPS STATUS AGE+ shirudo-test-basic fentry/do_nanosleep 0 success 1s++ TPM Measurement:+ TPM: reachable (device:/dev/tpmrm0)+ NV index: 0x01818E00 (anchored in PCR 9)+ Chain: c50b22ac27c5bb6a90ee5ff9b440fbbd5bb60b84a2aa7b395daec3f330886fcd+ Register name: 000be3a552e2219550d2597ab96f3fffdeec0d01ce27cde858e0858ab0cdaba6c045+ Anchored: yes (name on record)+ PCR before init: 0000000000000000000000000000000000000000000000000000000000000000+ Phase at init: 0000000000000000000000000000000000000000000000000000000000000000 (PCR 11)+ Bound in: initrd+ Chain vs eventlog: matches+ Eventlog: /var/lib/shirudo/eventlog (2 entries, 2324 bytes)++ Assets (/var/lib/shirudo):+ keys/cert.der present+ keys/signing_key.pem absent+ eventlog present (2324 bytes)+ upatches/ 1 .upatch+ incoming/ empty+ bpffs/ mounted++The sections below explain each part.++Header+~~~~~~++``Host``+ The host name.++``Roles``+ ``target`` when the primary certificate, the ``lsm/bpf`` pin or the+ keyring is present, ``operator`` when+ ``/var/lib/shirudo/keys/signing_key.pem`` exists, both as+ ``target, operator``, or ``none``. A production target shows+ ``target`` alone. A private signing key on a target breaks the+ operator and target split: remove it and treat the key as exposed,+ see :doc:`/operate/keys`.++``Mode``+ ``production`` when the ``lsm/bpf`` link is pinned in the private+ bpffs, ``inactive`` otherwise. ``Mode`` does not look at the keyring+ or the register. Read the conditions for those.++``Status``+ The verdict, followed by the reason in parentheses when it is not+ ``ok``. :ref:`status-verdicts` explains each verdict.++``Version-ID``+ The identifier of the shirudo build that runs. Compare it with the+ build you deployed, see :doc:`/operate/upgrade`.++Conditions+~~~~~~~~~~++Five conditions, each ``OK``, ``WARN`` or ``ALERT`` with a detail. The+verdict is derived from them.++.. list-table::+ :header-rows: 1+ :widths: 18 82++ * - Condition+ - What it checks, and the details other than ``OK``+ * - ``LsmAttached``+ - The ``lsm/bpf`` link is pinned. ``ALERT`` ``lsm/bpf absent --+ enforcement OFF`` means enforcement did not come up this boot.+ * - ``KeyringSealed``+ - The live ``.bpf`` keyring is the one ``init`` sealed and recorded+ in the frozen identity map. ``WARN`` ``shirudo keyring absent+ (not init'd?)`` before ``init``. ``ALERT`` ``pin serial=<pinned>+ != live serial=<live> (swapped?)`` or ``pin serial=<pinned>, the+ BPF keyring is gone (removed?)`` after it.+ * - ``ChainIntact``+ - The live register is the NV index ``init`` bound this boot, was+ bound once, and equals this boot's eventlog records replayed.+ ``ALERT`` ``live register != eventlog replay (tamper?)``. ``WARN``+ ``no register bound this boot (init incomplete)`` or ``no TPM+ answered, no register to replay``.+ * - ``TpmMeasured``+ - The NV index is defined, written and readable. ``WARN`` ``NV+ index 0x01818E00 not bound this boot`` or ``no TPM answered``.+ * - ``ConfigActive``+ - The config PCR, the activation records and the mounted config+ image agree. ``WARN`` ``the activation of config <root>.. is+ pending until the next reboot``. ``ALERT`` with one of three+ details, see :ref:`status-verdicts`.++Tamper attempts+~~~~~~~~~~~~~~~++The counters of refused attempts this boot, one per guard point, with the+counters that are not zero listed by name, count and meaning. ``none``+means every counter is zero. ``(none recorded: init has not pinned the+counters this boot)`` means ``init`` did not get that far.+:ref:`status-tamper-counters` explains how to read them.++Keyring+~~~~~~~++``Serial``+ The serial of the kernel's ``.bpf`` keyring.++``Frozen serial``+ The serial ``init`` recorded when it sealed the keyring, followed by+ ``(matches)``, ``(MISMATCH -- swapped?)`` or ``(GONE -- removed?)``.++``Certificates``+ The trusted set: the runtime image's primary certificate and the+ vouched certificates of the active signed config, less its+ revocations. ``unvouched`` counts certificates in the config that+ have no valid vouch and are therefore not members. The last number+ counts the keys in the ``.bpf`` keyring itself. Each member's public+ key fingerprint follows, the runtime image's certificate marked+ ``(primary)``. :doc:`/operate/keys` explains the set.++upatches loaded+~~~~~~~~~~~~~~~++One row per upatch pinned in the private bpffs: its name, the attach+location resolved from kernel BTF, its number of maps, ``success`` and+the time since it was loaded. ``upatches loaded (0):`` with no rows+means nothing is loaded.++TPM Measurement+~~~~~~~~~~~~~~~++``TPM``+ Whether a TPM answered, and the TCTI that reached it.++``NV index``+ The measurement register, ``0x01818E00``, and the PCR its name is+ anchored in.++``Chain``+ The register's value. It moves with every measured load, unload,+ revocation and tree operation.++``Register name``+ The TPM name of the NV index, which binds its attributes and policy.++``Anchored``+ ``yes (name on record)`` when the index is the one ``init`` bound and+ recorded. ``NO (index is not the one init bound)`` otherwise.++``PCR before init`` and ``Phase at init``+ The values of PCR 9 and PCR 11 that ``init`` bound the register to.+ A verifier pins them with ``--expect-bind-pcr``, see+ :doc:`/operate/attest`. In the capture above both are zero because+ the test VM boots its kernel and initrd directly, without a measured+ UKI. On a production target booted from a measured UKI, PCR 11 holds+ the ``enter-initrd`` phase measurement. ``init`` warns in the journal+ when it finds PCR 11 unmeasured.++``Bound in``+ ``initrd`` or ``root file system``. A production target shows+ ``initrd``. ``root file system`` means the first ``init`` of this+ boot ran after the initrd.++``Init records``+ Printed only when the register was bound more than once for this TPM+ reset: ``<n> for this TPM reset (REBOUND after init; tamper?)``.++``Chain vs eventlog``+ ``matches``, ``MISMATCH (tamper?)`` or ``n/a`` when there is no+ register to compare.++``Eventlog``+ The path of the eventlog, its number of entries over all boots and+ its size.++Assets+~~~~~~++``keys/cert.der``+ Whether the primary certificate is present. On a production target+ this is the runtime image's ``keys/cert.der``.++``keys/signing_key.pem``+ ``absent`` on every target. ``present`` means a private signing key+ is on the target.++``eventlog``+ Whether ``/var/lib/shirudo/eventlog`` exists, and its size.++``upatches/``+ The number of archived upatches that ``init`` restores at the next+ boot.++``incoming/`` and ``bpffs/``+ The staging directory for loads in progress and whether the private+ bpffs is mounted.++Eventlog+~~~~~~~~++With ``--include-eventlog`` the report adds every record of the+eventlog, of all boots, between the ``TPM Measurement`` and ``Assets``+sections. This target recorded its boot, then one load and one unload:++.. code-block:: console++ target# shirudo status --include-eventlog+ ...+ Eventlog (audit trail):+ TIME TYPE DIGEST DETAIL+ 2026-10-29T16:17:38Z init cb206abf8e51 set_digest=e3b0c44298fc..+ 2026-10-29T16:21:19Z upatch_load d979b373d4e5 shirudo-test-basic payload=8aee7072a1a1..+ 2026-10-29T16:21:20Z upatch_unload 26dae981e9bb shirudo-test-basic payload=8aee7072a1a1..+ ...++The ``init`` record comes from the initrd run. Every later record is a+state change that extended the register. :doc:`/reference/formats/eventlog`+describes the records.++.. _status-verdicts:++Act on the verdict+------------------++``status`` derives one verdict from the conditions, in this order of+precedence: ``tampered``, ``lsm-off``, ``init-pending``,+``reboot-pending``, ``degraded``, ``ok``. The first that applies wins.++.. list-table::+ :header-rows: 1+ :widths: 18 42 40++ * - Verdict+ - Meaning+ - What to do+ * - ``ok``+ - Enforcement is up, the keyring is the sealed one, the register+ replays from the eventlog and the config is active.+ - Nothing. Verify with the TPM regularly, see+ :doc:`/operate/attest`.+ * - ``degraded``+ - Enforcement is up, but this report has no register to check.+ - Read the ``Chain`` line. See :ref:`status-degraded`.+ * - ``reboot-pending``+ - A config activation is pending until the next reboot. Every+ command except ``status`` and ``image status`` refuses until+ then.+ - Reboot when it suits you. See :ref:`status-reboot-pending`.+ * - ``init-pending``+ - The ``lsm/bpf`` link is pinned but no keyring was recorded:+ ``init`` did not finish.+ - Read the journal of ``shirudo-initrd.service``, see+ :doc:`/operate/initialize`.+ * - ``lsm-off``+ - The ``lsm/bpf`` link is not pinned. Enforcement is off and the+ target is unprotected.+ - See :ref:`status-lsm-off`.+ * - ``tampered``+ - The register, the keyring or the config is not what ``init``+ recorded.+ - Handle it as an incident. See :ref:`status-tampered`.++.. _status-tampered:++``tampered``+~~~~~~~~~~~~++A ``tampered`` verdict has one of four reasons. Each shows as an+``ALERT`` condition. The lines below are what ``status`` prints in each+state, cut to the verdict and the condition that raised it. ``<pinned>``,+``<live>`` and ``<root>`` stand for the values of your target.++The register does not replay from the eventlog:++.. code-block:: text++ Status: tampered (live register != eventlog replay)+ ...+ ChainIntact ALERT live register != eventlog replay (tamper?)++Something extended or replaced the register without a matching eventlog+record, the eventlog of this boot was altered or hidden, or the index is+not the one ``init`` bound. The ``TPM Measurement`` section shows which+lines disagree.++The live keyring is not the one ``init`` sealed:++.. code-block:: text++ Status: tampered (keyring serial swap detected)+ ...+ KeyringSealed ALERT pin serial=<pinned> != live serial=<live> (swapped?)++The keyring ``init`` sealed is gone:++.. code-block:: text++ Status: tampered (the keyring init froze is gone)+ ...+ KeyringSealed ALERT pin serial=<pinned>, the BPF keyring is gone (removed?)++The config cannot be verified against its records:++.. code-block:: text++ Status: tampered (the selected config cannot be verified against its records)+ ...+ ConfigActive ALERT the config PCR, activation records and mounted config disagree (tamper?)++The detail of ``ConfigActive`` names the cause:++- ``the config PCR, activation records and mounted config disagree+ (tamper?)``: the config PCR does not hold the value the activation+ records predict. Something extended the PCR after this boot's config+ measurement. Software that measures into the same PCR causes this+ too, see :doc:`/operate/hardening` for the PCR choice.+- ``the config activation record does not belong to this TPM boot+ (tamper?)``: the TPM was reset since the config was measured, for+ example by a resume from hibernation.+- ``the mounted config does not match the selected root (tamper?)``: the+ config image mounted at ``/run/shirudo/config`` is not the one the+ records select.++In each of the config states every command except ``status`` and+``image status`` refuses with ``shirudo: image state:`` and the error,+see :doc:`/operate/troubleshooting`.++For every reason, do not retry anything and do not reboot first: the+journal and the state of this boot are the evidence. Follow+:doc:`/operate/incident-tampered`.++.. _status-lsm-off:++``lsm-off``+~~~~~~~~~~~++.. code-block:: text++ Status: lsm-off (LSM not attached -- enforcement OFF)+ ...+ LsmAttached ALERT lsm/bpf absent -- enforcement OFF++Enforcement is not up. Root can load BPF, and the seal on shirudo's+state is not enforced. A failure of ``init`` in the initrd does not stop+the boot, so a target whose ``shirudo-initrd.service`` failed comes up+in this state. So does a target booted without the shirudo initrd.++1. Read the journal of the initrd run:++ .. code-block:: console++ target# journalctl -b -u shirudo-initrd.service++2. Fix the cause that :doc:`/operate/initialize` lists for the failed+ step.++3. Reboot.++.. _status-reboot-pending:++``reboot-pending``+~~~~~~~~~~~~~~~~~~++.. code-block:: text++ Status: reboot-pending (a config activation is pending until the next reboot)+ ...+ ConfigActive WARN the activation of config <root>.. is pending until the next reboot++A config activation was recorded as pending and did not complete. This+happens when ``shirudo image update`` is interrupted after it saved the+pending selection, and when ``init`` fails after it recorded this boot's+config measurement, while restoring the archived upatches or binding the+register. In the second case ``ChainIntact`` and ``TpmMeasured`` also+show ``WARN``. Every command except ``status`` and ``image status``+refuses with ``shirudo: image state: Operation now in progress`` until+the next boot.+A re-run of ``init`` refuses too. shirudo never reboots the target on+its own.++1. Read the journal to learn which step failed:++ .. code-block:: console++ target# journalctl -b -t shirudo++2. Reboot. The next boot verifies the pending config and records a fresh+ measurement for it.++3. Check the verdict again. A ``reboot-pending`` verdict after the next+ boot, with ``boot-restore`` errors in the journal, means an archived+ upatch fails to load at every boot. :doc:`/operate/backup-recovery`+ describes what works in that case.++.. _status-degraded:++``degraded``+~~~~~~~~~~~~++.. code-block:: text++ Status: degraded (no register bound this boot)+ ...+ ChainIntact WARN no register bound this boot (init incomplete)+ TpmMeasured WARN NV index 0x01818E00 not bound this boot++Enforcement is up, but the TPM holds no written measurement register, or+``status`` could not read it. The ``Chain`` line of the ``TPM+Measurement`` section tells the two apart: ``unavailable (register not+bound this boot)`` or ``unavailable (TPM error: <error>)``.++A failure of ``init`` while binding the register leaves the config+activation pending, which shows as ``reboot-pending``. A ``degraded``+verdict whose ``Chain`` line says ``register not bound this boot``+therefore means the register was bound and then disappeared. Undefining+the index takes TPM owner authorization, which root has on a TPM whose+owner authorization is empty. Collect the evidence as for ``tampered``,+see :doc:`/operate/incident-tampered`, then reboot.++The reason ``no TPM answered`` means the TPM stopped answering while+``status`` ran. On a production target every command first checks that+the TPM is the one ``init`` bound, so a TPM that does not answer at all+makes ``status`` itself fail with ``shirudo: image state:``.++.. _status-tamper-counters:++Read the tamper counters+------------------------++Each counter counts the attempts that one guard point refused this boot.+The refusal worked, so a counter alone does not change any condition or+the verdict. It tells you that something on the host tried.++These four attempts, made as root without shirudo's runtime authority,+were each refused:++.. code-block:: console++ # cat /run/shirudo/bpffs/tamper+ cat: /run/shirudo/bpffs/tamper: Permission denied+ # rm /run/shirudo/bpffs/identity+ rm: cannot remove '/run/shirudo/bpffs/identity': Operation not permitted+ # umount /run/shirudo/bpffs+ umount: /run/shirudo/bpffs: must be superuser to unmount.+ # echo x >> /var/lib/shirudo/eventlog+ sh: 4: cannot create /var/lib/shirudo/eventlog: Permission denied++``umount`` prints ``must be superuser to unmount`` for the ``EPERM`` the+LSM returns. The report afterwards lists one more count under+``ObjGet``, ``PinUnlink``, ``BpffsUmount`` and ``SealWrite``:++.. code-block:: console++ target# shirudo status+ ...+ Tamper attempts (refused this boot):+ LoadNotLoader 39 program load that is not a signed loader+ MapCreate 1 map creation by another executable+ BpfCommand 16 detach, update, delete or unclassified bpf() command+ PinUnlink 1 unlink of a pin in the private bpffs+ BpffsUmount 1 unmount of the private bpffs+ SealWrite 1 write open of a sealed file+ SealPtrace 12 ptrace of a shirudo task+ ObjGet 1 pin, map or link opened by another executable+ ...++Read the counters with these rules:++- Learn the baseline of your hosts. Software other than shirudo that+ uses BPF or inspects processes is refused too. A freshly booted test+ VM shows counts for ``LoadNotLoader``, ``MapCreate``, ``BpfCommand``+ and ``SealPtrace`` before any upatch is loaded.+- Alert on a counter that moves beyond the baseline, and on any count of+ a counter that stays at zero on your hosts.+- Find the actor in the journal and on the host. The counter does not+ record who tried.+- A zero count does not prove that nothing tried. Some refusals have no+ counter, among them those of the runtime and config image mounts and+ of device-mapper control commands.++:doc:`/security/tamper-counters` lists every counter and the guard point+that raises it.++Monitor with ``status --json``+------------------------------++``status --json`` prints the same data as one JSON document. The+keepalive timer sends it to your collector, see+:doc:`/operate/telemetry`.++.. warning::++ ``shirudo status`` exits 0 whatever the verdict, ``tampered``+ included. It exits 1 only when it cannot load its configuration, runs+ out of memory or fails to send a keepalive, and 2 on a usage error or+ an invalid ``map_export`` setting. Alert on the ``status`` field of+ the JSON document, never on the exit code.++Read the verdict:++.. code-block:: console++ target# shirudo status --json | jq -r .status+ ok++The fields that matter for monitoring:++.. list-table::+ :header-rows: 1+ :widths: 38 62++ * - Field+ - Alert when+ * - ``status``+ - It is not ``ok``.+ * - ``conditions[].status``+ - Any condition is ``ALERT``.+ * - ``mode``+ - It is not ``production``.+ * - ``tamper_attempts.total``+ - It rises beyond your baseline. It is ``null`` before ``init``.+ * - ``config.activation_pending``+ - It is ``true``.+ * - ``config.error``+ - It is not ``null``. It carries the error of an unverifiable+ config: ``Structure needs cleaning``, ``Stale file handle`` or+ ``Key was rejected by service``.+ * - ``keyring_serial_matches``+ - It is ``false``.+ * - ``tpm.register_bound`` and ``tpm.register_anchored``+ - Either is ``false``.+ * - ``tpm.chain_matches_eventlog``+ - It is ``false``.+ * - ``tpm.register_rebound``+ - It is ``true``.+ * - ``tpm.bound_in``+ - It is not ``initrd``.+ * - ``signing_key_present``+ - It is ``true`` on a target.+ * - ``version_id``+ - It differs from the build you deployed.+ * - ``upatch_tree.eventlog_matches_state``+ - It is ``false``.++``upatches_loaded`` lists each loaded upatch with its+``payload_sha256``, which you can compare with the artifacts you+shipped. :doc:`/reference/formats/status-json` describes every field.++Alert separately when ``status`` does not run at all. A target that+refuses every command, ``status`` included, prints ``shirudo: image+state:`` with an error and exits 1, and a target whose keepalive stops+arriving may be in that state.++Check a copy outside the runtime image+--------------------------------------++Only the runtime image's binary has runtime authority. Any other copy of+the binary is refused before it reads anything:++.. code-block:: console++ target# /usr/local/bin/shirudo status+ shirudo: image state: Permission denied++It exits 1. The refusal also shows as one more ``ObjGet`` count, because+the copy tried to open the identity pin. A monitoring agent that reports+this error is running the wrong binary, see :ref:`runtime-invocation`.++Verify+------++Confirm that your monitoring reads the verdict from the JSON document:+on a healthy target, ``shirudo status --json | jq -r .status`` prints+``ok`` and your alert stays quiet.++Next steps+----------++- :doc:`/operate/attest` to have the TPM confirm what the report says.+- :doc:`/operate/incident-tampered` for a ``tampered`` verdict.+- :doc:`/operate/troubleshooting` for refused commands and failure+ categories.+- :doc:`/operate/telemetry` to send the report to a collector.+- :doc:`/reference/cli/status` for every option.diff --git a/Documentation/operate/system-requirements.rst b/Documentation/operate/system-requirements.rstnew file mode 100644index 00000000..1f39a62d--- /dev/null+++ b/Documentation/operate/system-requirements.rst@@ -0,0 +1,482 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++System requirements+===================++What the target, the operator host and the host that builds the target+binary need. A missing requirement fails the build, ``shirudo init`` or+the load. shirudo has no compatibility mode and no fallback for an older+kernel.++Architectures+-------------++.. list-table::+ :header-rows: 1+ :widths: 20 80++ * - Architecture+ - Notes+ * - x86-64+ - Target and operator. The test VM runs on x86-64 hosts. Targets+ need ``kernel/0001`` (see below).+ * - arm64+ - Target and operator. The test VM runs on arm64 hosts.+ * - riscv64+ - Target and operator. The build applies the hardening flags that+ exist for riscv64. No test VM runs on riscv64.++All three are little-endian, the byte order of the ``.upatch`` container.++Target kernel+-------------++The target runs a bpf-next kernel with the signed-loader ABI. A release+number does not identify such a kernel: development trees report the+release they follow (the test kernel reports ``7.3.0-bpf-next+``), and+the ABI and the patches below decide whether shirudo works on it.++Kernel source+~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Component+ - Requirement+ * - bpf-next+ - The signed-loader ABI: ``bpf_map.sha``, ``bpf_map.excl_prog_sha``,+ ``bpf_prog_aux.sig`` with ``keyring_serial``, ``keyring_type``+ and ``verdict``, the ``.bpf`` keyring reachable as+ ``KEY_SPEC_BPF_KEYRING`` with the ``bpf.keyring_unsealed``+ parameter, and the kfuncs ``bpf_inode_init_xattr`` and+ ``bpf_real_data_inode``. The test suite runs bpf-next commit+ ``4169c9c90532``.+ * - Upstream commit ``1041fca2ee8a``+ - ``keys: add KEY_SPEC_DM_VERITY_KEYRING``. ``shirudo init``+ enrolls and seals the config certificate in the ``.dm-verity``+ keyring through ``KEY_SPEC_DM_VERITY_KEYRING``. Apply it to a+ bpf-next tree that predates it.+ * - ``kernel/0001-x86-ftrace-Mark-jmp-mode-by-clearing-bit-63-of-the-trampoline-address.patch``+ - x86-64 only. Without it, detaching one BPF program from a hook+ that others share can crash tasks that run the hook during the+ update, on kernels where an ftrace callback starts at an odd+ address (seen with gcc 13 and ``CONFIG_CC_OPTIMIZE_FOR_SIZE=y``).+ Unloading an upatch detaches its programs from hooks that other+ programs share.+ * - ``kernel/0002-tpm-Let-LSMs-inspect-userspace-commands.patch``+ - Adds the ``tpm_command`` LSM hook. ``shirudo init`` attaches+ ``lsm/tpm_command`` to refuse an untrusted ``TPM2_NV_Extend`` of+ its register and fails without the hook.++:doc:`/internals/kernel-patches` gives the upstream status of the+carried patches.++Identify the kernel+~~~~~~~~~~~~~~~~~~~++- Record the source commit and the patches applied when you build the+ kernel. ``make -C testing kernel`` writes them as ``commit=``,+ ``upstream_commit=`` and ``patches_applied=`` to a+ ``<name>-kernel-build`` file beside the kernel packages, for bpf-next+ ``bpf-next-kernel-build``.+- ``shirudo init --check-only`` checks the ABI of the running kernel+ from its BTF (``signed_loader_kernel_abi``). A load on a kernel+ without it fails with ``kernel_abi_unsupported``.+- The test harness builds bpf-next by default. It also builds release+ tags and refuses any tag older than v7.4. It applies the patches in+ ``kernel/`` to either. A release kernel still needs ``kernel/0002``.++Kernel configuration+~~~~~~~~~~~~~~~~~~~~++shirudo needs every option below. The test kernel's configuration is the+slim configuration in ``testing/vm/build-kernel.sh``, which also enables+options that only the tests use.++.. list-table::+ :header-rows: 1+ :widths: 38 62++ * - Option+ - Reason+ * - ``CONFIG_BPF_SYSCALL``+ - The ``bpf()`` system call, the BPF file system that holds+ shirudo's pins, and the ``.bpf`` keyring. Pre-flight check+ ``bpffs_supported``.+ * - ``CONFIG_BPF_JIT``+ - BPF trampolines, through which the LSM programs and ``fentry``,+ ``fexit``, ``fmod_ret`` and ``lsm`` upatches attach, exist only+ with the JIT. ``CONFIG_BPF_LSM`` depends on it.+ * - ``CONFIG_BPF_LSM``, ``CONFIG_SECURITY``, ``bpf`` in+ ``CONFIG_LSM``+ - Every admission gate, guard and the seal are BPF LSM programs.+ Without ``bpf`` in ``CONFIG_LSM``, add it with ``lsm=`` on the+ command line. Pre-flight check ``bpf_lsm_active``.+ * - ``CONFIG_BPF_EVENTS``, with ``CONFIG_PERF_EVENTS`` and+ ``CONFIG_KPROBE_EVENTS`` or ``CONFIG_UPROBE_EVENTS``+ - ``CONFIG_BPF_LSM`` depends on ``CONFIG_BPF_EVENTS``, which+ depends on these.+ * - ``CONFIG_SECURITYFS``+ - ``/sys/kernel/security/lsm``, which ``bpf_lsm_active`` reads.+ * - ``CONFIG_FUNCTION_TRACER``, ``CONFIG_DYNAMIC_FTRACE``,+ ``CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS``+ - The kernel installs a trampoline on an ftrace-managed function as+ an ftrace direct call and refuses the attach without direct-call+ support.+ * - ``CONFIG_DEBUG_INFO_BTF``+ - ``/sys/kernel/btf/vmlinux``: the ABI check, CO-RE relocation in+ every signed loader, and attaching LSM programs by BTF id.+ * - ``CONFIG_KEYS``+ - The ``.bpf`` and ``.dm-verity`` keyrings. Pre-flight check+ ``kernel_keyring``.+ * - ``CONFIG_ASYMMETRIC_KEY_TYPE``,+ ``CONFIG_ASYMMETRIC_PUBLIC_KEY_SUBTYPE``,+ ``CONFIG_X509_CERTIFICATE_PARSER``+ - ``add_key(2)`` of the signing and config certificates as+ ``asymmetric`` keys. Pre-flight check ``cert_kernel_support``.+ * - ``CONFIG_PKCS7_MESSAGE_PARSER``,+ ``CONFIG_SYSTEM_DATA_VERIFICATION``+ - Verification of the detached PKCS#7 signature of a loader at+ ``BPF_PROG_LOAD`` and of a config image's root hash by dm-verity.+ * - ``CONFIG_CRYPTO_MLDSA``+ - ML-DSA-87 certificates and signatures, the only kind shirudo+ produces. Without it ``add_key(2)`` fails with ``ENOENT`` or+ ``ENOPKG`` and ``cert_kernel_support`` fails.+ * - ``CONFIG_CRYPTO_SHA512``+ - The signed-attributes digest that OpenSSL 3.x adds to an ML-DSA+ signature. ``CONFIG_CRYPTO_MLDSA`` does not select it.+ * - ``CONFIG_CRYPTO_SHA256``+ - The ``sha256`` hash trees of the runtime and config images.+ * - ``CONFIG_TCG_TPM`` and a TPM driver (``CONFIG_TCG_TIS``,+ ``CONFIG_TCG_CRB`` or the platform's)+ - ``/dev/tpmrm0``. Pre-flight check ``tpm2_reachable``.+ * - ``CONFIG_BLK_DEV_DM``, ``CONFIG_DM_VERITY``+ - The runtime and config images are mapped as dm-verity devices:+ verity format 1, SHA-256, 4096-byte blocks.+ * - ``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG``+ - The kernel verifies the signed root hash of a config image. The+ ``.dm-verity`` keyring exists only with this option.+ * - ``CONFIG_BLK_DEV_LOOP``+ - The image files are attached to loop devices.+ * - ``CONFIG_EXT4_FS``+ - The images are ext4 file systems, mounted read-only.+ * - Security extended attributes on the file system of+ ``/var/lib/shirudo`` (``CONFIG_EXT4_FS_SECURITY`` on ext4)+ - The seal labels writable state with ``security.bpf.shirudo``,+ on new inodes while the kernel creates them.+ * - ``CONFIG_TMPFS``, ``CONFIG_TMPFS_XATTR``+ - ``/run/shirudo`` carries the same label.++The dm-verity root-hash check also accepts a config signed by a key in+the kernel's built-in trusted keyring, and in the secondary or platform+keyring when ``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_SECONDARY_KEYRING`` or+``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_PLATFORM_KEYRING`` is set.+:doc:`/operate/hardening` lists what that means for who can sign a+config, and the options the trust model assumes beyond this table:+lockdown, module signature enforcement, ``CONFIG_COMPAT`` and others.++Kernel command line+~~~~~~~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 38 62++ * - Parameter+ - Reason+ * - ``bpf.keyring_unsealed=1``+ - The kernel leaves the ``.bpf`` keyring unsealed at boot, so that+ ``shirudo init`` in the initrd enrolls the trusted certificates+ and seals it. Without it the kernel seals the keyring empty and+ ``init`` fails: ``bpf keyring serial=<n> was sealed empty at boot;+ boot with bpf.keyring_unsealed=1``.+ * - ``dm_verity.keyring_unsealed=1``+ - The same for the ``.dm-verity`` keyring and the config+ certificate. Without it ``init`` fails with ``initrd boot keys:+ dm-verity keyring sealed empty at boot; boot with+ dm_verity.keyring_unsealed=1``.+ * - ``lsm=<list>`` including ``bpf``+ - Only when ``CONFIG_LSM`` does not list ``bpf``.++``shirudo-gen-initrd --print-cmdline`` prints the two keyring parameters.+In production the command line is part of the signed unified kernel+image. See :doc:`/operate/boot-integration`.++Attach points for upatches+~~~~~~~~~~~~~~~~~~~~~~~~~~++shirudo runs without these options. They decide where the upatches a+fleet runs can attach. ``fentry``, ``fexit``, ``lsm`` and ``tp_btf``+upatches need nothing beyond the table above. An upatch whose attach+point is missing fails to load.++.. list-table::+ :header-rows: 1+ :widths: 38 62++ * - Option+ - Enables+ * - ``CONFIG_KPROBES``, ``CONFIG_KPROBE_EVENTS``+ - ``kprobe`` and ``kretprobe`` upatches.+ * - ``CONFIG_FUNCTION_ERROR_INJECTION``+ - ``fmod_ret`` on kernel functions outside the ``security_*`` hooks+ that are marked for error injection.+ * - ``CONFIG_BPF_KPROBE_OVERRIDE``+ - ``bpf_override_return()`` from a ``kprobe`` upatch.+ * - ``CONFIG_UPROBE_EVENTS``+ - ``uprobe.multi`` upatches.+ * - ``CONFIG_CGROUP_BPF``+ - ``cgroup_skb`` upatches.+ * - ``CONFIG_NETFILTER``, ``CONFIG_NETFILTER_BPF_LINK``+ - ``netfilter`` upatches.++:doc:`/upatches/attach-kinds` describes each attach kind.++TPM+---++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Requirement+ - Reason+ * - TPM 2.0 through the kernel resource manager, ``/dev/tpmrm0``+ - The measurement register and the attestation key. There is no+ mode without a TPM. An authenticated-image target accepts only a+ ``device:`` TCTI, so that ``lsm/tpm_command`` sees every command.+ The static target binary contains only the device TCTI.+ * - SHA-256 PCR bank+ - shirudo reads PCRs 9 and 11 and the config PCR in the SHA-256+ bank and extends PCR 9 and the config PCR there.+ * - RSA-3072 primary keys with RSASSA and SHA-256 in the owner+ hierarchy+ - The key that authorizes writes to the register through+ ``TPM2_PolicySigned``.+ * - ECC NIST P-256 primary keys with ECDSA and SHA-256 in the+ endorsement hierarchy+ - The attestation key that ``shirudo attest`` signs evidence with.+ * - An endorsement key in the RSA-2048 or ECC P-256 template+ - Credential activation for ``shirudo attest --challenge``.+ * - NV index ``0x01818E00`` free+ - shirudo defines its register there. The index clears at TPM reset.+ * - Endorsement hierarchy without an authorization value+ - shirudo creates the attestation and endorsement keys with an+ empty authorization.+ * - Owner hierarchy authorization, if set, in ``tpm.owner_auth``+ - shirudo defines the NV index and the writer key under the owner+ hierarchy. See :doc:`/reference/formats/configuration`.++Target userspace+----------------++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Requirement+ - Reason+ * - systemd 256 or newer+ - ``shirudo-initrd.service`` orders itself after ``tpm2.target``,+ which systemd 256 introduced. With an older systemd, ``init`` can+ run before the TPM is available.+ * - A systemd initrd built by dracut, with the ``systemd``,+ ``systemd-initrd`` and ``systemd-pcrextend`` modules+ (``systemd-pcrphase`` in older dracut)+ - The dracut module ``90shirudo`` installs and enables+ ``shirudo-initrd.service``. ``shirudo-gen-initrd`` refuses an+ initrd without ``systemd-pcrphase-initrd.service``.+ * - A unified kernel image booted through ``systemd-stub``+ - ``systemd-pcrphase-initrd.service`` measures ``enter-initrd`` into+ PCR 11 only under ``systemd-stub``. The register's write policy+ binds PCRs 9 and 11 while the initrd runs.+ * - ``/var/lib/shirudo`` writable and mounted under ``/sysroot``+ while the initrd runs+ - ``shirudo-initrd.service`` has+ ``RequiresMountsFor=/sysroot/var/lib/shirudo``. Its file system+ needs security extended attributes.+ * - No other task adds keys to or restricts the ``.bpf`` and+ ``.dm-verity`` keyrings before ``shirudo-initrd.service``+ - ``init`` refuses a keyring that holds keys other than its own or+ carries a restriction it did not install.+ * - Root+ - Run shirudo as root on a target. ``shirudo init`` refuses a+ non-zero effective UID (pre-flight check ``root``).+ * - ``CAP_IPC_LOCK`` or an ``RLIMIT_MEMLOCK`` large enough for the+ process+ - ``shirudo`` locks all its memory with ``mlockall(2)`` before it+ dispatches a command and exits with ``hardening: cannot lock+ process memory`` when that fails. The shipped units set+ ``LimitMEMLOCK=infinity``.++The target needs no external tools: it maps and verifies the images+through kernel interfaces.++Pre-flight checks+-----------------++``shirudo init`` runs these checks first and stops when one fails.+``shirudo init --check-only`` runs only them. See+:doc:`/reference/cli/init`.++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Check+ - Passes when+ * - ``root``+ - The effective UID is 0.+ * - ``bpf_lsm_active``+ - ``/sys/kernel/security/lsm`` lists ``bpf``.+ * - ``bpffs_supported``+ - ``/proc/filesystems`` lists ``bpf``.+ * - ``signed_loader_kernel_abi``+ - The kernel BTF has the fields of the signed-loader ABI with the+ expected types.+ * - ``cert_on_disk``+ - The primary certificate exists, is a regular file and is not+ empty.+ * - ``cert_algorithm``+ - Every trusted certificate is ML-DSA-87.+ * - ``cert_kernel_support``+ - The kernel accepts every trusted certificate as an+ ``asymmetric`` key, probed in the thread keyring.+ * - ``kernel_keyring``+ - ``keyctl(2)`` resolves the user keyring and the ``.bpf`` keyring.+ * - ``embedded_loader``+ - The binary carries its two embedded BPF objects.+ * - ``tpm2_reachable``+ - ``/dev/tpmrm0`` is readable and writable, or ``tpm.tcti`` names a+ TCTI.++Run the checks as root on a target:++.. code-block:: console++ target# shirudo init --check-only+ pre-flight checks:+ root OK+ bpf_lsm_active OK+ bpffs_supported OK+ signed_loader_kernel_abi OK+ cert_on_disk OK+ cert_algorithm OK+ cert_kernel_support OK+ kernel_keyring OK+ embedded_loader OK+ tpm2_reachable OK: TCTI override: device:/dev/tpmrm0+ 10/10 passed (0 failed)++A failed check prints ``FAIL`` and its reason, and the command exits 1+after ``init: pre-flight failed (<failed>/<total> checks)``.++Network+-------++Every HTTPS connection to a registry, an OTLP collector or an S3+endpoint uses TLS 1.3 with the hybrid key exchange ``X25519MLKEM768`` or+``SecP256r1MLKEM768``. A server that offers neither fails the handshake,+unless its exact host name is listed in ``tls.classical_hosts``. Then+shirudo also offers ``X25519`` and ``secp256r1`` and logs a warning when+the handshake uses one of them.++Operator host+-------------++The operator host never loads BPF and never uses a TPM or the kernel+keyrings. Any Linux kernel on which the tools below run serves.++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Requirement+ - Reason+ * - OpenSSL 3.5 or newer: ``libcrypto``, ``libssl`` and the+ ``openssl`` command with ML-DSA+ - ML-DSA-87 signing and hybrid ML-KEM TLS. The build refuses older+ versions.+ * - ``libcurl`` 7.75 or newer, ``tss2-esys`` 4.0 or newer,+ ``tss2-tctildr``, ``libelf``, ``zlib``, LuaJIT+ - Linked by the ``shirudo`` binary, which is the same program on+ both roles.+ * - ``clang`` and LLVM with the BPF target, installed as+ ``/usr/bin/clang``+ - ``shirudo build`` runs that path and does not search ``PATH``.+ * - The target kernel's ``vmlinux.h``+ - The one kernel-derived input of a build. ``shirudo build`` takes+ ``--vmlinux``, else ``./vmlinux.h``, else+ ``./vendor/linux/vmlinux.h``, else ``<sharedir>/shirudo/vmlinux.h``+ of the installation. See :doc:`/reference/cli/build`.+ * - ``veritysetup`` (``cryptsetup-bin`` or ``cryptsetup``),+ ``mkfs.ext4`` (``e2fsprogs``), Bash and GNU coreutils+ - Building runtime and config images, and ``shirudo image verify``.+ * - ``CAP_IPC_LOCK`` or an ``RLIMIT_MEMLOCK`` large enough for the+ process+ - ``shirudo`` and ``shirudo-build`` lock all their memory before+ they dispatch a command.++The operator package depends on ``clang``, ``llvm`` and the+``veritysetup`` package. The operator and target packages conflict, so+one host cannot install both.++Build host for the target binary+--------------------------------++``make target`` builds a static PIE binary with no interpreter, no+shared-library dependencies and no library search path. It runs ``make+target-deps`` first.++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Requirement+ - Reason+ * - Network access to the OpenSSL and curl release downloads and to+ the tpm2-tss Git repository+ - ``make target-deps`` builds OpenSSL 3.5.9, libcurl 8.18.0 and+ tpm2-tss 4.2.0 from source as static archives. Set+ ``TARGET_DEPS_PREBUILT=1`` and ``SHIRUDO_TARGET_PKG_CONFIG_PATH``+ to use prebuilt ones.+ * - autoconf, automake, libtool and autoconf-archive+ - tpm2-tss's ``bootstrap`` script.+ * - Static ``libelf.a``, ``libz.a``, ``libzstd.a`` and+ ``libluajit-5.1.a``+ - Taken from the first of ``/usr/lib/<multiarch>``, ``/usr/lib64``+ and ``/usr/lib`` that holds ``libelf.a``.+ ``TARGET_SYSTEM_LIBDIR=`` names another directory.+ * - Static glibc, ``libm``, startup objects and compiler runtime with+ static PIE support (``libc6-dev`` on Debian, ``glibc-static`` on+ Fedora)+ - The static PIE link. They come from the compiler's sysroot.+ * - ``clang`` with the BPF target+ - The BPF objects embedded in the binary.+ * - BTF of a kernel with the signed-loader ABI+ - The embedded BPF objects read ``prog->aux->sig`` and do not+ compile against an older ``vmlinux.h``. The build uses+ ``BPF_VMLINUX_BTF=<file>``, or ``BPF_VMLINUX_H=<file>``, else+ ``artifacts/bpf-next-kernel-debs/vmlinux.btf`` when present, else+ ``/sys/kernel/btf/vmlinux``.+ * - ``readelf`` (binutils)+ - The build checks that the result is a static PIE.++The operator binary links the host's shared libraries. Build it on the+distribution it is installed on.++Related+-------++- :doc:`/operate/deployment-checklist`+- :doc:`/operate/hardening`+- :doc:`/operate/boot-integration`+- :doc:`/internals/kernel-interfaces`+- :doc:`/start/install`diff --git a/Documentation/operate/telemetry.rst b/Documentation/operate/telemetry.rstnew file mode 100644index 00000000..40268dae--- /dev/null+++ b/Documentation/operate/telemetry.rst@@ -0,0 +1,420 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Monitor and export telemetry+============================++A target pushes two kinds of telemetry to a collector: a status+keepalive and snapshots of the maps its upatches keep. Both leave as+OTLP/HTTP requests with JSON bodies, sent by one-shot commands that+systemd timers start. Nothing connects to the target. This page shows+how to choose the destination, set up the collector, check the pipeline+and decide what to alert on.++Telemetry is the target's own account of itself. It carries no proof of+origin, so it tells you where to look, not what is true. Evidence that a+target cannot forge comes from the TPM, through :doc:`attest`.++What a target sends+-------------------++.. list-table::+ :header-rows: 1+ :widths: 26 30 44++ * - Timer+ - Runs+ - Sends+ * - ``shirudo-keepalive.timer``+ - ``shirudo status --otel --include-system``+ - One log record, ``shirudo.keepalive``, when an OTLP endpoint is+ configured. Nothing otherwise.+ * - ``shirudo-map-export.timer``+ - ``shirudo upatch map --all``+ - One record per pinned map to every destination the config names:+ JSON lines, OTLP, or both. With no destination, the dump goes to+ the journal.++Both timers start their service 5 seconds after boot and again 5 seconds+after each run ends. ``shirudo-map-export.service`` runs only while+``/run/shirudo/bpffs/lsm_link`` exists.++The keepalive record has the event name ``shirudo.keepalive``. Its body+is the ``shirudo status --json`` document with the system section, and+its attributes are ``shirudo.status`` (the verdict),+``shirudo.version_id`` and ``shirudo.tamper_attempts`` (the refusals the+guards counted this boot). Its severity follows the verdict:++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Severity+ - Verdict+ * - ``INFO`` (9)+ - ``ok``+ * - ``WARN`` (13)+ - ``degraded``, ``init-pending``, ``reboot-pending``+ * - ``ERROR`` (17)+ - Every other verdict, ``tampered`` and ``lsm-off`` among them++A map snapshot has the event name ``shirudo.bpf.map.snapshot``. Its body+is what the map's signed decoder returns, or the map's entries when the+upatch ships no decoder for it. A decoder can return metrics instead of+a log record. Every request carries the resource attributes+``service.name`` (``shirudo``), ``service.version`` and ``host.name``.+:doc:`/reference/formats/otlp` describes every field.++Before you begin+----------------++- On the target, ``shirudo`` stands for the runtime image's binary,+ ``/run/shirudo/runtime/usr/bin/shirudo`` (:ref:`runtime-invocation`).+- The keepalive and map-export services run that binary through their+ drop-ins (:ref:`unit-drop-ins`). Without them both services fail on an+ enforcing target and nothing is sent.+- A collector that accepts OTLP over HTTP with JSON bodies, reachable+ from the target over TLS 1.3.+- On the operator host, the source directory of the target's config+ image and the key that signs config images.++Set the destination+-------------------++The destination belongs in the signed config image, in+``etc/shirudo/shirudo.conf``. The target ignores the host's+``/etc/shirudo/shirudo.conf`` while a config image is active.++#. In the config source directory, add the export settings to+ ``etc/shirudo/shirudo.conf``:++ .. code-block:: text++ map_export.otel_endpoint = https://<collector-host>:4318+ map_export.tenant_id = <tenant>++ ``<collector-host>`` is the collector's DNS name. ``<tenant>`` is an+ optional label that the target sends as the ``X-Tenant-ID`` header.++#. Build, sign and activate the config, as described in+ :ref:`deliver-packages-config-update`.++#. Check the effective settings on the target:++ .. code-block:: console++ target# shirudo config+ # shirudo config (authenticated config image; TPM settings from runtime image)+ ...+ map_export.json_path =+ map_export.otel_endpoint =+ map_export.tenant_id = config-boot-keys+ map_export.otel_insecure = false+ map_export.otel_retries = 3+ map_export.s3_uri =+ map_export.log_record_max_bytes = 1048576+ map_export.otlp_max_bytes = 4194304++ The first line says that the settings come from the authenticated+ config image. This target's config names no destination yet, so+ ``map_export.otel_endpoint`` is empty. After your update it shows+ your collector.++The config image accepts these keys:++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Key+ - Meaning+ * - ``map_export.otel_endpoint``+ - Base URL of the collector. The target appends ``/v1/logs`` or+ ``/v1/metrics``. ``http://`` is allowed only to ``localhost``,+ ``127.0.0.1`` and ``[::1]``, and a URL with a user name or+ password is refused. Default: empty.+ * - ``map_export.tenant_id``+ - Value of the ``X-Tenant-ID`` header, 1 to 128 characters from+ ``A-Z``, ``a-z``, ``0-9``, ``.``, ``_`` and ``-``. Default: empty,+ no header.+ * - ``map_export.otel_insecure``+ - ``true`` allows ``http://`` to any host and turns off certificate+ and host name checks for ``https://``. The command prints a+ warning each time. Default: ``false``.+ * - ``map_export.otel_retries``+ - Retries after a failed request, 0 to 10. Default: 3.+ * - ``map_export.json_path``+ - Absolute path of a file to which ``upatch map --all`` appends+ one JSON line per map. Default: empty.+ * - ``map_export.s3_uri``+ - S3 location for a decoded snapshot too large for one OTLP+ record. The collector then receives a record that points to the+ object. Requires ``map_export.otel_endpoint``. Default: empty.+ * - ``map_export.log_record_max_bytes``+ - Largest log record, 1 to 8388608 bytes, at most+ ``map_export.otlp_max_bytes``. Default: 1048576.+ * - ``map_export.otlp_max_bytes``+ - Largest request body before compression, 1 to 8388608 bytes.+ Default: 4194304.++The only other key the config image's ``shirudo.conf`` accepts is+``eventlog.max_bytes``. :doc:`/reference/formats/configuration` lists+every key, including those of the runtime image.++Set credentials and TLS material+--------------------------------++Credentials, headers and certificates are environment variables, not+configuration. systemd reads them for both services from+``/etc/shirudo/map-export.env``.++#. Write the variables your collector needs to+ ``/etc/shirudo/map-export.env``:++ .. code-block:: text++ OTEL_EXPORTER_OTLP_HEADERS=authorization=Bearer%20<token>+ OTEL_EXPORTER_OTLP_CERTIFICATE=/etc/shirudo/collector-ca.pem++ ``OTEL_EXPORTER_OTLP_HEADERS`` takes comma-separated+ ``<key>=<value>`` pairs with percent-encoded values, so ``%20`` is a+ space. It refuses ``Content-Type``, ``Content-Encoding``,+ ``Content-Length``, ``Host`` and ``User-Agent``.+ ``OTEL_EXPORTER_OTLP_CERTIFICATE`` names the CA bundle that signed+ the collector's certificate. ``<token>`` is your collector's ingest+ token.++#. Make the file readable by root alone:++ .. code-block:: console++ target# chmod 0600 /etc/shirudo/map-export.env++The target also reads these variables:++- ``OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`` and+ ``OTEL_EXPORTER_OTLP_CLIENT_KEY`` for mutual TLS, both or neither.+- ``OTEL_EXPORTER_OTLP_COMPRESSION``: ``none`` or ``gzip``.+- ``OTEL_EXPORTER_OTLP_TIMEOUT``: milliseconds per attempt, 1 to 120000,+ default 10000.+- ``OTEL_EXPORTER_OTLP_PROTOCOL``: only ``http/json`` is accepted.+- ``AWS_REGION`` or ``AWS_DEFAULT_REGION``, ``AWS_ACCESS_KEY_ID``,+ ``AWS_SECRET_ACCESS_KEY``, ``AWS_SESSION_TOKEN``,+ ``AWS_ENDPOINT_URL_S3`` and ``AWS_CA_BUNDLE`` for ``map_export.s3_uri``.++Each ``OTEL_EXPORTER_OTLP_*`` variable also has a ``_LOGS_`` and a+``_METRICS_`` form, which wins over the generic one for its signal.+:doc:`/reference/environment` lists them all.++The endpoint variables behave differently for the two services:++- ``OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`` and ``OTEL_EXPORTER_OTLP_ENDPOINT``+ apply only while ``map_export.otel_endpoint`` is empty.+- The keepalive sends when ``map_export.otel_endpoint`` or one of those+ two variables is set. It never falls back to ``localhost``.+- ``upatch map --all`` sends OTLP only when ``map_export.otel_endpoint``+ is set. An endpoint variable alone does not turn the map export on.++``/etc/shirudo/map-export.env`` is host state outside the signed+config, and root on the target can change it. While the signed config+names no endpoint, the file decides where keepalives go. Set the+endpoint in the signed config.++Set up the collector+--------------------++The target speaks OTLP/HTTP with JSON bodies and nothing else:+``POST <base>/v1/logs`` and ``POST <base>/v1/metrics`` with+``Content-Type: application/json``, optional ``Content-Encoding: gzip``+and ``X-Tenant-ID``. It uses TLS 1.3 with the hybrid key exchange groups+``X25519MLKEM768`` and ``SecP256r1MLKEM768`` only. A collector that+offers no hybrid group is refused, unless its exact DNS name is in+``tls.classical_hosts`` in the runtime image's+``etc/shirudo/shirudo.conf``, which takes a new runtime image and a+reboot.++#. Configure the OpenTelemetry Collector's ``otlp`` receiver with TLS:++ .. code-block:: yaml++ receivers:+ otlp:+ protocols:+ http:+ endpoint: 0.0.0.0:4318+ tls:+ cert_file: /etc/otelcol/collector.crt+ key_file: /etc/otelcol/collector.key+ min_version: "1.3"++ exporters:+ debug:+ verbosity: detailed++ service:+ pipelines:+ logs:+ receivers: [otlp]+ exporters: [debug]+ metrics:+ receivers: [otlp]+ exporters: [debug]++ The ``debug`` exporter prints what arrives. Replace it with the+ exporters for your storage once records arrive. A collector built+ with Go 1.24 or later offers ``X25519MLKEM768`` by default.++#. Restart the collector.++Any HTTPS server that accepts those two requests works as a destination.+It answers ``200`` to accept. A ``200`` whose ``partialSuccess`` reports+rejected records counts as a failure. The target retries timeouts,+connection errors and the statuses ``429``, ``502``, ``503`` and+``504``, honors ``Retry-After``, and does not retry any other status.++Check the pipeline+------------------++#. Send one keepalive by hand and print it:++ .. code-block:: console++ target# shirudo status --otel --include-system --json++ The command prints the status document and sends it. ``--otel``+ without ``--json`` prints nothing. When the send fails, the command+ prints ``status: OTEL export failed: <reason>`` and exits 1. When no+ endpoint is configured, it sends nothing and exits 0.++#. Check that the collector printed a record with the event name+ ``shirudo.keepalive`` and the attribute ``shirudo.status``.++#. List the maps the loaded upatches pin:++ .. code-block:: console++ target# shirudo upatch map+ (no pinned maps)++ This target has no upatch with maps loaded. With maps, the command+ lists each map with its upatch, type and size.++#. Look at one map without draining it and without exporting it:++ .. code-block:: console++ target# shirudo upatch map <upatch> <map> --peek++ ``<upatch>`` and ``<map>`` are names from the list. ``--peek`` asks+ the serializer for the interval it is collecting and leaves it for+ the timer.++#. Check that the timers run:++ .. code-block:: console++ target# systemctl list-timers 'shirudo-*'++Map export without a destination+--------------------------------++``shirudo-map-export.timer`` runs whether or not a destination is+configured. With no ``map_export.json_path`` and no+``map_export.otel_endpoint``, every run reads every pinned map, drains+the maps that have a serializer, and prints the dump to its standard+output, which systemd writes to the journal. That happens every 5+seconds, and drained records are gone for any later exporter.++If nothing consumes map snapshots, stop the timer:++.. code-block:: console++ target# systemctl disable --now shirudo-map-export.timer++Maps and decoders+-----------------++A map whose upatch ships a signed decoder for it exports what the+decoder returns, a log record or metrics. A map without a decoder+exports as a log record whose body lists the map's entries.++One kind of map without a decoder fails: a per-CPU map whose value is an+unsigned BTF integer. The target classifies it as a metric, finds no+decoder to build the metric and prints ``upatch map: OTLP export+<upatch>/<map>: No data available``. Give such a map a decoder.+:doc:`/upatches/decoders` shows how.++What to alert on+----------------++The keepalive body is the ``shirudo status --json`` document.+:doc:`read-status` explains each field and :doc:`/reference/formats/status-json`+lists them.++.. list-table::+ :header-rows: 1+ :widths: 38 62++ * - Signal+ - What it means+ * - No keepalive from a host for several intervals+ - The target is down or unreachable, the timer or its drop-in is+ missing, or the commands fail. A keepalive also fails when+ another ``shirudo`` command holds the config operation lock for+ more than 30 seconds, during a long package download for+ example.+ * - ``shirudo.status`` other than ``ok``+ - Read :doc:`read-status` for each verdict.+ * - A condition with ``status`` ``ALERT``+ - ``LsmAttached``, ``KeyringSealed``, ``ChainIntact`` or+ ``ConfigActive`` found tampering or lost enforcement.+ * - ``shirudo.tamper_attempts`` rises+ - Something on the target tried an operation the guards refused.+ The counters start at zero each boot. See+ :doc:`/security/tamper-counters`.+ * - ``config.activation_pending`` is ``true``+ - A config activation waits for a reboot. Every command except+ ``status`` is refused until then.+ * - ``tpm.chain_matches_eventlog`` is ``false``+ - The register holds a value the eventlog does not explain. Handle+ it as in :doc:`incident-tampered`.+ * - ``tpm.register_rebound`` is ``true``+ - The register was bound twice in one TPM reset.+ * - ``tpm.bound_in`` is not ``initrd``+ - ``init`` bound the register from the root file system, not from+ the initrd.+ * - ``assets.eventlog_bytes`` nears 8388608+ - The eventlog approaches the size that readers refuse. See+ :doc:`backup-recovery`.+ * - ``version_id`` is not the build you deployed+ - The target runs another shirudo build.++Limits+------++- Telemetry has no proof of origin. Root on a target, or anyone who can+ reach the collector with valid credentials, can send records in a+ target's name. Use :doc:`attest` for evidence.+- While the config cannot be verified, ``status`` uses only the runtime+ image's settings and the environment. While an activation is pending,+ it uses the pending config's settings only when that config is the one+ mounted. To keep keepalives arriving in those states, also set+ ``OTEL_EXPORTER_OTLP_ENDPOINT`` in ``/etc/shirudo/map-export.env``.+ The map export is refused in those states.+- The keepalive interval is 5 seconds after the previous run ends, not a+ fixed schedule. Size the alert for a missing keepalive to several+ intervals plus the 30-second lock wait.++Next steps+----------++- :doc:`read-status` to read what the keepalive carries.+- :doc:`/reference/formats/otlp` for the records on the wire.+- :doc:`/upatches/decoders` to give a map a decoder.+- :doc:`/reference/cli/upatch-map` and :doc:`/reference/cli/status` for+ every option.+- :doc:`attest` for evidence that the target cannot forge.diff --git a/Documentation/operate/troubleshooting.rst b/Documentation/operate/troubleshooting.rstnew file mode 100644index 00000000..f0fd801b--- /dev/null+++ b/Documentation/operate/troubleshooting.rst@@ -0,0 +1,523 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Troubleshoot by symptom+=======================++This page starts from what you see: a message a command prints, the+failure category of an upatch load or unload, or a status verdict. Each+entry says what the symptom means, what causes it and what to do. The+output shown was captured from the test VM.++:doc:`/reference/failure-categories` lists every category and exit+status. :doc:`/operate/read-status` explains the status report.++Before you begin+----------------++- On the target, ``shirudo`` means the binary on the runtime image,+ ``/run/shirudo/runtime/usr/bin/shirudo``, see+ :ref:`runtime-invocation`.+- Every message shirudo prints also goes to the journal under the+ identifier ``shirudo``. Read the messages of this boot, and the two+ ``init`` runs, with:++ .. code-block:: console++ target# journalctl -b -t shirudo+ target# journalctl -b -u shirudo-initrd.service -u shirudo.service++- ``upatch load`` and ``upatch unload`` print a JSON report with the+ category, the phase and the verifier log when you pass+ ``--report=-``, see :doc:`/reference/cli/upatch-load`.++Commands refused before they run+--------------------------------++On a production target every target command except ``init`` first+checks its runtime authority, the TPM and the config activation. A refusal prints ``shirudo: image state:`` and the error,+and the command exits 1 without doing anything.++``shirudo: image state: Permission denied``+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++.. code-block:: console++ target# /usr/local/bin/shirudo status+ shirudo: image state: Permission denied++Meaning+ The command has no runtime authority, or the TPM is not the one+ ``init`` bound.++Causes+ - You ran a copy of the binary other than the runtime image's, for+ example the one a package installed under ``/usr/bin``. The LSM+ refuses it the identity pin, which also counts as ``ObjGet``.+ - A shipped unit runs the host's installed binary because its+ drop-in is missing.+ - The message follows ``tpm: not the TPM init bound (attestation key+ name differs)``: the TPM that answers is not the TPM ``init`` bound+ this boot.++Action+ - Run ``/run/shirudo/runtime/usr/bin/shirudo``, see+ :ref:`runtime-invocation`.+ - Install the drop-ins for every unit, see :ref:`unit-drop-ins`.+ - A different TPM is an incident, see+ :doc:`/operate/incident-tampered`.++``shirudo: image state: Operation not permitted``+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Meaning+ The command carries a setting that a production target takes only+ from its authenticated images.++Causes+ - An argument starts with ``--keys-dir``, ``--cert`` or ``--tcti``.+ A target refuses all three, so ``attest verify`` and ``attest+ predict`` with ``--cert=`` run on the operator host, not on a+ target.+ - The message follows ``bootstrap override <name> is forbidden``: the+ environment sets one of ``SHIRUDO_KEYS_DIR``, ``SHIRUDO_TPM_TCTI``,+ ``SHIRUDO_TPM_OWNER_AUTH``, ``SHIRUDO_EVENTLOG_PATH``,+ ``SHIRUDO_EVENTLOG_PENDING_PATH``, ``SHIRUDO_INITRD_RELEASE`` or+ ``SHIRUDO_SYSROOT``. ``init`` refuses the same variables with+ ``init: authenticated image settings: Operation not permitted``.++Action+ - Drop the argument, or run the command on the operator host.+ - Unset the variable in your shell, or remove it from the+ environment file of the unit: ``/etc/shirudo/map-export.env`` or+ ``/etc/shirudo/bpm/environment``.++``shirudo: image state: Operation now in progress``+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Meaning+ A config activation is pending until the next reboot. Only+ ``status`` and ``image status`` run, and ``status`` reports+ ``reboot-pending``.++Causes+ - ``shirudo image update`` was interrupted after it recorded the+ pending selection.+ - ``init`` failed after it measured this boot's config, while it+ restored the archived upatches or bound the register. The journal+ shows ``image: activation is pending; further changes are blocked``+ for a re-run of ``init``.++Action+ Reboot. Nothing clears the pending state within the boot. See+ :ref:`status-reboot-pending`.++``shirudo: image state: Structure needs cleaning``+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Meaning+ The config PCR, the activation records and the mounted config+ disagree. ``status`` runs and reports ``tampered`` with the reason+ ``the selected config cannot be verified against its records``. Two+ other errors belong to the same state: ``Stale file handle`` when the+ activation record belongs to another TPM boot, and ``Key was rejected+ by service`` when the mounted config is not the selected one.++Causes+ - Something extended the config PCR after this boot's config+ measurement, either an attacker or other software that measures+ into the same PCR.+ - The TPM was reset without a reboot, for example by a resume from+ hibernation.+ - The config mount was replaced.++Action+ Do not retry. Handle the target as an incident, see+ :doc:`/operate/incident-tampered`, and reboot once you have the+ evidence. If other software extends the PCR, choose another config+ PCR, see :doc:`/operate/hardening`.++``image: waiting for another shirudo command to release the config operation lock``+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Meaning+ Every target command holds ``/var/lib/shirudo/config-update/lock``+ for its whole run. Your command waits for the one that holds it, and+ prints this message after one second. After 30 seconds it gives up+ with ``image: another shirudo command still holds the config+ operation lock /var/lib/shirudo/config-update/lock after 30 seconds``+ and ``shirudo: image state: Resource temporarily unavailable``.++Causes+ A long command runs, typically a timer service: a package update or+ tree sync against a slow registry, or a map export.++Action+ 1. See which shirudo services run:++ .. code-block:: console++ target# systemctl list-units 'shirudo-*'++ 2. Wait for the active one to finish, then run your command again.++``hardening: cannot lock process memory``+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Meaning+ Every ``shirudo`` and ``shirudo-build`` invocation locks its memory+ with ``mlockall`` before it dispatches a command. The lock failed and+ the command exited 1.++Causes+ The process has no ``CAP_IPC_LOCK`` and its memory-lock limit is too+ small: an unprivileged operator shell, a container or a unit without+ ``LimitMEMLOCK=infinity``.++Action+ Raise the limit in the shell (``ulimit -l unlimited`` as root) or+ set ``LimitMEMLOCK=infinity`` in the unit. The shipped units set it.++upatch load and unload failures+-------------------------------++Each failure ends in one category, which the JSON report of+``--report`` carries. The journal holds the messages, but not every+load failure names its category there, so pass ``--report`` when you+need it. Nothing changed on the target unless the entry says otherwise.++``tampered``, message ``chain_drift``+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++.. code-block:: console++ target# shirudo upatch load --expect-chain=0000000000000000000000000000000000000000000000000000000000000000 --report=- /mnt/shirudo-bundle/fixtures/shirudo-test-lifecycle.upatch+ upatch load: pre-flight refused (category: tampered, message: chain_drift) -- live chain c50b22ac27c5bb6a90ee5ff9b440fbbd5bb60b84a2aa7b395daec3f330886fcd != expected; re-status and re-issue with the refreshed value+ {"schema":1,"result":"failed","op":"upatch_load","phase":"pre_flight","errno":1,"errno_name":"EPERM","category":"tampered","message":"pre-flight check failed",...}++Meaning+ The live register is not the value you passed with+ ``--expect-chain``. The command stopped before it loaded anything.+ ``tampered`` also ends a load whose pre-flight finds the ``lsm/bpf``+ link unpinned (message ``lsm_detached``) or the ``.bpf`` keyring+ different from the one ``init`` sealed.++Causes+ - Something changed the register after you read the value: another+ operator, or a timer that installed or upgraded a package or+ applied a tree operation.+ - Something changed the register outside shirudo.++ The target cannot tell you which, and its own report is not proof.++Action+ Do not repeat the command with the value the message prints. Keep the+ journal and the eventlog, and follow+ :doc:`/operate/incident-tampered`. TPM-signed evidence, checked+ against the events you expect, decides whether the change was yours.++``version_mismatch``+~~~~~~~~~~~~~~~~~~~~++.. code-block:: console++ target# shirudo upatch load --expect-version-id=0000000000000000000000000000000000000000000000000000000000000000 --report=- /mnt/shirudo-bundle/fixtures/shirudo-test-lifecycle.upatch+ upatch load: version mismatch -- operator expects 0000000000000000000000000000000000000000000000000000000000000000, target is 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0; redeploy a matching shirudo or pass --no-version-check+ {"schema":1,"result":"failed","op":"upatch_load","phase":"pre_flight","errno":1,"errno_name":"EPERM","category":"version_mismatch","message":"SHIRUDO_VERSION_ID mismatch (operator vs target)",...}++Meaning+ The target runs a shirudo build other than the one+ ``--expect-version-id`` names. The check runs first, before anything+ else.++Causes+ - The target was not upgraded, or was upgraded to another build.+ - The id you expect comes from a binary built on another host. The+ identifier covers the build configuration, so two builds of one+ commit on different hosts differ, see :doc:`/operate/upgrade`.++Action+ 1. Read the identifier of the target:++ .. code-block:: console++ target# shirudo version --version-id+ 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0++ 2. Compare it with the build you deployed to this target. If the+ target runs the wrong build, upgrade it. If your expectation came+ from another host's build, record the target's identifier as the+ expected one.++``keyring_missing``+~~~~~~~~~~~~~~~~~~~++.. code-block:: console++ target# shirudo upatch load --report=- /mnt/shirudo-bundle/fixtures/shirudo-test-foreign.upatch+ BPF_PROG_LOAD (signed loader): Required key not available+ loader verifier log:+ signature verification failed: -126++ {"schema":1,"result":"failed","op":"upatch_load","phase":"signed_loader_load","errno":126,"errno_name":"ENOKEY","category":"keyring_missing","message":"BPF_PROG_LOAD of signed loader failed",...}++Meaning+ The kernel found no key in the ``.bpf`` keyring that verifies the+ loader's signature (``ENOKEY``). The artifact is signed by a key the+ target does not trust. In the pre-flight phase the same category+ means that no keyring was recorded this boot: ``no trust anchor+ frozen this boot``.++Causes+ - The artifact was signed with another operator key.+ - The signing key is not in the target's trusted set. A key enters+ the ``.bpf`` keyring only at boot, from the runtime image and the+ config selected for that boot.+ - The signing key was revoked.++Action+ 1. Print the fingerprints the target trusts:++ .. code-block:: console++ target# shirudo keys++ 2. Print the fingerprint of the key that signed the artifact, on the+ operator host:++ .. code-block:: console++ operator$ shirudo keys --keys-dir=<keys-dir>++ 3. Compare the ``SPKI fingerprint`` of the operator's certificate+ with the members of the target's ``Trusted set``. Sign with a+ trusted key, or see :doc:`/operate/keys` for how a key becomes+ trusted.++``<keys-dir>`` is the directory that holds the signing key the artifact+was built with.++``payload_mismatch``+~~~~~~~~~~~~~~~~~~~~++.. code-block:: console++ target# shirudo upatch unload --report=- /mnt/shirudo-bundle/fixtures/shirudo-test-basic-mismatch.unload.upatch+ loaded signed loader: prog_fd=10 keyring=420195959 sig=4853B insns=165 data=2808B+ upatch unload: payload_mismatch -- the upatch loaded under 'shirudo-test-basic' is not what the directive expects; refusing+ upatch unload failed: name=shirudo-test-basic phase=pin category=payload_mismatch err=1 (Operation not permitted) message=loaded payload does not match directive+ {"schema":1,"result":"failed","op":"upatch_unload","phase":"pin","errno":1,"errno_name":"EPERM","category":"payload_mismatch","message":"loaded payload does not match directive",...}++Meaning+ The unload directive is signed for one payload, and the upatch loaded+ under that name has another. The upatch stays loaded.++Causes+ - The directive was built for another version of the upatch, for+ example before a package upgrade replaced it.+ - The payload record of the loaded upatch cannot be read, which the+ journal reports as ``cannot read the payload recorded for``.++Action+ 1. Read the payload digest of the loaded upatch:++ .. code-block:: console++ target# shirudo upatch get <name>++ 2. Build a directive for that payload on the operator host:++ .. code-block:: console++ operator$ shirudo build --unload <name> --payload-sha256 <payload> --keys-dir <keys-dir> -o <name>.unload.upatch++``<name>`` is the upatch name, ``<payload>`` the 64-character digest+from the ``Payload:`` line, and ``<keys-dir>`` the directory of a trusted+signing key.++``attach_target_missing``+~~~~~~~~~~~~~~~~~~~~~~~~~++Meaning+ The kernel has no attach point where the upatch's metadata names one:+ a kprobe function, a module, or the binary of a uprobe. The journal+ shows ``attach prog <n> (<kind> <target>): No such file or+ directory``, or ``uprobe target verification failed+ (attach_target_missing)``. Nothing stays loaded. ``upatch load`` exits+ 2 for this category.++Causes+ - The function does not exist in the running kernel, or its module is+ not loaded.+ - The binary of a uprobe is not at the path the upatch names.+ - The upatch was built for another kernel.++Action+ Check the attach point on the target, load the module first if the+ upatch needs one, or ship a upatch built for this kernel.++``attach_scope_mismatch``+~~~~~~~~~~~~~~~~~~~~~~~~~++Meaning+ The kernel created the link, but not at the site the metadata names,+ so shirudo refused to pin it (``EXDEV``). The journal shows ``attach+ prog <n> (<kind> <target>): the link is not at the site the metadata+ names``.++Causes+ The command ran in a namespace other than the host's initial ones: a+ ``cgroup_skb`` link not at the root cgroup, a ``netfilter`` link in+ another network namespace, a kprobe at another function or offset.++Action+ Run the load from the host's initial namespaces, not from a container+ or from a unit with private namespaces.++``verifier_rejected``+~~~~~~~~~~~~~~~~~~~~~++Meaning+ The kernel rejected the payload, or the signed loader failed to load+ it. The journal shows ``loader returned error: <n>`` and the loader's+ runtime log, or ``BPF_PROG_TEST_RUN:`` with the error. The report+ carries the log in ``verifier_log``.++Causes+ - The upatch was built against another kernel's BTF, and a CO-RE+ relocation or an attach target does not resolve on this kernel.+ - The kernel lacks a helper, kfunc or program type the payload uses.++Action+ Read ``verifier_log`` in the report. Rebuild the upatch against the+ target kernel's ``vmlinux.h``, or ship a version for this kernel.++``kernel_abi_unsupported``+~~~~~~~~~~~~~~~~~~~~~~~~~~++Meaning+ The kernel lacks the signed-loader interfaces shirudo requires. The+ pre-flight prints ``upatch: pre-flight refused (category:+ kernel_abi_unsupported, message: <detail>)``, where the detail names+ the missing piece, for example ``struct bpf_map.excl_prog_sha is+ missing; boot a Shirudo-patched kernel``. The same category ends a+ load whose attach kind the kernel does not support.++Causes+ The target booted a kernel without the required ABI.++Action+ Boot a kernel that meets :doc:`/operate/system-requirements`.++``eventlog_full``+~~~~~~~~~~~~~~~~~++Meaning+ The next record would take the eventlog past ``eventlog.max_bytes``.+ The command refused before it loaded or extended anything:+ ``upatch load: eventlog /var/lib/shirudo/eventlog would exceed+ eventlog.max_bytes=<n>; refusing -- no load, no extend``.++Causes+ The eventlog grows by one record per boot, load, unload, revocation+ and tree operation, and shirudo never rotates it.++Action+ Raise ``eventlog.max_bytes`` in a signed config and activate it, see+ :doc:`/reference/formats/configuration`. Keep the cap below 8 MiB:+ every reader of the eventlog fails on a larger log.+ :doc:`/operate/backup-recovery` covers the eventlog's lifetime.++Boot and init+-------------++``init: pre-flight failed``+~~~~~~~~~~~~~~~~~~~~~~~~~~~++Meaning+ One of the checks ``init`` runs before it changes anything failed.+ ``init`` prints a table with ``FAIL`` and a detail for each failed+ check, then ``init: pre-flight failed (<failed>/<total> checks)``.+ In the initrd the table is in the journal of+ ``shirudo-initrd.service``. A passing run looks like this:++ .. code-block:: console++ target# shirudo init --check-only+ pre-flight checks:+ root OK+ bpf_lsm_active OK+ bpffs_supported OK+ signed_loader_kernel_abi OK+ cert_on_disk OK+ cert_algorithm OK+ cert_kernel_support OK+ kernel_keyring OK+ embedded_loader OK+ tpm2_reachable OK: TCTI override: device:/dev/tpmrm0+ 10/10 passed (0 failed)++Causes+ The check names the requirement that is missing: root, the BPF LSM+ in the kernel's active LSM list, bpffs, the signed-loader ABI, the+ certificate and its algorithm, the kernel keyring, the embedded+ loader or the TPM.++Action+ Fix the requirement, see :doc:`/operate/system-requirements`, and+ reboot. :doc:`/operate/initialize` describes the init runs.++``init: boot-restore failed; further changes and attestation remain blocked``+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Meaning+ ``init`` could not load one of the archived upatches, preceded by+ ``boot-restore: failed to apply <file>``. It stops at the first+ failure. The upatches it loaded before stay loaded, and the register+ is not bound. The config activation stays pending, so every command+ except ``status`` and ``image status`` refuses until the next boot,+ and ``status`` reports ``reboot-pending``.++Causes+ The archived upatch does not load on this kernel, typically after a+ kernel upgrade. The load failure before this message carries its+ category.++Action+ A reboot restores the same archive and fails the same way.+ :doc:`/operate/backup-recovery` describes what works and what does+ not.++Status verdicts+---------------++:ref:`status-verdicts` explains every verdict in full. The short form:++``tampered``+ Handle as an incident, see :doc:`/operate/incident-tampered`. Do not+ retry and do not reboot before you have the evidence.++``reboot-pending``+ A config activation is pending. Reboot.++``degraded``+ Enforcement is up but there is no register to check. Read the+ ``Chain`` line of the report, see :ref:`status-degraded`.++``lsm-off``+ Enforcement did not come up this boot and the target is unprotected.+ Read the journal of ``shirudo-initrd.service``, fix the cause and+ reboot, see :ref:`status-lsm-off`.++Next steps+----------++- :doc:`/reference/failure-categories` for every category and exit+ status.+- :doc:`/operate/incident-tampered` for a ``tampered`` refusal or+ verdict.+- :doc:`/operate/read-status` for the status report.diff --git a/Documentation/operate/upgrade.rst b/Documentation/operate/upgrade.rstnew file mode 100644index 00000000..3eb48138--- /dev/null+++ b/Documentation/operate/upgrade.rst@@ -0,0 +1,305 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Upgrade shirudo and the kernel+==============================++The trusted ``shirudo`` binary lives in the runtime image, and the UKI+pins that image's root hash. A new shirudo build therefore takes a new+runtime image, a new initrd, a new UKI and a reboot. A new kernel takes a+new initrd, a new UKI and a reboot, and the archived upatches must load+on it. This page covers both.++Config images and upatch packages change while the target runs and need+no reboot:++.. list-table::+ :header-rows: 1+ :widths: 30 40 30++ * - Change+ - What you rebuild+ - Takes effect+ * - shirudo binary+ - Runtime image, UKI bootstrap file, initrd, UKI+ - After a reboot+ * - Kernel+ - Initrd, UKI+ - After a reboot+ * - Config image+ - Config image, activated with ``shirudo image update``+ - At once+ * - Packages of upatches+ - Packages, published to a registry+ - Within a minute, through the timers++:doc:`/operate/deliver-packages` covers packages, and+:doc:`/reference/cli/image` covers ``image update``.++Before you begin+----------------++- A target set up as described in :doc:`/operate/boot-integration`, and+ the files you built for it: ``runtime.conf``, the BPF signing+ certificate and the config signing key.+- A root shell on the target. On the target, ``shirudo`` means the+ runtime image's binary, ``/run/shirudo/runtime/usr/bin/shirudo``. See+ :ref:`runtime-invocation`.+- A canary target with the same packages as the fleet, to try a new+ kernel on first.++Version ID+----------++Every build of shirudo carries a version ID. ``shirudo version`` prints+it after the release:++.. code-block:: console++ target# shirudo version+ shirudo (58d3fa7-dirty-rc0, "Social BPF Coding")+ version-id: 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0++The build computes the ID as a SHA-256 over the source revision, a+``-dirty`` mark when the tree has uncommitted changes, and a digest of+``config.mk`` and ``Makefile.shirudo``. The revision comes from git, or+from the ``VERSION`` file outside a git checkout. ``config.mk`` records+the library flags of the build host, so two builds of one commit on+different hosts get different IDs, and an operator package built on+another host than the target package carries another ID. The ID does not+cover the compiler or the contents of the libraries.++``shirudo upatch load`` and ``upatch unload`` compare the ID with+``--expect-version-id`` and refuse with ``version_mismatch`` when it+differs. In this example the path of the artifact is shortened:++.. code-block:: console++ target# shirudo upatch load --expect-version-id=0000000000000000000000000000000000000000000000000000000000000000 --report=- shirudo-test-lifecycle.upatch+ upatch load: version mismatch -- operator expects 0000000000000000000000000000000000000000000000000000000000000000, target is 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0; redeploy a matching shirudo or pass --no-version-check+ {"schema":1,"result":"failed","op":"upatch_load","phase":"pre_flight","errno":1,"errno_name":"EPERM","category":"version_mismatch","message":"SHIRUDO_VERSION_ID mismatch (operator vs target)",...}++Take the expected ID from the binary in the runtime image, never from the+operator's own binary. After an upgrade, update the ID that your+automation passes.++Upgrade shirudo+---------------++Build on the operator host+~~~~~~~~~~~~~~~~~~~~~~~~~~++1. Build the new static target binary with ``make target``, or take+ ``/usr/bin/shirudo`` from the new target package.++2. Record its version ID:++ .. code-block:: console++ operator$ ./shirudo-target version --version-id++ Like every shirudo command, it locks its memory first, so it needs+ ``CAP_IPC_LOCK`` or a large enough ``RLIMIT_MEMLOCK``.++3. Build the new runtime image under a prefix of its own:++ .. code-block:: console++ operator$ shirudo-gen-runtime --binary ./shirudo-target \+ --bootstrap-conf runtime.conf --cert <bpf-cert> \+ --config-cert <config-keys-dir>/cert.der --output runtime-2 \+ --keys-dir <config-keys-dir> --unit-output runtime-service-2.conf++ Use the same ``runtime.conf`` and certificates as before.+ ``<bpf-cert>`` is the primary BPF signing certificate and+ ``<config-keys-dir>`` holds the config signing key.++4. Write a UKI bootstrap file for the new image, ``uki-bootstrap-2.conf``:++ .. code-block:: ini++ runtime.image = /sysroot/var/lib/shirudo-runtime/runtime-2+ runtime.root_hash = <runtime-2-root-hash>++ ``<runtime-2-root-hash>`` is the content of ``runtime-2.roothash``.+ The next step explains the path.++Stage and boot on the target+~~~~~~~~~~~~~~~~~~~~~~~~~~~~++shirudo has no command that installs a runtime image on a running+target, and the seal refuses root's new entries and writes under+``/var/lib/shirudo``. Stage the image elsewhere, on the file system that+holds ``/var/lib/shirudo``, which the initrd mounts before init runs.+The initrd reads the root file system below ``/sysroot``, so the UKI+bootstrap file names the image by that path. The test suite does not+cover this layout. Remove a staged image only when no UKI you keep names+it.++1. Copy the new runtime image to the target:++ .. code-block:: console++ target# install -d -m 0700 /var/lib/shirudo-runtime+ target# install -m 0644 runtime-2.img runtime-2.verity runtime-2.roothash \+ /var/lib/shirudo-runtime/++2. Install the new target package. The initrd embeds its+ ``/usr/bin/shirudo``, which must be the same build as the binary in+ ``runtime-2``.++3. For a dynamically linked binary, install ``runtime-service-2.conf`` as+ ``/etc/systemd/system/shirudo.service.d/runtime.conf`` and update the+ other drop-ins from :ref:`unit-drop-ins` to its invocation. For the+ static binary the drop-ins stay as they are.++4. Generate the initrd with the new bootstrap file:++ .. code-block:: console++ target# shirudo-gen-initrd --bootstrap-conf uki-bootstrap-2.conf \+ --cert <bpf-cert> --kver <kernel-release> \+ --output /boot/initrd-shirudo-<kernel-release>-2.img+ target# shirudo-gen-initrd --check /boot/initrd-shirudo-<kernel-release>-2.img++5. Build and sign a UKI from the kernel, this initrd and the same command+ line, and install it as the default boot entry. Keep the previous UKI+ as a second entry, and keep the previous runtime image where its UKI+ expects it.++6. Reboot:++ .. code-block:: console++ target# systemctl reboot++Verify the upgrade+~~~~~~~~~~~~~~~~~~++1. Check that the runtime binary is the new build:++ .. code-block:: console++ target# shirudo version --version-id++ The ID must be the one you recorded on the operator host.++2. Check init as described in :doc:`/operate/initialize`:+ ``shirudo status`` reports ``ok`` and ``Bound in: initrd``, and+ ``shirudo image status`` reports ``"pending":false`` and+ ``"consistent":true``.++3. Update your verifiers. The new initrd and UKI change the PCR values+ that init records when it binds the register, which a verifier pins+ with ``--expect-bind-pcr``. :doc:`/operate/attest` describes how to+ record them.++When the new build fails to initialize, boot the previous UKI and read the+journal of the failed boot.++Upgrade the kernel+------------------++The runtime image does not depend on the kernel, so a kernel upgrade+keeps the image and the UKI bootstrap file. The archived upatches are+the risk: init restores every one of them at boot, and a upatch that+does not load on the new kernel stops the restore. Check them on a+canary target before you upgrade the fleet.++1. Confirm that the new kernel meets :doc:`/operate/system-requirements`.++2. Boot the new kernel on a canary target with steps 4 to 8, and check+ it as described in :doc:`/operate/initialize`.++3. On every target, remove the upatches that do not load on the new+ kernel before you reboot into it. Uninstall such a package:++ .. code-block:: console++ target# shirudo bpm uninstall <package>++ Retract a upatch that the upatch tree manages with a delete operation,+ as :doc:`/operate/deliver-packages` describes. Unload a upatch that+ you loaded by hand with its unload directive.++4. Install the new kernel package.++5. Generate the initrd for the new kernel with the bootstrap file of the+ running image:++ .. code-block:: console++ target# shirudo-gen-initrd --bootstrap-conf <uki-bootstrap-file> \+ --cert <bpf-cert> --kver <new-kernel-release> \+ --output /boot/initrd-shirudo-<new-kernel-release>.img+ target# shirudo-gen-initrd --check /boot/initrd-shirudo-<new-kernel-release>.img++ Do not use an initrd that your distribution's kernel hooks generate:+ they run dracut with the host configuration and without the UKI+ bootstrap file.++6. Build and sign a UKI from the new kernel, this initrd and the same+ command line. Install it as the default entry and keep the previous+ kernel's UKI as a second entry.++7. Reboot:++ .. code-block:: console++ target# systemctl reboot++8. Check init as described in :doc:`/operate/initialize`, and update the+ PCR values your verifiers pin.++.. _boot-restore-lockout:++Recover from a restore failure after a kernel upgrade+-----------------------------------------------------++When an archived upatch does not load on the new kernel, init stops the+restore and the config activation stays pending. ``status`` reports+``reboot-pending``, and commands other than ``status`` and+``image status`` fail with+``shirudo: image state: Operation now in progress``. A reboot into the+same kernel repeats the failure. ``bpm uninstall`` and ``upatch unload``+are refused in this state, and the seal stops root from removing the+archived file. shirudo has no command that leaves this state on the new+kernel.++What works is the previous kernel, on which the upatch still loads:++1. Before you reboot, read the name of the failed upatch in the journal:++ .. code-block:: console++ target# journalctl -b -u shirudo-initrd.service++ The line is ``boot-restore: failed to apply <file>``.++2. Boot the previous kernel's UKI from the boot menu. Its runtime image+ must still be where its UKI bootstrap file names it.++3. Check that init completed, as described in :doc:`/operate/initialize`.++4. Uninstall the package that holds the upatch, retract it from the+ upatch tree, or unload it with its unload directive. For a package:++ .. code-block:: console++ target# shirudo bpm uninstall <package>++5. Boot the new kernel's UKI and check init again.++Without a previous kernel that boots, no supported procedure removes the+upatch.++Next steps+----------++- :doc:`/operate/initialize` for the checks after every boot.+- :doc:`/operate/attest` to update what verifiers expect.+- :doc:`/operate/backup-recovery` for the state to keep across upgrades.diff --git a/Documentation/operations.rst b/Documentation/operations.rstdeleted file mode 100644index 3aae6c65..00000000--- a/Documentation/operations.rst+++ /dev/null@@ -1,499 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--Operating a target-==================--This guide is for whoever runs targets: what to watch, what the-conditions and the categories mean, how to upgrade shirudo and the-kernel underneath it, how to take a target out of service, what to back-up, and how to recover from the states shirudo refuses to paper over.-The `getting-started <getting-started.rst>`__ document brings a target-up; the `initrd <initrd.rst>`__ document describes the production-configuration; this one is about the time after that.--Every target uses runtime and signed config images. See-`config-images <config-images.rst>`__ for generation, boot and activation.-Writable state keeps its seal xattrs; BPF upatches still require signed loaders.-Commands here denote the configured runtime interpreter and binary invocation.--1) The moving parts----------------------A target runs no daemon. Everything is a one-shot command started by-systemd:--.. list-table::- :header-rows: 1- :widths: 36 64-- * - Unit- - Runs- * - ``shirudo-initrd.service``- - ``shirudo init`` in the initrd, once per boot; enrols the- certificate, attaches the LSM, restores the archived upatches,- binds the register. Only present in an initrd the dracut- module built.- * - ``shirudo.service``- - ``shirudo init`` from the root file system, before- ``sysinit.target``: checks the image-backed initialization and- adopts its pending eventlog record.- * - ``shirudo-keepalive.timer``- - ``shirudo status --otel --include-system`` every 5 seconds: the- conditions below and the system facts as an OTLP keepalive.- * - ``shirudo-map-export.timer``- - ``shirudo upatch map --all`` every 5 seconds, with the export- destination from ``map-export.env``: decoded map snapshots as- OTLP logs and metrics.- * - ``shirudo-bpm-repo-update.timer``- - ``shirudo bpm repo update`` at boot: refreshes the signed- repository indexes.- * - ``shirudo-bpm-tree-sync.timer``- - ``shirudo bpm tree sync`` every 60 seconds when- ``/etc/shirudo/bpm/upatch-tree.conf`` exists.--Persistent export settings and tree/repository inputs come from the signed-config image. Host paths below describe their layout; editing a host copy-does not change the selected config. The keepalive and map-export units read ``/etc/shirudo/map-export.env``-and the ``map_export.*`` keys of ``/etc/shirudo/shirudo.conf``; the-`telemetry <telemetry.rst>`__ document covers what they send and how-to receive it. ``shirudo config`` prints every effective setting with-a comment.--Every ``shirudo`` and ``shirudo-build`` invocation locks its current and future process-mappings before command dispatch. The shipped services set-``LimitMEMLOCK=infinity``. Manual invocations need ``CAP_IPC_LOCK`` or-a sufficiently large memory-lock limit; a failure is logged and exits-with status 1 before the command runs. Future allocations and stack-growth also consume the locked-memory allowance. The locks end on-process exit or exec; the operator helper reapplies memory locking-before its own command dispatch.--State lives in two places. ``/var/lib/shirudo`` is persistent:-``keys/`` (the primary certificate, the trusted set with its vouches,-the revoked certificates), ``eventlog``, the ``upatches/`` archive-``init`` restores at boot, ``bpm/`` (indexes, cached packages, tree-state) and ``locks/``. The seal protects labelled files against the-operations listed in the `threat model <threat-model.rst>`__. New inodes-inherit the label during creation when their parent has a cached seal-mark; Shirudo's writers hold the parent directory open while creating.-This does not exclude every foreign directory entry or revoke existing-writable references.-``/run/shirudo`` is per boot: the private bpffs with the-LSM pins, the frozen identity map and the pending init record between-the initrd run and the root's.--2) Watching a target-----------------------``shirudo status`` is the local view and ``shirudo status --json`` the-machine-readable one. The fields that matter day to day:--``mode``- ``production`` (certificate in the kernel's bpf keyring, enforcement- up) or ``inactive`` (enforcement has not been initialized).--``tpm.reachable``- Whether a TPM answered on the TCTI, which the human report names on- its ``TPM:`` line.--``tpm.bound_in``- ``initrd`` or ``root``: where the register was bound. Production- means ``initrd``.--Conditions- Five, each ``OK``, ``WARN`` or ``ALERT`` with a detail:-- .. list-table::- :header-rows: 1- :widths: 22 78-- * - Condition- - Meaning when not ``OK``- * - ``LsmAttached``- - ``ALERT``: the ``lsm/bpf`` link is not pinned; enforcement- is off and the target has not been initialised this boot.- * - ``KeyringSealed``- - ``WARN`` before ``init``; ``ALERT`` when- the live keyring is not the one ``init`` froze into the- identity map or is gone (every load refuses ``tampered``).- The only supported trust anchor is the kernel BPF keyring.- * - ``ChainIntact``- - ``ALERT`` when replaying this boot's eventlog does not- reproduce the live register: something extended it that- shirudo did not record.- * - ``TpmMeasured``- - ``WARN`` when no register is bound this boot- (``degraded``) or no TPM answers; the detail says which.- * - ``ConfigActive``- - ``WARN`` while a config activation is pending until the next- reboot (``reboot-pending``); ``ALERT`` when the config PCR,- the activation records and the mounted config disagree, or- the records belong to another TPM boot (``tampered``).--``config``- The selected or pending config's ``root_hash``, whether its- ``activation_pending`` and, when its records cannot vouch for it,- the ``error``. Every other target command refuses in those states;- ``status`` runs in them so that the keepalive reports them. It then- uses the pending config's export settings only when that is the- config mounted, and otherwise only the runtime image's settings and- the environment, so a keepalive needs ``OTEL_EXPORTER_OTLP_ENDPOINT``- in ``map-export.env`` to reach a collector in such a state.--``keyring_serial`` and ``keyring_serial_pinned``- The live keyring and the one frozen at ``init``; they match on a- healthy target.--``certs``, ``certs_enrolled``, ``certs_unvouched``, ``certs_revoked``- The trusted set on disk (each member's digest, fingerprint and- whether it is the primary), how many keys the bpf keyring holds- right now, how many files under ``keys/trusted`` lack a valid- vouch and are therefore not members, and how many certificates are- revoked. The set and the keyring part when a certificate was added- since the boot (the keyring learns of it at the next boot) or- revoked (the keyring lost it at once); the `key-lifecycle- <key-lifecycle.rst>`__ guide covers both.--``register_rebound``, ``init_records``- Two init records for one TPM reset means the register was bound- again, which only a TPM reset should allow.--``tamper_attempts``- What the named guard points refused this boot: ``total`` and one counter- per point of refusal under ``counters`` (``LoadNotLoader``,- ``LoadUnsigned``, ``LoadUnverified``, ``LoadKeyringKind``,- ``LoadKeyring``, ``MapFdWrite``, ``PinRename``,- ``BpffsUmountAbove``, ``SealWrite``, ``SealPtrace`` and the rest,- named in ``util/tamper.c`` like the condition types), or- ``null`` before ``init`` has run. The human report lists the- counters that are not zero with what each means under ``Tamper- attempts``. A count is an attempt that was refused, so the- conditions stay ``OK``; it is the operator's cue to look at the- journal and the host. Image-only device, parent-mount and process- refusals are not counted; zero does not mean no attempts occurred.--The same conditions leave the target every five seconds as the OTLP-keepalive, so a collector sees a target go ``WARN`` or ``ERROR``, or go-silent, without anyone logging in.--Logs go to the journal under the ``shirudo`` identifier::-- journalctl -t shirudo- journalctl -b -u shirudo-initrd.service -u shirudo.service--Four events are logged at audit priority and are worth forwarding:-``genkey`` creating signing material (operator), ``upatch load`` with-the upatch name, the keyring used and the program count, ``upatch-load`` or ``unload`` measured with the register value afterwards, and-an ``upatch unload`` that found nothing to unload. Every refusal is-logged at error priority with its category.--The target's own account proves nothing to anyone else. The operator's-health check is ``shirudo attest`` on the target and ``shirudo attest-verify`` on the operator against the value ``shirudo attest predict``-computes from what was installed, with a fresh nonce each time; the-`tpm <tpm.rst>`__ document describes the loop and what each refusal-means.--3) Upgrading shirudo-----------------------Build a new runtime image containing the new binary and its complete library-closure. Update the runtime root in authenticated bootstrap configuration,-install the generated service drop-in and rebuild the UKI with its initrd.-Reboot when the operator chooses. The old runtime remains authorized for its-boot; replacing a host-root binary does not replace the trusted executable.--A new runtime or config verification certificate requires this boot rollout.-Config and signed upatch updates remain live. Missing runtime files or an-incorrect authenticated root stop initialization rather than choosing a-host-root fallback. Installing a target package alone does not provision the-images or start enforcement.--The authenticated NV-writer upgrade also requires updating the operator-verifier: the write policy and certified index Name change, and old-public-write-policy evidence is rejected. Install the updated-target profile and rebuild the initrd before rebooting. No secret file-needs migration or backup: the TPM creates the RSA writer from a fresh-input at each boot, and Shirudo freezes that nonsecret input and the-public modulus. The kernel needs the ``tpm_command`` LSM hook to-reject untrusted extensions to Shirudo's NV index; it does not block-TPM signing. The TPM must create RSA-3072 RSASSA/SHA-256 keys. There-is no separate mutable binding-attempt record.---4) Kernel updates--------------------A new kernel package makes dracut build an initrd for it, and the-shirudo module includes itself whenever a certificate is installed, so-the production configuration carries over without action. The kernel-parameters ``bpf.keyring_unsealed=1 dm_verity.keyring_unsealed=1`` live in the boot loader's-configuration, which the installer wrote once.--The upatches do not carry over by themselves. ``init`` restores the-archived set on every boot, and a upatch built for another kernel-generation fails its load with ``btf_mismatch`` or-``verifier_rejected``; boot-restore is all or nothing, so one such-upatch leaves the target with the LSM up, nothing loaded and no-register bound (``TpmMeasured`` warns, ``status`` says-``degraded``). Before rebooting into a new kernel generation,-either uninstall the packages that do not cover it or make sure the-tree the node follows has selectors that do: an operation whose-``kernel_release_prefix`` or ``kernel_build_id`` no longer matches is-not applied again, but a upatch the node already loaded stays archived-until a ``delete`` removes it. The `upatch <upatch.rst>`__ guide-covers selectors. After the reboot, ``shirudo init`` reports the-upatch that failed; remove it (``bpm uninstall``, or the tree's-``delete``) and re-run ``init``, which then binds the register.--5) Taking a target out of service------------------------------------Enforcement cannot be switched off at runtime, by design: the LSM-links are held by pins that nothing but shirudo can remove and that-shirudo has no command to remove. Decommissioning is therefore a-reboot with shirudo gone from the boot path::-- sudo shirudo bpm uninstall <package> # every installed package- sudo systemctl disable --now shirudo-keepalive.timer \- shirudo-map-export.timer shirudo-bpm-repo-update.timer \- shirudo-bpm-tree-sync.timer- sudo systemctl disable shirudo.service- sudo apt remove shirudo-target # or dnf; removes the dracut module- sudo rm /etc/default/grub.d/shirudo.cfg && sudo update-grub # or the equivalent- sudo dracut --force- sudo reboot- sudo rm -rf /var/lib/shirudo /etc/shirudo--The package's removal scripts disable the units; the initrd must be-rebuilt without the module so that ``shirudo-initrd.service`` does not-run, and the kernel parameter should go so that the bpf keyring is-sealed empty again at boot. The state directory can only be removed-after the reboot: while the seal is attached, its labels stop root-from deleting it. An unload before the reboot is optional but-measured, which keeps the last evidence of the node complete.--6) Backup and restore------------------------Back up ``/var/lib/shirudo`` and ``/etc/shirudo``:--* ``keys/`` is replaceable from the operator: the primary, the- trusted set with its vouches and the revoked certificates. The- signing keys are never on a target.-* ``eventlog`` is the node's measurement history across boots, append- only. Evidence and verification work per boot, so losing it costs- the history, not the security of the running boot; keep it where- audit records go.-* ``upatches/`` and ``bpm/`` are what ``init`` restores at boot and- what the tree sync continues from. They are also recoverable from- the registry by reinstalling.-* ``/etc/shirudo`` holds the configuration, the repository- registrations and their certificates, the tree configuration and the- node labels.--Restoring onto a reinstalled target is a matter of putting the files-back before ``shirudo init`` runs; the labels are reapplied by ``init``.-Restoring an ``eventlog`` whose last boot is not this one is harmless:-readers work from this boot's ``init`` record on. Restoring tree-state from another node is not: the sequence it continues from belongs-to that node.--The eventlog grows by one line per init, load, unload and tree-operation and is never rotated by shirudo. ``eventlog.max_bytes`` in-``shirudo.conf`` caps it (``0``, the default, is unlimited); at the-cap every state-changing operation refuses ``eventlog_full`` before it-does anything, so the register and the log never diverge. Because the-file is sealed, nothing but shirudo can truncate or rotate it while-enforcement is up, and shirudo has no command to; archive it at-reinstall time, and size the cap to the lifetime of the installation.--7) Recovering----------------``tampered``- The register, the keyring or the pins are not what the operation- expected. Nothing was changed. It is also what a legitimate- concurrent operator produces, so refresh the state (``shirudo- status``, the eventlog, the journal) before deciding; never retry- the same input blind. A register the eventlog cannot explain or a- keyring that is not the frozen one is an incident; a reboot- restores a clean boot and the evidence of the bad one is in the- eventlog, the journal and whatever the TPM certified before.--``degraded`` and ``TpmMeasured`` warning- ``init`` attached the LSM but did not bind the register: a- boot-restore failure (section 4) or a TPM that could not be- reached, which the ``TpmMeasured`` detail tells apart. The journal of ``shirudo-initrd.service`` or- ``shirudo.service`` names the step. Fix the cause and re-run- ``shirudo init``; it is idempotent and completes what it can.--The register is gone before the next reboot- A process with the owner authorisation undefined the NV index, or- the TPM was reset without a reboot (hibernation does that). Every- extension fails ``tpm_error`` and ``init`` refuses to bind again- before the next TPM reset, except in the hibernation case, which- the reset count on the record lets ``init`` tell apart. Reboot,- and read the eventlog of the boot it happened in.--Initialization cannot enroll the BPF keys- Check both enrollment boot parameters, authenticated runtime settings and- selected image files. A sealed empty BPF keyring is an error. Read the- journal of ``shirudo-initrd.service`` and verify the UKI was regenerated.- Shirudo cannot open an already sealed keyring at runtime.--``certs_unvouched`` is not zero- A config signer certificate lacks a valid vouch. Prepare the certificate- and vouch on the operator and deliver them in the intended signed config.- Invalid config trust material is refused before activation. New signer- enrollment requires reboot; see `key-lifecycle <key-lifecycle.rst>`__.--A key is compromised- Deliver a signed config containing its revocation record. Activation- removes the live key and purges its upatches. A node that has not received- the config still trusts the key. Require the intended config root in- attestation. Local ``keys revoke`` is disabled.--A pending record lingers- ``/run/shirudo/eventlog.pending`` is the initrd run's record until- the root's ``init`` appends it. One that remains after boot means- ``shirudo.service`` did not run or could not append; its journal- says why. Loads still work meanwhile, since the readers treat the- pending record as part of this boot's log.--``shirudo init --check-only`` runs the pre-flight without touching-anything and is the first thing to run on a target that misbehaves.--8) Categories and exit status--------------------------------Every ``upatch load`` and ``unload`` ends in one category, in the-report (``--report``) and in the journal. The commands exit ``0`` on-success, ``1`` on any refusal or failure and ``2`` on a usage error;-``shirudo init`` exits ``1`` when the pre-flight fails or a step does.--.. list-table::- :header-rows: 1- :widths: 26 44 30-- * - Category- - Meaning- - Action- * - ``ok``- - The operation completed and was measured.- - None.- * - ``init_prereqs_missing``- - A pre-flight check failed; the message names each.- - ``shirudo init --check-only``; fix what it lists.- * - ``kernel_abi_unsupported``- - The kernel lacks the signed-loader ABI.- - A current upstream kernel.- * - ``keyring_missing``- - No trust anchor is frozen this boot: ``init`` has not run.- - ``shirudo init``.- * - ``tampered``- - The register, the keyring or a pin disagrees with what the- operation expected (section 7).- - Inspect before acting.- * - ``version_mismatch``- - ``--expect-version-id`` named another build.- - Match operator and target builds.- * - ``eventlog_full``- - The eventlog cap would be exceeded.- - Raise ``eventlog.max_bytes``.- * - ``parser_rejected``- - The file is not a valid upatch, or its name is unsafe.- - Rebuild it.- * - ``signature_rejected``- - The kernel rejected the loader's signature.- - The artifact was signed with another key, or altered.- * - ``signature_unsupported``- - The kernel cannot verify ML-DSA.- - ``CONFIG_CRYPTO_MLDSA`` and ``CONFIG_CRYPTO_SHA512``.- * - ``lsm_denied``- - The LSM denied the load (``EACCES``), or the kernel refused the- keyring (``EPERM``).- - The load named a keyring other than the anchor.- * - ``verifier_rejected``- - The verifier rejected the payload; the log is in the report.- - Rebuild against the target kernel's BTF.- * - ``btf_mismatch``- - A CO-RE relocation found no match.- - Regenerate ``vmlinux.h`` from the target kernel.- * - ``payload_mismatch``- - The unload directive's expected payload is not the pin's.- - Build the directive for the loaded artifact.- * - ``already_unloaded``- - Nothing to unload.- - None.- * - ``detach_failed``- - The link could not be detached.- - Inspect the journal; the pin is intact.- * - ``tpm_error``- - The register could not be extended or bound.- - ``/dev/tpmrm0``, ``tpm.tcti``, ``tpm.owner_auth``; section 7.- * - ``unknown``- - An error without a closer category; errno is in the report.- - Read the report.--9) Config updates---------------------Use ``shirudo image status`` to inspect the active config root hash, PCR,-TPM reset and restart counts, event sequence and pending state. Ordinary target commands-hold the config operation lock and use one held config directory for the-operation; a command waits up to 30 seconds for another one to release-it. They refuse a pending activation or PCR/history inconsistency;-attestation follows the same rule. ``status`` alone runs in those states-and reports them (section 2).--Activate a complete locally staged bundle or pull it by HTTPS prefix::-- shirudo image update /path/to/new-config- shirudo image update https://config.example/shirudo/config--A successful command means required key and mount effects completed.-Validation failures before the pending selection is saved leave the current-config usable. Once activation is pending, interruption or an ambiguous TPM-response blocks further mutations and config attestation. The node keeps-running; Shirudo never initiates a reboot and has no same-boot recovery-command. The operator chooses when to reboot. Trusted startup then verifies-the pending selection and records a fresh BOOT event before completing-initialization. Do not remove pending records or rewrite the eventlog to-make a failure disappear.--Additional BPF keys and revocations arrive through signed config images;-local ``keys add``, ``bpm key add`` and ``keys revoke`` commands are refused.-Repository registration changes also require a signed config: ``bpm config-register add``, ``remove`` and ``rm`` do not mutate image-mode trust inputs.-Package installation and upgrades, tree sync, export and attestation remain-available using the active authenticated configuration. New BPF signing keys-require boot-time enrollment and a reboot; live activation cannot add them-to the sealed keyring. Config updates using the existing signing-key set and-the signed upatch flow remain live. Runtime executable updates are-intentionally disruptive: replace the runtime image and authenticated boot-hash, regenerate the UKI and reboot. Replacing the config verification-certificate uses that same reboot procedure.--New signer enrollment has a provisioning limitation: the CLI does not queue-an otherwise refused candidate for reboot. An existing activation record-selects its cached bundle before the bootstrap ``config.image`` default.-Changing only the default does not select a new signer set. Plan the-boot-time provisioning separately; do not erase the journal to force the-selection. First-boot provisioning and live updates with already enrolled-signers are the workflows exercised by the image fixture suite.--Back up the image bundles under ``/var/lib/shirudo/images`` together with-``/var/lib/shirudo/config-update``, normal installed state and eventlogs.-The activation journal includes TPM reset identity and expected PCR values;-a journal from another target or an inconsistent partial restore must not be-accepted as the current boot. The selected cached config is verified and-receives a fresh BOOT event after reset. Retain operator source directories-and signing keys separately from target backups.--A valid old config remains acceptable in this implementation. Check the intended-root hash when operating a deployment; do not infer rollback prevention or-proof of activation against direct TPM writers from the measurement alone.diff --git a/Documentation/reference/cheat-sheet.rst b/Documentation/reference/cheat-sheet.rstnew file mode 100644index 00000000..7aa7eafc--- /dev/null+++ b/Documentation/reference/cheat-sheet.rst@@ -0,0 +1,477 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: All readers++Cheat sheet+===========++Command lines for common tasks, grouped by task. The prompt says where a+command runs: ``operator$`` on the operator host, ``target#`` as root on a+target, ``$`` and ``#`` in a checkout. On a production target, ``shirudo``+stands for the runtime binary ``/run/shirudo/runtime/usr/bin/shirudo``+(see :doc:`cli/shirudo`). ``~/shirudo-keys`` stands for the operator's keys+directory. Each command links to its reference page.++Keys and signing+----------------++Create an ML-DSA-87 key and certificate with :doc:`cli/genkey`:++.. code-block:: console++ operator$ shirudo genkey --keys-dir ~/shirudo-keys++Show the key material with :doc:`cli/keys`:++.. code-block:: console++ operator$ shirudo keys --keys-dir ~/shirudo-keys++Vouch for a second operator's certificate with :doc:`keys vouch+<cli/keys>`:++.. code-block:: console++ operator$ shirudo keys vouch other-cert.der -o other-cert.der.vouch --keys-dir ~/shirudo-keys++Prepare a new key pair beside the old one and vouch for it with the old+key, before any target relies on it (:doc:`/operate/keys`):++.. code-block:: console++ operator$ shirudo genkey --keys-dir ~/shirudo-keys-new+ operator$ shirudo keys vouch ~/shirudo-keys-new/cert.der --keys-dir ~/shirudo-keys++Build and inspect+-----------------++Compile and sign a upatch into ``fix.bpf.upatch`` with :doc:`cli/build`:++.. code-block:: console++ operator$ shirudo build fix.bpf.c --keys-dir ~/shirudo-keys --vmlinux <vmlinux-h>++``<vmlinux-h>`` is the ``vmlinux.h`` of the target kernel.++Choose the output and the name, and keep the compiled object, with+:doc:`cli/build`:++.. code-block:: console++ operator$ shirudo build fix.bpf.c -o fix.upatch --name fix --keys-dir ~/shirudo-keys --vmlinux <vmlinux-h> --emit-artifacts++Describe an artifact offline with :doc:`cli/upatch-info`:++.. code-block:: console++ operator$ shirudo upatch info fix.upatch++Read its payload digest with :doc:`cli/upatch-info`:++.. code-block:: console++ operator$ shirudo upatch info --json fix.upatch | jq -r .payload_sha256++Sign the unload directive bound to that payload with :doc:`cli/build`+and ``--unload``:++.. code-block:: console++ operator$ shirudo build --unload fix --payload-sha256 "$(shirudo upatch info --json fix.upatch | jq -r .payload_sha256)" -o fix.unload.upatch --keys-dir ~/shirudo-keys++Target state+------------++Run the pre-flight checks without bringing up enforcement with+:doc:`cli/init`:++.. code-block:: console++ target# shirudo init --check-only++Show the state of the target with :doc:`cli/status`:++.. code-block:: console++ target# shirudo status++Read the verdict in a script with :doc:`cli/status`. The exit status is 0+even when the verdict is ``tampered``:++.. code-block:: console++ target# shirudo status --json | jq -r .status++Show everything, with the eventlog, the system, the kernel log and the+modules, with :doc:`cli/status`:++.. code-block:: console++ target# shirudo status --show-full++Add the last 50 kernel log lines with :doc:`cli/status`:++.. code-block:: console++ target# shirudo status --include-kernellog=50++Print the effective configuration with :doc:`cli/config`:++.. code-block:: console++ target# shirudo config++Print the version ID that ``--expect-version-id`` compares with+:doc:`cli/version`:++.. code-block:: console++ target# shirudo version --version-id++Show the certificates and the ``.bpf`` keyring with :doc:`cli/keys`:++.. code-block:: console++ target# shirudo keys++Load and unload+---------------++Load an artifact and print the report with :doc:`cli/upatch-load`:++.. code-block:: console++ target# shirudo upatch load --report=- fix.upatch++Load only when the register holds the value you predicted with+:doc:`cli/upatch-load`. ``<register>`` comes from+:doc:`cli/attest-predict`:++.. code-block:: console++ target# shirudo upatch load --expect-chain=<register> fix.upatch++Load only on the shirudo build you tested with :doc:`cli/upatch-load`:++.. code-block:: console++ target# shirudo upatch load --expect-version-id=<version-id> fix.upatch++Unload with a signed directive and print the category with+:doc:`cli/upatch-unload`:++.. code-block:: console++ target# shirudo upatch unload --report=- fix.unload.upatch | jq -r .category++List the archived and the loaded upatches with :doc:`cli/upatch-list`:++.. code-block:: console++ target# shirudo upatch list --json++Show a loaded upatch with its hook, source lines and every map entry with+:doc:`cli/upatch-get`:++.. code-block:: console++ target# shirudo upatch get fix --json --show-full++Packages and the tree+---------------------++Build ``kernel-obs-1.0.0.bee`` from its Beefile with :doc:`bpm build+<cli/bpm>`:++.. code-block:: console++ operator$ shirudo bpm build upatches/kernel-obs --version 1.0.0 --keys-dir ~/shirudo-keys++List the upatches and directives in a package with :doc:`bpm info+<cli/bpm>`:++.. code-block:: console++ operator$ shirudo bpm info upatches ./kernel-obs-1.0.0.bee --all++Print the fingerprint of the certificate in a package with :doc:`bpm key+<cli/bpm>`:++.. code-block:: console++ operator$ shirudo bpm key fingerprint ./kernel-obs-1.0.0.bee++Publish a package and add it to the registry's signed index with+:doc:`bpm push <cli/bpm>`:++.. code-block:: console++ operator$ shirudo bpm push ./kernel-obs-1.0.0.bee oci://quay.io/example/kernel-obs --keys-dir ~/shirudo-keys++Build the next version with a new ``.rodata`` input with :doc:`bpm config+update <cli/bpm>`. ``watch`` names the Beefile input ``watch.list``:++.. code-block:: console++ operator$ shirudo bpm config update --base-package ./kernel-obs-1.0.0.bee --version 1.0.1 --rodata-input watch=./watch.list --keys-dir ~/shirudo-keys++Append a package's tree entries to the signed tree with :doc:`bpm tree+append <cli/bpm>`. ``<package>`` is a built package whose Beefile has+``[upatches.tree]`` entries:++.. code-block:: console++ operator$ shirudo bpm tree append <package> oci://quay.io/example/tree --keys-dir ~/shirudo-keys++Retract them on another tree reference with :doc:`bpm tree append+<cli/bpm>`:++.. code-block:: console++ operator$ shirudo bpm tree append <package> oci://quay.io/example/tree --keys-dir ~/shirudo-keys --reference canary --op delete++Refresh the indexes and upgrade, as ``shirudo-bpm-repo-update.timer``+does, with :doc:`cli/bpm`:++.. code-block:: console++ target# shirudo bpm repo update+ target# shirudo bpm upgrade++Install a pinned version from a registered repository with :doc:`bpm+install <cli/bpm>`:++.. code-block:: console++ target# shirudo bpm install example/[email protected]++Install directly from a registry reference with :doc:`bpm install+<cli/bpm>`:++.. code-block:: console++ target# shirudo bpm install oci://quay.io/example/kernel-obs:1.0.0++List and remove installed packages with :doc:`cli/bpm`:++.. code-block:: console++ target# shirudo bpm list+ target# shirudo bpm uninstall kernel-obs++Preview a tree sync with :doc:`bpm tree sync <cli/bpm>`:++.. code-block:: console++ target# shirudo bpm tree sync --dry-run --report=/tmp/tree.json++Attestation+-----------++Make a nonce on the operator host:++.. code-block:: console++ operator$ NONCE=$(openssl rand -hex 32)++Produce evidence for that nonce on the target with :doc:`cli/attest`:++.. code-block:: console++ target# shirudo attest --nonce=<nonce> --out=ev.json++Read the attestation key name to pin at enrollment:++.. code-block:: console++ operator$ jq -r .ak.name ev.json++Make a credential challenge for the pinned key with+:doc:`cli/attest-challenge`:++.. code-block:: console++ operator$ shirudo attest challenge --evidence=ev.json --ak-name=<ak-name> --ek-ca=<tpm-vendor-roots> --out=challenge.json++Answer the challenge on the target with :doc:`cli/attest`:++.. code-block:: console++ target# shirudo attest --nonce=<nonce> --challenge=challenge.json --out=ev.json++Predict the register for the certificates the target enrolls and a load+after boot with :doc:`cli/attest-predict`:++.. code-block:: console++ operator$ shirudo attest predict --cert=cert.der --cert=own.der --event=load:fix=<payload-sha256>++Verify evidence against the predicted value with :doc:`cli/attest-verify`:++.. code-block:: console++ operator$ shirudo attest verify --evidence=ev.json --nonce=$NONCE --ak-name=<ak-name> --expect-chain=<register>++Verify against the enrolled certificates, accepting events after boot,+with :doc:`cli/attest-verify`:++.. code-block:: console++ operator$ shirudo attest verify --evidence=ev.json --nonce=$NONCE --ak-name=<ak-name> --cert=cert.der --cert=own.der --allow-runtime-events --require-initrd++Images and config+-----------------++Build a signed config image from a directory with :doc:`cli/gen-tools`:++.. code-block:: console++ operator$ /usr/libexec/shirudo/gen-image/shirudo-gen-image --source ./config-root --output ./config --keys-dir ~/shirudo-keys --kind config++Sign an existing ext4 image with :doc:`image build <cli/image>`:++.. code-block:: console++ operator$ shirudo image build config.ext4 --output config --keys-dir ~/shirudo-keys++Verify an image offline with :doc:`image verify <cli/image>`. The+argument order is fixed:++.. code-block:: console++ operator$ shirudo image verify config --cert config-cert.der++Activate a new config image on a target with :doc:`image update+<cli/image>`:++.. code-block:: console++ target# shirudo image update https://config.example/shirudo/config++Show the config activation with :doc:`image status <cli/image>`. It exits+with 1 while the activation is pending:++.. code-block:: console++ target# shirudo image status++Build the initrd and print the kernel parameters it needs with+:doc:`cli/gen-tools`:++.. code-block:: console++ target# shirudo-gen-initrd --bootstrap-conf <bootstrap-conf>+ target# shirudo-gen-initrd --print-cmdline++Telemetry+---------++List the pinned maps with :doc:`cli/upatch-map`:++.. code-block:: console++ target# shirudo upatch map++Look at a serializer-backed map without draining it with+:doc:`cli/upatch-map`:++.. code-block:: console++ target# shirudo upatch map kernel-obs exec --json --peek++Send one map to a collector with :doc:`cli/upatch-map`:++.. code-block:: console++ target# shirudo upatch map kernel-obs exec --otel --otel-endpoint=https://collector.example:4318 --tenant-id=fleet-eu-1++Export every map to the configured destinations, as+``shirudo-map-export.timer`` does, with :doc:`cli/upatch-map`:++.. code-block:: console++ target# shirudo upatch map --all++Send a keepalive and print it with :doc:`cli/status`. Nothing is sent+without a configured endpoint:++.. code-block:: console++ target# shirudo status --otel --include-system --json++Developing shirudo+------------------++Build the operator binary, the helper and the static target binary+(:doc:`/contribute/developer-guide`):++.. code-block:: console++ $ make+ $ make shirudo-build+ $ make target++Run ``shirudo`` from the checkout with the checkout's helper:++.. code-block:: console++ $ export SHIRUDO_BUILD=$PWD/tools/shirudo-build/shirudo-build++Run every test (:doc:`/contribute/testing`):++.. code-block:: console++ $ make tests++Run the tests that need no VM under the sanitizers:++.. code-block:: console++ $ make tests VM=0 SANITIZE=address,undefined++Run one unit suite and one functional family without a VM:++.. code-block:: console++ $ make -C testing unit/hex+ $ make -C testing functional/upatch VM=0++List the suites and families:++.. code-block:: console++ $ make -C testing help++Boot the interactive test VM, log in and stop it. Booting needs root:++.. code-block:: console++ # make -C testing vm+ # make -C testing vm-ssh+ # make -C testing vm-stop++Run the fuzz targets for a minute each:++.. code-block:: console++ $ make -C testing fuzz FUZZ_SECONDS=60++Render and serve the documentation, and check it against the code+(:doc:`/contribute/writing-docs`):++.. code-block:: console++ $ make docs+ $ make -C Documentation check++Check the commits of a branch as CI does (:doc:`/contribute/contributing`):++.. code-block:: console++ $ .github/scripts/check-dco.sh origin/main..HEAD+ $ .github/scripts/check-style.sh origin/main..HEAD+ $ .github/scripts/check-spdx.sh+ $ .github/scripts/build-commits.sh origin/main..HEADdiff --git a/Documentation/reference/cli/attest-challenge.rst b/Documentation/reference/cli/attest-challenge.rstnew file mode 100644index 00000000..9b2f7646--- /dev/null+++ b/Documentation/reference/cli/attest-challenge.rst@@ -0,0 +1,124 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo attest challenge+========================++Make a credential challenge that only the TPM holding both the target's+endorsement key and its attestation key can answer.++Runs on: operator host, offline. It computes the credential in software+and uses no TPM. Requires: an evidence document from the target. Changes+measured state: no.++Usage+-----++.. code-block:: none++ shirudo attest challenge --evidence=<evidence> --out=<challenge>+ (--ek-ca=<bundle> | --ek-name=<name> | --trust-presented-ek)+ [--ak-name=<name>]++Every option takes its value after ``=``.++Description+-----------++Enrollment pins the target's attestation key. ``challenge`` binds that key+to the target's endorsement key:++#. It reads the attestation and endorsement keys from the evidence. With+ ``--ak-name`` the attestation key must be that one, and with+ ``--ek-name`` the endorsement key.+#. It checks that the endorsement key's name matches its public area and+ that the key has the TCG default template under the endorsement+ policy.+#. It decides whether to trust the endorsement key:++ - With ``--ek-ca``, the endorsement certificate in the evidence must+ describe the key and chain to an issuer in the PEM bundle.+ - With ``--ek-name``, the pinned name vouches for the key.+ - With ``--trust-presented-ek``, the key is accepted as presented.++ Without any of the three, the check fails.+#. It makes a random 32-byte credential, protects it for the endorsement+ key and the attestation key name, writes the challenge to ``--out``+ with mode 0600 and prints ``challenge: <path>`` and+ ``credential: <hex>``.++Give the challenge to ``shirudo attest --challenge=<challenge>`` on the+target. Its evidence then carries the recovered credential, and+``attest verify --expect-credential=<hex> --ak-name=<name>`` checks it.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 24 26 50++ * - Option+ - Argument+ - Description+ * - ``--evidence``+ - ``<evidence>``, a file+ - Required. Evidence from the target.+ * - ``--out``+ - ``<challenge>``, a path+ - Required. Where to write the challenge.+ * - ``--ak-name``+ - ``<name>``, 68 hex characters+ - The attestation key the challenge is for.+ * - ``--ek-ca``+ - ``<bundle>``, PEM file+ - Issuers the endorsement certificate must chain to.+ * - ``--ek-name``+ - ``<name>``, 68 hex characters+ - An endorsement key name known out of band.+ * - ``--trust-presented-ek``+ - none+ - Accept an endorsement key that nothing vouches for.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The challenge was written.+ * - 1+ - A check failed (``verdict: FAIL``), or the challenge could not be+ written.+ * - 2+ - ``--evidence`` or ``--out`` missing, an unknown option or invalid+ value, an unreadable evidence file, or evidence that carries no+ endorsement key.++Examples+--------++Make a challenge for a target whose TPM vendor roots you hold:++.. code-block:: console++ operator$ shirudo attest challenge --evidence=ev.json --ak-name=<ak-name> --ek-ca=<tpm-vendor-roots> --out=challenge.json++``<ak-name>`` is ``.ak.name`` of the evidence (:doc:`attest`) and+``<tpm-vendor-roots>`` a PEM bundle of the TPM manufacturers' issuing+certificates.++Related+-------++- :doc:`attest`+- :doc:`attest-verify`+- :doc:`/operate/attest`diff --git a/Documentation/reference/cli/attest-predict.rst b/Documentation/reference/cli/attest-predict.rstnew file mode 100644index 00000000..8fa5c515--- /dev/null+++ b/Documentation/reference/cli/attest-predict.rst@@ -0,0 +1,185 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo attest predict+======================++Compute the measurement register value a target reaches from the+certificates it enrolls, the upatches it restores at boot and the events+after boot.++Runs on: operator host, offline. It uses no TPM and no target state.+Requires: the certificates the target enrolls. Changes measured state: no.++Usage+-----++.. code-block:: none++ shirudo attest predict --cert=<certificate>... [--upatch=<file>]...+ [--expect=<name>=<digest>]... [--tree-root=<digest>]+ [--event=<event>]...+ [--bind-pcr=9=<value> --bind-pcr=11=<value>+ --writer-public=<modulus>]++Every option takes its value after ``=``. ``--cert cert.der`` with a space+is refused. On a host where enforcement is up the image gate refuses+``--cert``.++Description+-----------++``predict`` recomputes what ``init`` and later commands measure:++#. The init event covers the digest of the enrolled certificate set+ (every ``--cert``, in any order), the set of upatches archived at boot+ (every ``--upatch`` and ``--expect``) and the upatch tree root.+#. The register starts at zero and is extended with the init event. The+ result is ``register_at_boot``.+#. Each ``--event``, in the order given, extends it further. The result+ is ``register_after_events``.+#. With the PCR 9 and 11 values at binding and the writer's public key,+ ``predict`` also computes the register's TPM name, the anchor record+ and the PCR 9 value after the anchor.++The certificate set must be exactly the set the target enrolls: the+primary certificate and every vouched one.++Pass ``register_at_boot`` or ``register_after_events`` to+``upatch load --expect-chain`` or ``attest verify --expect-chain``.++Events+~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - ``--event=``+ - Event+ * - ``load:<name>=<payload-sha256>``+ - ``upatch load`` of ``<name>``+ * - ``unload:<name>=<payload-sha256>``+ - ``upatch unload`` of ``<name>``, with the digest the directive+ names+ * - ``tree:<sequence>=<operation-digest>``+ - an operation ``bpm tree sync`` applied+ * - ``revoke:<label>=<certificate-sha256>``+ - a key revocation. ``<certificate-sha256>`` is the SHA-256 of the+ revoked certificate. ``<label>`` is required and not used.++The eventlog entry of each event (:doc:`/reference/formats/eventlog`)+carries the values.++Output+~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Line+ - Value+ * - ``set_digest:``+ - digest of the upatch set archived at boot+ * - ``init_event:``+ - the init event+ * - ``register_at_boot:``+ - the register after ``init``+ * - ``register_after_events:``+ - the register after the ``--event`` values, only with ``--event``+ * - ``register_name:``, ``anchor:``, ``pcr9_after_anchor:``+ - the register's TPM name, the anchor record and PCR 9 after it,+ only with ``--bind-pcr`` and ``--writer-public``++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 22 30 48++ * - Option+ - Argument+ - Description+ * - ``--cert``+ - ``<certificate>``, DER+ - Required. A certificate the target enrolls. Repeat for each, up to+ 16.+ * - ``--upatch``+ - ``<file>``+ - An artifact archived on the target at boot. Repeatable.+ * - ``--expect``+ - ``<name>=<digest>``+ - An archived upatch by name and payload digest. Repeatable.+ * - ``--tree-root``+ - ``<digest>``, 64 hex characters+ - The upatch tree projection root at boot. Default: all zero.+ * - ``--event``+ - ``<event>``, see above+ - An event after boot. Repeatable, applied in order.+ * - ``--bind-pcr``+ - ``9=<value>`` or ``11=<value>``+ - PCR values the register was bound under. Give both.+ * - ``--writer-public``+ - ``<modulus>``, 768 hex characters+ - The 384-byte RSA modulus of the init record's writer key. Required+ with ``--bind-pcr``.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The values were printed.+ * - 1+ - The register's write policy could not be computed, or memory ran+ out.+ * - 2+ - No ``--cert``, an unknown option, an unreadable file, an invalid+ value or event, or ``--bind-pcr`` without both PCRs or without+ ``--writer-public``.++Examples+--------++Predict the register at boot for a target that enrolls one certificate and+restores nothing:++.. code-block:: console++ operator$ shirudo attest predict --cert=cert.der+ set_digest: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855+ init_event: 1014642f2d76b1eb10b4872c4299a70e191be0eb2958de65a7098bfe92a93124+ register_at_boot: 33ec2c3ed20693c2e40131e693a11b169b91efd8f7438f86313c915e512121e5++Predict the register of a target that enrolls two certificates, after one+load:++.. code-block:: console++ operator$ shirudo attest predict --cert=cert.der --cert=own.der --event=load:basic=46f3d9f5f6568bddb7692cad28e99a86a3104192d8a2251f9ef9ec6d593c2035+ set_digest: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855+ init_event: cb206abf8e514bc714fc69f372d464d2c7512f1489431aed2319551c5ed34b9a+ register_at_boot: d1bdb80f7c0cfc1560f0a5a0b974d282bfd05fc95852b7649d59a054b450aa51+ register_after_events: ff0eb201e073fdeeba80a4b268f039bea58ec6dd2998e6651c4834ee99f3e103++On that target, ``status`` showed ``Chain: d1bdb80f...`` after boot and+``ff0eb201...`` after ``upatch load basic.upatch``.++Related+-------++- :doc:`attest-verify`+- :doc:`upatch-load`+- :doc:`/internals/measurement-register`+- :doc:`/reference/formats/eventlog`diff --git a/Documentation/reference/cli/attest-verify.rst b/Documentation/reference/cli/attest-verify.rstnew file mode 100644index 00000000..ca680314--- /dev/null+++ b/Documentation/reference/cli/attest-verify.rst@@ -0,0 +1,234 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo attest verify+=====================++Check an evidence document offline against the pinned keys and the state+you expect the target to be in.++Runs on: operator host, offline. It uses no TPM. Requires: the evidence+and the nonce it was requested with. Changes measured state: no.++Usage+-----++.. code-block:: none++ shirudo attest verify --evidence=<evidence> --nonce=<nonce>+ [--ak-name=<name>] [--ek-name=<name>]+ [--expect-credential=<credential>]+ [--cert=<certificate>]... [--upatch=<file>]...+ [--expect=<name>=<digest>]... [--tree-root=<digest>]+ [--expect-chain=<register>] [--allow-runtime-events]+ [--expect-config-root=<root> --expect-config-pcr=<pcr>]+ [--expect-pcr=<pcr>=<value>]...+ [--expect-bind-pcr=<pcr>=<value>]...+ [--strict-anchor] [--require-initrd]++Every option takes its value after ``=``. On a host where enforcement is up+the image gate refuses ``--cert``. Run ``verify`` where enforcement is not+up.++Description+-----------++``verify`` prints one line per check, ``ok:``, ``FAIL:`` or ``note:``,+followed by ``verdict: ok`` or ``verdict: FAIL``. It checks:++- the nonce, in the document, the quote and the register certification.+- the attestation key: restricted, fixed to its TPM, its name matching its+ public area and, with ``--ak-name``, the pinned name.+- the endorsement key: its name and the TCG default template, and with+ ``--ek-name`` the pinned name. With ``--expect-credential``, the+ credential the target recovered.+- the quote and the register certification: signed by the attestation key+ as an endorsement primary, covering the listed PCRs and index, of one+ TPM reset.+- the config root history against the quoted config PCR, and with+ ``--expect-config-root`` the approved root.+- the register's public area against the recorded PCR 9 and 11 binding,+ the init record of this TPM reset, the eventlog replay to the certified+ value and the anchor in PCR 9.+- the expected state: with ``--cert`` (and ``--upatch``, ``--expect``,+ ``--tree-root``) the init event, and the events after boot, which fail+ unless ``--allow-runtime-events``. With ``--expect-chain``, the register+ value.++Without ``--ak-name``, ``verify`` warns that the signer is not pinned, and+a document from any TPM passes the key checks. Without ``--cert`` or+``--expect-chain``, it compares no state and prints the register value as+a note. A ``verdict: ok`` then says only that the document is consistent+in itself. Pin the keys at enrollment (:doc:`attest-challenge`) and always+give the expected state.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 26 24 50++ * - Option+ - Argument+ - Description+ * - ``--evidence``+ - ``<evidence>``, a file+ - Required. The document ``shirudo attest`` wrote.+ * - ``--nonce``+ - ``<nonce>``, hexadecimal, up to 64 bytes+ - Required. The nonce the evidence was requested with.+ * - ``--ak-name``+ - ``<name>``, 68 hex characters+ - The attestation key name pinned at enrollment.+ * - ``--ek-name``+ - ``<name>``, 68 hex characters+ - The endorsement key name pinned at enrollment.+ * - ``--expect-credential``+ - ``<credential>``, 64 hex characters+ - The credential of the challenge given to the target. Needs+ ``--ak-name``.+ * - ``--cert``+ - ``<certificate>``, DER+ - A certificate the target enrolls. Repeat for each, up to 16.+ * - ``--upatch``+ - ``<file>``+ - An artifact archived on the target at boot. Repeatable. Needs+ ``--cert``.+ * - ``--expect``+ - ``<name>=<digest>``+ - An archived upatch by name and payload digest. Repeatable. Needs+ ``--cert``.+ * - ``--tree-root``+ - ``<digest>``, 64 hex characters+ - The upatch tree projection root at boot. Needs ``--cert``.+ * - ``--expect-chain``+ - ``<register>``, 64 hex characters+ - The register value after the expected events.+ * - ``--allow-runtime-events``+ - none+ - Accept loads, unloads and revocations after boot.+ * - ``--expect-config-root``+ - ``<root>``, 64 hex characters+ - The approved config image root hash. Needs+ ``--expect-config-pcr``.+ * - ``--expect-config-pcr``+ - ``<pcr>``, 0 to 15, not 9 or 11+ - The PCR the config activation extends.+ * - ``--expect-pcr``+ - ``<pcr>=<value>``, PCR 0 to 23+ - A PCR value the quote must carry. Repeatable.+ * - ``--expect-bind-pcr``+ - ``<pcr>=<value>``, PCR 0 to 23+ - A PCR value the register was bound under. Repeatable.+ * - ``--strict-anchor``+ - none+ - Require PCR 9 to hold only the anchor.+ * - ``--require-initrd``+ - none+ - Fail unless ``init`` bound the register from the initrd.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - ``verdict: ok``.+ * - 1+ - ``verdict: FAIL``.+ * - 2+ - A usage error or an invalid value, ``--evidence`` or ``--nonce``+ missing, an option that needs another, an unreadable evidence file+ or a file that is not a shirudo evidence document.++Examples+--------++Verify evidence against the predicted register value, with the+attestation key pinned:++.. code-block:: console++ operator$ shirudo attest verify --evidence=ev.json --nonce=$NONCE --ak-name=<ak-name> --expect-chain=<register>+ ok: nonce matches the request+ ok: attestation key: restricted, fixed to this TPM+ ok: attestation key: name matches its public area+ ok: attestation key: the pinned key+ ok: endorsement key: name matches its public area+ ok: endorsement key: TCG default template under the endorsement policy+ ok: quote: ECDSA signature by the attestation key+ ok: quote: signed by the key as an endorsement primary+ ok: quote: carries the nonce+ ok: quote: covers the PCRs the document lists+ ok: quote: PCR digest matches the listed values+ ok: register: ECDSA signature by the attestation key+ ok: register: signed by the key as an endorsement primary+ ok: register: carries the nonce+ ok: register: certification names the listed index+ ok: register: certified contents match the listed value+ ok: quote and certification are of one TPM reset+ ok: config: config root history matches the quoted PCR+ note: config root has no operator approval; use --expect-config-root with --expect-config-pcr+ note: config records a selection; direct TPM writer protection is deferred+ ok: eventlog: this boot has an init record+ ok: register: the document names index 0x01818E00 and PCRs 9 and 11+ ok: register: public area is bound to PCRs 9 and 11 as recorded+ note: binding: made in the initrd+ ok: eventlog: one init record for this TPM reset (1 this boot)+ ok: register: init record is of the TPM's current reset count+ ok: eventlog: 2 records replay to the certified value+ ok: anchor: record digest matches the index name+ ok: anchor: PCR 9 equals the recorded value extended by the anchor+ ok: state: register equals the expected value+ note: event after boot: upatch_load basic+ verdict: ok++``$NONCE`` holds the nonce given to ``shirudo attest``, ``<ak-name>`` the+name pinned at enrollment and ``<register>`` the+``register_after_events`` line of :doc:`attest-predict`.++Verify against the enrolled certificates and require an initrd binding.+Events after boot fail the check without ``--allow-runtime-events``:++.. code-block:: console++ operator$ shirudo attest verify --evidence=ev.json --nonce=$NONCE --ak-name=<ak-name> --cert=cert.der --require-initrd --strict-anchor++The end of that report, for a target that loaded and unloaded a upatch+after boot:++.. code-block:: none++ ok: binding: made while the initrd ran+ ok: eventlog: one init record for this TPM reset (1 this boot)+ ok: register: init record is of the TPM's current reset count+ ok: eventlog: 3 records replay to the certified value+ ok: anchor: record digest matches the index name+ ok: anchor: PCR 9 equals the recorded value extended by the anchor+ FAIL: state: init event covers the expected certificate, set and tree root+ FAIL: state: 2 events after boot change the register+ note: event after boot: upatch_load shirudo-test-basic+ note: event after boot: upatch_unload shirudo-test-basic+ verdict: FAIL++The first ``FAIL`` line says that the target enrolls a certificate set+other than the one given: that target enrolls two certificates and the+command names one.++Related+-------++- :doc:`attest`+- :doc:`attest-predict`+- :doc:`attest-challenge`+- :doc:`/operate/attest`+- :doc:`/security/threat-model`diff --git a/Documentation/reference/cli/attest.rst b/Documentation/reference/cli/attest.rstnew file mode 100644index 00000000..a27928ac--- /dev/null+++ b/Documentation/reference/cli/attest.rst@@ -0,0 +1,151 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo attest+==============++Produce a TPM-signed evidence document for this target, and activate the+operator's credential challenge when given one.++Runs on: target, as root with the runtime binary. Requires: a TPM and a+measurement register bound this boot by ``init``. Changes measured state:+no.++Usage+-----++.. code-block:: none++ shirudo attest [--nonce=<nonce>] [--pcrs=<list>] [--challenge=<challenge>]+ [--out=<path>]+ shirudo attest verify ...+ shirudo attest predict ...+ shirudo attest challenge ...+ shirudo attest --list-cmds++Every option takes its value after ``=``. ``attest`` with no argument+produces evidence. It does not print help. The subcommands run on the+operator host: :doc:`attest-verify`, :doc:`attest-predict`,+:doc:`attest-challenge`.++Description+-----------++``attest`` collects and signs, with the TPM's attestation key:++- a quote over the selected PCRs with the nonce,+- a certification of the measurement register (NV index ``0x01818E00``)+ with the nonce,+- this boot's eventlog, the config activation records, and the firmware+ and systemd measurement logs,+- the public areas and names of the attestation key and the endorsement+ key, and the endorsement certificate when the TPM holds one.++The attestation key is a fixed-template primary under the endorsement+hierarchy. With ``--challenge``, ``attest`` activates the credential the+operator made for that key and includes it, which proves that the key+lives in the same TPM as the endorsement key (:doc:`attest-challenge`).++Without ``--nonce``, ``attest`` warns that the evidence proves no+freshness.++:doc:`/operate/attest` describes the procedure from enrollment to+verification.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 18 26 18 38++ * - Option+ - Argument+ - Default+ - Description+ * - ``--nonce``+ - ``<nonce>``, hexadecimal, up to 64 bytes+ - none+ - Freshness value from the verifier, carried in the quote and the+ certification.+ * - ``--pcrs``+ - ``<list>``, comma-separated PCRs 0 to 23+ - 0-7, 9, 11-15+ - PCRs to quote.+ * - ``--challenge``+ - ``<challenge>``, a file+ - none+ - Credential challenge from ``attest challenge`` to activate.+ * - ``--out``+ - ``<path>``+ - standard output+ - Write the evidence to ``<path>`` with mode 0600. A path in sealed+ state is refused.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The evidence was written.+ * - 1+ - No TPM answered (``attest: no TPM answered (tpm_error)``), the+ register is not bound this boot, the TPM refused the challenge+ (``attest: the challenge was refused (tampered?)``), or producing+ or writing the evidence failed.+ * - 2+ - An unknown option, an invalid ``--nonce`` or ``--pcrs``, or a+ ``--challenge`` file that is not a shirudo credential challenge.++Files and environment+---------------------++- Reads the TPM, ``/var/lib/shirudo/eventlog``, the config activation+ records and the firmware and systemd event logs.+- Writes ``--out``.++Examples+--------++On the operator host, make a nonce:++.. code-block:: console++ operator$ openssl rand -hex 32++On the target, produce evidence for that nonce:++.. code-block:: console++ target# shirudo attest --nonce=a707993af885f29e88a1f9e936a3ccf9806b8d8b02c43dfe56fe571ce0f200d3 --out=ev.json++``attest`` prints nothing on success and writes ``ev.json`` with mode+0600. The document is JSON with the keys ``schema``, ``kind``+(``shirudo-attestation``), ``version_id``, ``ts``, ``boot_id``, ``nonce``,+``pcr_bank``, ``pcr_mask``, ``pcrs``, ``ak``, ``ek``, ``quote``,+``register``, ``eventlog``, ``config``, ``credential``,+``ek_certificate`` and ``logs``. Read the attestation key name to pin at+enrollment:++.. code-block:: console++ operator$ jq -r .ak.name ev.json+ 000b6e354140b22198138167393ecd1233cfc27e8b16ef0b2b60cce88563c5588dbc++Related+-------++- :doc:`attest-verify`+- :doc:`attest-challenge`+- :doc:`attest-predict`+- :doc:`/operate/attest`+- :doc:`/internals/measurement-register`diff --git a/Documentation/reference/cli/bpm.rst b/Documentation/reference/cli/bpm.rstnew file mode 100644index 00000000..c7084b60--- /dev/null+++ b/Documentation/reference/cli/bpm.rst@@ -0,0 +1,410 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators, upatch authors++shirudo bpm+===========++Install, upgrade and remove signed packages of upatches on a target, and+build and publish them to an OCI registry from the operator host.++Runs on: per subcommand, see the table. Target subcommands run as root+with the runtime binary. Requires: per subcommand. Changes measured state:+``install``, ``upgrade``, ``uninstall`` and ``tree sync`` yes, the others+no.++Usage+-----++.. code-block:: none++ shirudo bpm config register add <source> oci://<registry> (--key-file <certificate> | --key-file=<certificate>)+ shirudo bpm config register list+ shirudo bpm config register (remove | rm) <source>+ shirudo bpm config update --base-package <package> --version <version>+ [-f <beefile> | --file <beefile>]+ [--rodata-input <name>=<path>]... [--keys-dir <dir>]+ shirudo bpm repo update [<source>]+ shirudo bpm tree sync [--dry-run] [--report <path> | --report=<path>]+ shirudo bpm tree append <package> oci://<registry>/<repository> [<append-options>]+ shirudo bpm key (add | fingerprint) <certificate | package | oci-reference>+ shirudo bpm key list+ shirudo bpm pull oci://<registry>/<repository>:<tag>+ shirudo bpm info <package>+ shirudo bpm info upatches <package> [--all]+ shirudo bpm info data <package> <member> [--json]+ shirudo bpm push <package> oci://<registry>/<repository>+ [--keys-dir <dir> | --index-cert <certificate> --index-key <signing-key>]+ shirudo bpm build [<context>] --version <version> [-f <beefile> | --file <beefile>]+ [--keys-dir <dir>] [--vmlinux <vmlinux-h>]+ [--rodata-input <name>=<path>]...+ shirudo bpm install <source>/<name>[@<version>]+ shirudo bpm install oci://<registry>/<repository>:<tag>+ shirudo bpm upgrade+ shirudo bpm list+ shirudo bpm uninstall <name>+ shirudo bpm --list-cmds++``<package>`` is a local ``.bee`` file or an ``oci://`` reference.+``<source>`` is the name of a registered repository.++.. list-table::+ :header-rows: 1+ :widths: 26 34 14 26++ * - Subcommand+ - Runs on+ - Lock+ - Measured+ * - ``config register add``, ``remove``+ - host without a config image, refused on targets with one+ - no+ - no+ * - ``config register list``+ - target+ - no+ - no+ * - ``config update``+ - operator host, helper+ - no+ - no+ * - ``repo update``+ - target+ - yes+ - no+ * - ``tree sync``+ - target+ - yes+ - yes+ * - ``tree append``+ - operator host, helper+ - no+ - no+ * - ``key add``+ - host without a config image, refused on targets with one+ - no+ - no+ * - ``key fingerprint``, ``key list``+ - any host+ - no+ - no+ * - ``pull``, ``info``+ - any host+ - no+ - no+ * - ``push``, ``build``+ - operator host, helper+ - no+ - no+ * - ``install``, ``upgrade``, ``uninstall``+ - target+ - yes+ - yes+ * - ``list``+ - target+ - no+ - no++The lock is ``/var/lib/shirudo/locks/bpm.lock``. A locked subcommand waits+for it. The helper subcommands execute ``shirudo-build`` (see+:doc:`shirudo`). ``shirudo bpm --help`` and ``--list-cmds`` show ``build``+and ``push`` only where the helper resolves. Elsewhere they are unknown+subcommands. ``config update`` and ``tree append`` always execute the+helper and fail with 127 without it.++Subcommand names after ``bpm`` and ``bpm key`` may be abbreviated (see+:doc:`shirudo`). The words after ``config``, ``repo`` and ``tree`` may+not.++config register+---------------++Repositories are registered per host in+``/etc/shirudo/bpm/registries.d/<source>.conf``. On a target with a config+image, the image's ``etc/shirudo/bpm/registries.d/`` is used instead, and+``add`` and ``remove`` are refused with:++.. code-block:: none++ image mode: change repository definitions and keys in a signed config image, then run `shirudo image update`++- ``add`` checks that the endpoint is ``oci://<host>[:<port>]`` without a+ path and that ``--key-file`` is a certificate, copies the certificate to+ ``/etc/shirudo/bpm/keys/<source>.der`` and writes the source file.+ Arguments after the endpoint other than ``--key-file`` are ignored.+- ``list`` prints the registered source names, one per line.+- ``remove`` and ``rm`` delete the source file and its certificate.++The key file verifies the signed index of the repository+(:doc:`/reference/formats/bpm-formats`).++config update+-------------++``config update`` builds the next version of a package without+compiling it. For each upatch of the base package that declares+``.rodata`` inputs, it checks that the operator's key signed it, runs+the Beefile's ``update`` command for each input to produce the new+``.rodata`` (``--rodata-input`` replaces an input file), signs the upatch+again and signs a new unload directive for it. The base package must be+signed by the same key and declare ``.rodata`` inputs, and ``--version``+must be greater than its version. Without ``-f``, the Beefile and the+commands it names come from the base package and run on the operator+host: take base packages only from sources you trust. The output is+``<name>-<version>.bee`` in the current directory. Options take their+value as the next argument only. The subcommand's ``--help`` does not list+``--keys-dir``.++repo update+-----------++``repo update`` fetches the signed index ``shirudo/bpm-index:stable`` of+every registered source, or of ``<source>`` alone, verifies it with the+source's key file and caches it in+``/var/lib/shirudo/bpm/repos/<source>/index.json``. A source that fails+does not stop the others, and the exit status is then 1.++tree sync+---------++``tree sync`` applies the signed upatch tree that+``etc/shirudo/bpm/upatch-tree.conf`` of the config image, or+``/etc/shirudo/bpm/upatch-tree.conf`` without one, names (``endpoint``+and ``reference``). Without that file it exits with 0 at once, without+reading its options.++#. It fetches the publication and checks its tree ID, generation, parent+ and sequence numbers against the state in+ ``/var/lib/shirudo/bpm/upatch-tree/state.json``.+#. For each new operation whose selector matches the node labels+ (``etc/shirudo/node.labels`` of the config image, or+ ``/etc/shirudo/node.labels``), it fetches and verifies the artifact,+ loads (``add``) or unloads (``delete``) it, extends the register with+ a tree event and records the new projection root.+#. It prints a JSON report to standard output, or to ``--report``.++With ``--dry-run``, it reports which operations would apply and changes+nothing. An ``add`` whose kprobe target module is not loaded is skipped+and recorded as ``skipped: module not loaded``.++tree append+-----------++``tree append`` publishes the ``[upatches.tree]`` entries of a built+package as the next operations of the signed tree at+``<repository>:<reference>`` and prints ``oci://<registry>/<repository>:<reference>+<digest>``. Its options take the value as the next argument or after+``=``:++.. list-table::+ :header-rows: 1+ :widths: 20 30 50++ * - Option+ - Default+ - Description+ * - ``--keys-dir``+ - ``$SHIRUDO_KEYS_DIR``, else ``/var/lib/shirudo/keys``+ - Keys directory.+ * - ``--key``, ``--cert``+ - from the keys directory+ - Signing key and certificate.+ * - ``--tree-id``+ - the existing tree's, else the package name+ - Tree ID. It must match the existing tree.+ * - ``--reference``+ - ``stable``+ - Tag of the tree publication.+ * - ``--op``+ - ``add``+ - ``add`` or ``delete``.++key+---++- ``key fingerprint`` prints the SHA-256 fingerprint of a certificate's+ public key (SPKI). The argument is a DER certificate, a ``.bee`` package+ (its ``cert.der``) or an ``oci://`` package reference.+- ``key add`` prints the same fingerprint and installs the certificate in+ ``/var/lib/shirudo/keys/<fingerprint>.der``. When+ ``/var/lib/shirudo/keys/cert.der`` does not exist, it links ``cert.der``+ to the new file, which makes it the host's primary BPF signing+ certificate. When ``cert.der`` exists with another public key, ``add``+ refuses with ``EPERM``. On a target with a config image ``add`` is+ refused.+- ``key list`` prints the fingerprints of the certificates in+ ``/var/lib/shirudo/keys``.++``key add`` with an ``oci://`` reference installs the certificate the+registry serves. Run ``key fingerprint`` on the same reference first and+compare the result with a fingerprint you obtained out of band.++pull and info+-------------++``pull`` downloads the package layer of an ``oci://`` reference into the+current directory, named after the layer title or+``<name>-<tag>.bee``, and checks its digest against the manifest.++``info`` prints the ``README.md`` of a package. ``info upatches`` lists+its ``upatches/*.upatch`` members, with ``--all`` also the+``.unload.upatch`` directives. ``info data`` decodes the initial+``.rodata`` of one member through its BTF types, with ``--json`` as JSON.++push+----++``push`` publishes a ``.bee`` file to ``oci://<registry>/<repository>``+(no tag) and prints ``oci://<registry>/<repository>:<version>``. With+``--keys-dir``, or ``--index-cert`` and ``--index-key`` together, it also+adds the package to the registry's signed index+``shirudo/bpm-index:stable``, signed with that key. Without them only the+package is published. ``push`` does not read ``SHIRUDO_KEYS_DIR``. Its+options take the value as the next argument or after ``=``.++build+-----++``build`` builds and signs a package from a Beefile+(:doc:`/upatches/beefile`):++- The Beefile is ``-f``, else ``<context>/Beefile``, with ``<context>``+ defaulting to the current directory.+- The keys directory is ``--keys-dir`` (a leading ``~`` is expanded), else+ ``$SHIRUDO_KEYS_DIR``, else ``/var/lib/shirudo/keys``.+- ``vmlinux.h`` is ``--vmlinux``, else ``./vmlinux.h`` or+ ``./vendor/linux/vmlinux.h`` in the current directory, else the search+ of :doc:`build` in the Beefile's directory.+- ``--rodata-input <name>=<path>`` replaces a ``.rodata`` input file of+ the Beefile. ``<name>`` is the file's base name up to the first dot+ (``watch`` for ``watch.list``). It is repeatable, once per name.+- Every upatch is compiled in the Beefile's directory and signed.+- The output is ``<name>-<version>.bee`` in the current directory, and+ ``build`` prints its path.++Options take the value as the next argument or after ``=``, except+``--rodata-input``.++install, upgrade, uninstall and list+------------------------------------++``install <source>/<name>[@<version>]`` takes the package from the index+cached by ``repo update``: the given version, else the greatest. ``install+oci://<registry>/<repository>:<tag>`` takes the package directly, with the+tag as its version and the source ``direct``. The manifest is then fetched+by tag and not checked against a digest. ``install`` does nothing when a+package of that name is installed, whatever its version.++For each package ``install`` and ``upgrade``:++#. Check the manifest digest and the package's digest and size against+ the index.+#. Extract the package to+ ``/var/lib/shirudo/bpm/packages/<name>/<version>``.+#. Require the package's ``cert.der`` to hold the same public key as+ ``/var/lib/shirudo/keys/cert.der``.+#. Load each ``upatches/*.upatch`` in name order, as ``upatch load+ --no-precheck`` does, each load measured.+#. Record the package in ``/var/lib/shirudo/bpm/state.json``.++``upgrade`` takes no argument. For every package not installed ``direct``+it installs the greatest version in the cached index when that version is+greater than the installed one: it unloads the old version with its+directives, loads the new one and restores the old one when that fails.+``upgrade`` fetches no index itself. ``shirudo-bpm-repo-update.timer`` runs+``repo update`` and then ``upgrade`` at boot and 60 seconds after each+run, so a new version in a registered index reaches every target that+runs the timer.++``uninstall <name>`` applies the package's shipped unload directives in+reverse name order, each measured, removes the package directory and+drops it from the state.++``list`` prints ``<name> <version> <source>`` for each installed package.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - Success, or ``tree sync`` without a configured tree.+ * - 1+ - Failure, printed as ``bpm <action>: <error>``. Also the usage+ errors of ``build``, ``config update``, ``tree append`` and+ ``tree sync``, and ``config register add`` or ``remove`` and+ ``key add`` on a target with a config image.+ * - 2+ - A usage error of the other subcommands, an unknown subcommand, and+ without a message: ``repo`` without ``update``, ``repo update``+ with more than one source, ``tree sync`` with more than three+ arguments, ``upgrade`` with an argument, ``install`` without+ exactly one reference, and an unknown ``config`` action.+ * - 127+ - A helper subcommand cannot execute ``shirudo-build``.++``bpm install --help`` and ``bpm repo update --help`` do not print help:+they treat ``--help`` as a package and a source.++Files and environment+---------------------++- ``/etc/shirudo/bpm/registries.d/``, ``/etc/shirudo/bpm/keys/``,+ ``/etc/shirudo/bpm/upatch-tree.conf``, ``/etc/shirudo/node.labels``, or+ the same paths in the config image.+- ``/var/lib/shirudo/bpm/``: ``repos/``, ``packages/``, ``staging/``,+ ``state.json`` and ``upatch-tree/``, and+ ``/var/lib/shirudo/locks/bpm.lock``.+- Registry access: ``BPM_OCI_USERNAME`` and ``BPM_OCI_PASSWORD``,+ ``BPM_OCI_BEARER_TOKEN``, ``REGISTRY_AUTH_FILE``, ``DOCKER_CONFIG`` and+ ``~/.docker/config.json``, ``BPM_OCI_SCHEME`` (``https`` or ``http``),+ ``BPM_OCI_CA_FILE``. The timer services read them from+ ``/etc/shirudo/bpm/environment``. See :doc:`/reference/environment`.++Examples+--------++On the operator host, build a package and publish it with its index+entry:++.. code-block:: console++ operator$ shirudo bpm build ./example-shield --version 1.0.0 --keys-dir ~/shirudo-keys+ operator$ shirudo bpm push ./example-shield-1.0.0.bee oci://quay.io/example/example-shield --keys-dir ~/shirudo-keys++On a target, refresh the indexes, install a pinned version and list the+packages:++.. code-block:: console++ target# shirudo bpm repo update+ target# shirudo bpm install example/[email protected]+ target# shirudo bpm list++Preview a tree sync:++.. code-block:: console++ target# shirudo bpm tree sync --dry-run --report=/tmp/tree.json++Print the fingerprint of the certificate a package carries:++.. code-block:: console++ operator$ shirudo bpm key fingerprint ./example-shield-1.0.0.bee++Related+-------++- :doc:`/operate/deliver-packages`+- :doc:`/upatches/publishing`+- :doc:`/upatches/beefile`+- :doc:`/reference/formats/bpm-formats`+- :doc:`/reference/systemd-units`diff --git a/Documentation/reference/cli/build.rst b/Documentation/reference/cli/build.rstnew file mode 100644index 00000000..9753e058--- /dev/null+++ b/Documentation/reference/cli/build.rst@@ -0,0 +1,241 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: upatch authors++shirudo build+=============++Compile and sign a BPF program into a ``.upatch`` artifact, or sign an+unload directive for a loaded upatch.++Runs on: operator host, without the image gate. Requires: the+``shirudo-build`` helper, the signing key and certificate, and for a+``.bpf.c`` input ``/usr/bin/clang`` and a ``vmlinux.h``. Changes measured+state: no.++Usage+-----++.. code-block:: none++ shirudo build <input> [-o <output>] [--name <name>]+ [--keys-dir <dir> | --keys-dir=<dir>]+ [--key <signing-key>] [--cert <certificate>]+ [--vmlinux <vmlinux-h>] [--extra-cflags <flags>]+ [--emit-artifacts]+ shirudo build --unload <name> [-o <output>] [--payload-sha256 <digest>]+ [--keys-dir <dir> | --keys-dir=<dir>]+ [--key <signing-key>] [--cert <certificate>]+ shirudo build --help+ shirudo-build --help++Every option except ``--keys-dir`` takes its value as the next argument.+The form ``--option=<value>`` is refused as an unknown option, except+``--keys-dir=<dir>``. Options and the input may come in any order.++``shirudo build`` executes the ``shirudo-build`` helper with the same+arguments (see :doc:`shirudo` for how it finds the helper).+``shirudo build --help`` prints a short summary and the helper path.+``shirudo-build --help``, or ``--help`` after any other argument, prints+the helper's full option list.++Description+-----------++Building a upatch+~~~~~~~~~~~~~~~~~++#. The helper resolves the signing key and the certificate: ``--key`` and+ ``--cert``, else ``signing_key.pem`` and ``cert.der`` in the keys+ directory, which is ``--keys-dir``, else ``$SHIRUDO_KEYS_DIR``, else+ ``/var/lib/shirudo/keys``. The key must be a regular file with mode+ 0600 and the certificate readable.+#. It selects the output: ``-o``, else the input path with a trailing+ ``.c`` or ``.o`` replaced by ``.upatch``, beside the input+ (``fix.bpf.c`` becomes ``fix.bpf.upatch``).+#. For a ``.bpf.c`` input, it finds ``vmlinux.h``: ``--vmlinux``, else+ ``./vmlinux.h``, else ``./vendor/linux/vmlinux.h``, else the installed+ ``vmlinux.h`` (``/usr/share/shirudo/vmlinux.h`` in the operator+ package, ``/usr/local/share/shirudo/vmlinux.h`` after ``make+ install``). It then runs ``/usr/bin/clang -target bpf -O2 -g -Wall+ -Wextra`` with the ``vmlinux.h`` directory, the libbpf headers and the+ shirudo BPF headers on the include path, plus ``--extra-cflags``. The+ clang path is fixed when the helper is built, and ``PATH`` is not+ searched. The object goes to a temporary file in ``/tmp``, or with+ ``--emit-artifacts`` beside the output.+#. A ``.bpf.o`` or ``.o`` input is packaged as it is. Any other input is+ refused.+#. It names the upatch: ``--name``, else the input file name without+ ``.bpf.c``, ``.bpf.o`` or ``.o``.+#. It generates the loader for the object, signs it with the key and+ writes the artifact. The detached CMS signature covers the loader+ instructions and the loader's data, which hold the payload and the+ signed sections: the name, the attach metadata and any decoders (see+ :doc:`/reference/formats/upatch-format`).++The helper prints ``wrote <output> (insns=<n> sig=<n> data=<n>+sections=<n> maps=<n> progs=<n> decoders=<n> name=<name>)``.++Signing an unload directive+~~~~~~~~~~~~~~~~~~~~~~~~~~~++With ``--unload <name>``, the helper takes no input. It signs the+prebuilt unload program together with ``<name>`` and the expected payload+digest:++#. The expected digest is ``--payload-sha256``, 64 hexadecimal+ characters. Read it from the artifact with ``upatch info --json`` (key+ ``payload_sha256``).+#. Without ``--payload-sha256``, the helper reads the digest from+ ``/var/lib/shirudo/upatches/<name>.upatch`` on the host it runs on.+ Without that file it signs 32 zero bytes and prints a warning.+#. The output is ``-o``, else ``<name>.unload.upatch`` in the current+ directory.++A target applies a directive only to an upatch whose loaded payload+digest equals the signed one (:doc:`upatch-unload`). The helper's warning+and ``--help`` say that an all-zero digest makes the target skip that+check. It does not: the target compares the digests and refuses a+directive with a zero digest with ``payload_mismatch``. Always pass+``--payload-sha256``.++Other helper commands+~~~~~~~~~~~~~~~~~~~~~++The helper also serves ``keys vouch``, ``image build``, ``image verify``+and the operator ``bpm`` commands, and two commands that only scripts and+tooling call:++.. code-block:: none++ shirudo-build image sign-root <root-hash-file> -o <signature>+ [--keys-dir <dir>] [--key <signing-key>] [--cert <certificate>]+ shirudo-build upatch rewrite-rodata <original> <modified> -o <output>+ --data-range <offset>:<length> [--data-range ...]+ [--keys-dir <dir>] [--key <signing-key>] [--cert <certificate>]++``image sign-root`` signs the 64 lowercase hexadecimal characters of a+dm-verity root hash. ``shirudo-gen-verity`` calls it. ``upatch+rewrite-rodata`` re-signs an artifact whose ``.rodata`` changed inside the+given ranges.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 22 18 25 35++ * - Option+ - Argument+ - Default+ - Description+ * - ``-o``+ - ``<output>``+ - see above+ - Where to write the artifact or directive.+ * - ``--name``+ - ``<name>``+ - input file name+ - Name of the upatch. Ignored with ``--unload``.+ * - ``--keys-dir``+ - ``<dir>``, next argument or after ``=``+ - ``$SHIRUDO_KEYS_DIR``, else ``/var/lib/shirudo/keys``+ - Directory holding ``signing_key.pem`` and ``cert.der``.+ * - ``--key``+ - ``<signing-key>``+ - from the keys directory+ - Private key, PEM, mode 0600. Overrides ``--keys-dir``.+ * - ``--cert``+ - ``<certificate>``+ - from the keys directory+ - Certificate, DER. Overrides ``--keys-dir``.+ * - ``--vmlinux``+ - ``<vmlinux-h>``+ - see above+ - ``vmlinux.h`` of the kernel the upatch is for.+ * - ``--extra-cflags``+ - ``<flags>``, one argument+ - none+ - Further clang flags.+ * - ``--emit-artifacts``+ - none+ - off+ - Keep the compiled object as ``<output without .upatch>.o`` and+ print the emitted paths on standard output.+ * - ``--unload``+ - ``<name>``+ - none+ - Sign an unload directive for the upatch ``<name>``.+ * - ``--payload-sha256``+ - ``<digest>``, 64 hex characters+ - see above+ - Payload digest the directive expects. Only with ``--unload``.+ * - ``-h``, ``--help``+ - none+ -+ - Print the helper's option list on standard output.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The artifact or directive was written.+ * - 1+ - The key or certificate is unusable, ``vmlinux.h`` or clang is+ missing, compilation failed, or packaging and signing failed.+ * - 2+ - An unknown option, a second input, an input that is not+ ``.bpf.c``, ``.bpf.o`` or ``.o``, no input, an input together with+ ``--unload``, or a ``--payload-sha256`` that is not 64 hexadecimal+ characters.+ * - 127+ - ``shirudo`` cannot execute the helper.++Files and environment+---------------------++- Reads the key and certificate, ``vmlinux.h``, and for ``--unload``+ without a digest ``/var/lib/shirudo/upatches/<name>.upatch``.+- Writes the output, and ``/tmp/shirudo-build-*.bpf.o`` while it compiles.+- ``SHIRUDO_KEYS_DIR``: the default keys directory.+- ``SHIRUDO_BUILD``: the helper ``shirudo`` executes.++Examples+--------++Build and sign a upatch for the kernel whose ``vmlinux.h`` you name:++.. code-block:: console++ operator$ shirudo build basic.bpf.c --keys-dir <keys-dir> --vmlinux <vmlinux-h> -o basic.upatch+ wrote basic.upatch (insns=992 sig=4853 data=2456 sections=2 maps=0 progs=1 decoders=0 name=basic)++Sign the directive that unloads it, bound to its payload digest:++.. code-block:: console++ operator$ shirudo build --unload basic --payload-sha256 <payload-sha256> --keys-dir <keys-dir> -o basic.unload.upatch+ wrote basic.unload.upatch (insns=1320 sig=4853 data=2808 sections=2 maps=1 progs=1 decoders=0 name=basic UNLOAD)++``<keys-dir>`` holds the key pair, ``<vmlinux-h>`` is the target kernel's+``vmlinux.h`` and ``<payload-sha256>`` is the ``payload_sha256`` that+``shirudo upatch info --json basic.upatch`` prints.++Related+-------++- :doc:`upatch-info`+- :doc:`upatch-load`+- :doc:`upatch-unload`+- :doc:`/upatches/kernel-fix-tutorial`+- :doc:`/reference/formats/upatch-format`diff --git a/Documentation/reference/cli/config.rst b/Documentation/reference/cli/config.rstnew file mode 100644index 00000000..a8c734cb--- /dev/null+++ b/Documentation/reference/cli/config.rst@@ -0,0 +1,157 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo config+==============++Print the effective shirudo configuration in ``shirudo.conf`` syntax.++Runs on: any host, and on a target as root with the runtime binary. Requires:+nothing. Changes measured state: no.++Usage+-----++.. code-block:: none++ shirudo config++Description+-----------++``config`` loads the configuration the other commands use and prints+every setting with a comment above it. The first line names the source:++.. list-table::+ :header-rows: 1+ :widths: 55 45++ * - First line+ - Source+ * - ``# shirudo config (authenticated config image; TPM settings from runtime image)``+ - The active signed config image. ``tpm.*`` come from the runtime+ image.+ * - ``# shirudo config (effective, loaded from /etc/shirudo/shirudo.conf)``+ - ``/etc/shirudo/shirudo.conf`` on a host without an active config+ image.+ * - ``# shirudo config (no /etc/shirudo/shirudo.conf present; defaults shown)``+ - Built-in defaults.++Without an active config image, ``SHIRUDO_TPM_OWNER_AUTH`` and+``SHIRUDO_TPM_TCTI`` override the file, and the line of each overridden+setting names the variable. ``tpm.owner_auth`` is never printed. The+output gives its length and source instead.++The output is a starting point for a new file on a host without config+images:++.. code-block:: console++ # shirudo config > /etc/shirudo/shirudo.conf++The comments in the output are not a reference. Two of them are wrong: the+``tpm.tcti`` comment points to a section of the documentation that does+not exist, and the ``map_export`` comment says that empty destinations+leave the export timer idle, while the timer runs ``upatch map --all``,+which reads every map and prints it (see :doc:`upatch-map`).+:doc:`/reference/formats/configuration` describes every setting.++Options+-------++``config`` takes no option except ``--help``.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The configuration was printed and is valid.+ * - 1+ - ``/etc/shirudo/shirudo.conf`` exists and cannot be loaded, or the+ printed ``map_export`` or ``tls.classical_hosts`` settings are+ invalid. In the second case the configuration is still printed.+ * - 2+ - An unknown argument.++Files and environment+---------------------++- ``/etc/shirudo/shirudo.conf``+- ``/run/shirudo/config``: the active config image.+- ``SHIRUDO_TPM_OWNER_AUTH``, ``SHIRUDO_TPM_TCTI``: honored only+ without an active config image. The image gate refuses both on an+ enforcing target.++Examples+--------++Print the configuration of a target with an active config image:++.. code-block:: console++ target# shirudo config++The command prints:++.. code-block:: none++ # shirudo config (authenticated config image; TPM settings from runtime image)++ # Eventlog cap; 0 = unlimited. When the log would exceed this,+ # the state-changing op refuses with category: eventlog_full.+ eventlog.max_bytes = 0++ # TPM owner-hierarchy password used at NV-index define time.+ # Empty by default (works on fresh TPMs, swtpm, most cloud VMs);+ # set on TPMs whose owner auth was already provisioned by+ # another tool. Literal string, or `hex:<even hex>` for a+ # binary auth value. May also be supplied via the+ # SHIRUDO_TPM_OWNER_AUTH env var; that override wins.+ # tpm.owner_auth = (unset)++ # TCTI override for the TPM library connection. Empty (default)+ # means the kernel resource manager at `device:/dev/tpmrm0`.+ # Set to `swtpm:host=<addr>,port=<port>` for a software TPM+ # emulator (dev/CI without real hardware); see+ # Documentation/getting-started.rst "TPM in development"+ # for a worked recipe. Pre-flight skips the /dev/tpmrm0 check+ # when this is set. The SHIRUDO_TPM_TCTI env var overrides+ # this in turn.+ tpm.tcti = device:/dev/tpmrm0 # from runtime image++ # Exact DNS hosts that may use classical TLS key exchange.+ # Targets honor this only from the immutable runtime image;+ # operators use the root-managed /etc/shirudo/shirudo.conf.+ # Leave empty for hybrid-only TLS.+ tls.classical_hosts =++ # Periodic `shirudo upatch map --all` export. Empty JSON and+ # OTLP destinations leave the installed timer idle. Every emitted+ # map must carry a signed Lua decoder declaring log or metric.+ # OTEL headers, TLS material, and AWS credentials belong in+ # /etc/shirudo/map-export.env for the systemd service.+ map_export.json_path =+ map_export.otel_endpoint =+ map_export.tenant_id = config-boot-keys+ map_export.otel_insecure = false+ map_export.otel_retries = 3+ map_export.s3_uri =+ map_export.log_record_max_bytes = 1048576+ map_export.otlp_max_bytes = 4194304++Related+-------++- :doc:`/reference/formats/configuration`+- :doc:`/internals/config-images`+- :doc:`image`diff --git a/Documentation/reference/cli/gen-tools.rst b/Documentation/reference/cli/gen-tools.rstnew file mode 100644index 00000000..6439534a--- /dev/null+++ b/Documentation/reference/cli/gen-tools.rst@@ -0,0 +1,325 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Image and initrd generators+===========================++Four Bash scripts build the signed images and the initrd a target boots+with: ``shirudo-gen-image``, ``shirudo-gen-runtime`` and+``shirudo-gen-verity`` on the operator host, ``shirudo-gen-initrd`` on the+target.++.. list-table::+ :header-rows: 1+ :widths: 24 30 46++ * - Script+ - Installed by, to+ - Purpose+ * - ``shirudo-gen-image``+ - operator package, ``$(libexecdir)/shirudo/gen-image/``+ - Build a signed image from a directory.+ * - ``shirudo-gen-runtime``+ - operator package, ``$(libexecdir)/shirudo/gen-image/``+ - Build the signed runtime image and its ``shirudo.service`` drop-in.+ * - ``shirudo-gen-verity``+ - operator package, ``$(libexecdir)/shirudo/gen-image/``+ - Sign an existing ext4 image. ``shirudo image build`` runs it.+ * - ``shirudo-gen-initrd``+ - target package, ``$(bindir)``+ - Build and check the initrd with the dracut module ``90shirudo``.++``$(libexecdir)`` is ``/usr/libexec`` in the distribution packages and+``/usr/local/libexec`` after ``make install``. Every option of the scripts+takes its value as the next argument. None accepts ``--option=<value>``.+A script that fails prints ``<script>: <reason>`` and exits with 1, or+with the status of the tool that failed. ``-h`` and ``--help`` print the+usage on standard output.++Runs on: as listed above. Requires: listed per script. Changes measured+state: no. A target measures the images when it activates them.++shirudo-gen-image+-----------------++.. code-block:: none++ shirudo-gen-image --source <directory> --output <prefix> --keys-dir <dir>+ [--kind config|runtime] [--size <mib>] [--builder <helper>]++Builds an ext4 file system of ``--size`` MiB from ``<directory>`` (owner+root, no journal, 4096-byte blocks) and signs it with+``shirudo-gen-verity``. It writes ``<prefix>.img``, ``.verity``,+``.roothash`` and ``.p7s`` and replaces no existing file.++It refuses a source that contains a file named ``signing_key.pem``, a+special file, a source that contains the keys directory, and for+``--kind config`` any symbolic link. Requires ``mkfs.ext4`` and+``veritysetup``.++.. list-table::+ :header-rows: 1+ :widths: 20 30 50++ * - Option+ - Default+ - Description+ * - ``--source``+ - required+ - Directory that becomes the root of the image.+ * - ``--output``+ - required+ - Output prefix.+ * - ``--keys-dir``+ - required+ - Operator keys directory, outside ``--source``.+ * - ``--kind``+ - ``config``+ - ``config`` or ``runtime``.+ * - ``--size``+ - 64+ - File system size in MiB, 8 to 1048576.+ * - ``--builder``+ - ``$SHIRUDO_BUILD``, else ``shirudo-build``+ - The helper that signs the root hash.++shirudo-gen-runtime+-------------------++.. code-block:: none++ shirudo-gen-runtime --binary <shirudo> --bootstrap-conf <file>+ --cert <certificate> --config-cert <certificate>+ --output <prefix> --keys-dir <dir>+ [--size <mib>] [--builder <helper>]+ [--unit-output <file>] [--extra-binary <file>]...++Builds the runtime image, the image whose root hash the bootstrap+settings pin. It holds:++- ``usr/bin/shirudo``: ``--binary``, the target binary.+- ``etc/shirudo/shirudo.conf``: ``--bootstrap-conf``.+- ``keys/cert.der``: ``--cert``, the initial BPF signing certificate.+- ``etc/shirudo/config-cert.der``: ``--config-cert``, the certificate+ that verifies config images.+- for a dynamically linked binary, its ELF interpreter and libraries+ under their own paths, found with ``ldd``.+- each ``--extra-binary`` under ``usr/bin/`` with its libraries.++It prints the runtime invocation on standard error, for example+``/run/shirudo/runtime/usr/bin/shirudo init`` for a static binary. With+``--unit-output`` it writes a systemd drop-in for ``shirudo.service``+that clears ``EnvironmentFile=`` and ``ExecStart=`` and runs the runtime+binary with ``init``. No drop-in is written for the other units.++``ldd`` runs the inputs' dynamic loader on the operator host: pass only+trusted binaries. Requires ``readelf`` and ``ldd``.++.. list-table::+ :header-rows: 1+ :widths: 20 30 50++ * - Option+ - Default+ - Description+ * - ``--binary``+ - required+ - The ``shirudo`` binary for the target.+ * - ``--bootstrap-conf``+ - required+ - The bootstrap ``shirudo.conf``+ (:doc:`/reference/formats/configuration`).+ * - ``--cert``+ - required+ - The initial BPF signing certificate.+ * - ``--config-cert``+ - required+ - The config image verification certificate.+ * - ``--output``+ - required+ - Output prefix.+ * - ``--keys-dir``+ - required+ - Operator keys directory that signs the image.+ * - ``--size``+ - 128+ - File system size in MiB, 8 to 1048576.+ * - ``--builder``+ - ``$SHIRUDO_BUILD``, else ``shirudo-build``+ - The signing helper.+ * - ``--unit-output``+ - none+ - Write the ``shirudo.service`` drop-in to this new file.+ * - ``--extra-binary``+ - none+ - A further trusted executable for the image. Repeatable.++shirudo-gen-verity+------------------++.. code-block:: none++ shirudo-gen-verity <filesystem-image> -o <prefix> [--kind config|runtime]+ [--keys-dir <dir>] [--key <signing-key>]+ [--cert <certificate>] [--salt <salt>]+ [--builder <helper>]++Formats the dm-verity hash tree of an existing ext4 image with+``veritysetup``, signs the root hash, verifies the result and prints the+root hash. :doc:`image` describes it as ``shirudo image build``, which+passes ``--builder`` itself.++.. list-table::+ :header-rows: 1+ :widths: 20 30 50++ * - Option+ - Default+ - Description+ * - ``-o``, ``--output``+ - required+ - Output prefix.+ * - ``--kind``+ - ``config``+ - ``config`` or ``runtime``. Validated, no other effect.+ * - ``--keys-dir``+ - ``$SHIRUDO_KEYS_DIR``, else ``/var/lib/shirudo/keys``+ - Directory of the signing key and certificate.+ * - ``--key``, ``--cert``+ - from ``--keys-dir``+ - Signing key and certificate.+ * - ``--salt``+ - chosen by ``veritysetup``+ - 64 hexadecimal characters.+ * - ``--builder``+ - ``$SHIRUDO_BUILD``, else ``shirudo-build``+ - The signing helper.++shirudo-gen-initrd+------------------++.. code-block:: none++ shirudo-gen-initrd [--kver <release>] [--output <file>]+ [--cert <certificate>] [--trusted-dir <dir>]+ [--binary <file> --binary-path <path>]+ [--unit <file>] [--bootstrap-conf <file>]+ [--kmoddir <dir>] [--no-kernel] [--module-dir <dir>]+ [-- <dracut-arguments>]+ shirudo-gen-initrd --check [<file>] [--kver <release>] [--output <file>]+ shirudo-gen-initrd --print-cmdline++Runs ``dracut --force --add shirudo`` for a kernel release, then checks+the result. It runs as root and requires ``dracut``. The initrd holds the+binary at its root file system path, the primary certificate as+``/etc/shirudo/keys/cert.der``, the trusted certificates and their vouches+under ``/etc/shirudo/keys/trusted/``, the bootstrap+``/etc/shirudo/shirudo.conf`` and ``shirudo-initrd.service``, enabled.++When the script's own directory holds ``module-setup.sh`` that differs+from ``/usr/lib/dracut/modules.d/90shirudo/module-setup.sh``, it installs+its copy there. Paths given on the command line reach the module through a+generated ``dracut.conf`` that also leaves out the host's drop-ins.++The check lists the archive with ``lsinitrd`` and fails unless it holds+the shirudo binary, ``etc/shirudo/keys/cert.der``,+``etc/shirudo/shirudo.conf``, ``shirudo-initrd.service`` and its+enablement, ``systemd-pcrphase-initrd.service`` and+``etc/initrd-release``. After a build, the script warns when the running+kernel's command line lacks ``bpf.keyring_unsealed=1`` or+``dm_verity.keyring_unsealed=1``.++.. list-table::+ :header-rows: 1+ :widths: 22 33 45++ * - Option+ - Default+ - Description+ * - ``--kver``+ - ``uname -r``+ - Kernel release.+ * - ``--output``+ - ``/boot/initrd.img-<release>`` on Debian without+ ``/boot/loader/entries`` or ``/etc/kernel/cmdline``,+ ``/boot/initramfs-<release>.img`` elsewhere+ - Initrd to write, or to check.+ * - ``--check``+ - the ``--output`` path+ - Only check an initrd.+ * - ``--print-cmdline``+ - off+ - Print the kernel parameters the initrd needs and exit.+ * - ``--cert``+ - ``/var/lib/shirudo/keys/cert.der``+ - Primary certificate to embed.+ * - ``--trusted-dir``+ - ``trusted/`` beside the certificate+ - Further certificates and their vouches.+ * - ``--binary``+ - the installed ``shirudo``+ - Binary to embed. Needs ``--binary-path``.+ * - ``--binary-path``+ - the binary's path+ - Where the binary lives on the root file system.+ * - ``--unit``+ - the installed ``shirudo-initrd.service``+ - Unit to embed.+ * - ``--bootstrap-conf``+ - ``/etc/shirudo/shirudo.conf``+ - Bootstrap settings to embed. The module fails without a readable+ file.+ * - ``--kmoddir``+ - dracut's+ - Take kernel modules from ``<dir>/<release>``.+ * - ``--no-kernel``+ - off+ - Embed no kernel modules.+ * - ``--module-dir``+ - the script's directory+ - Where to install the dracut module from.+ * - ``--``+ -+ - Pass the remaining arguments to ``dracut``.++Examples+--------++Build a config image from a directory:++.. code-block:: console++ operator$ /usr/libexec/shirudo/gen-image/shirudo-gen-image --source ./config-root --output ./config --keys-dir ~/shirudo-keys --kind config++Build the runtime image and its drop-in:++.. code-block:: console++ operator$ /usr/libexec/shirudo/gen-image/shirudo-gen-runtime --binary <target-binary> --bootstrap-conf bootstrap.conf --cert cert.der --config-cert config-cert.der --output ./runtime --keys-dir ~/shirudo-keys --unit-output ./runtime.conf++``<target-binary>`` is the static ``shirudo`` of the target package.++Build the initrd for the running kernel and print the kernel parameters it+needs:++.. code-block:: console++ target# shirudo-gen-initrd --bootstrap-conf <bootstrap-conf>+ target# shirudo-gen-initrd --print-cmdline+ bpf.keyring_unsealed=1 dm_verity.keyring_unsealed=1++``<bootstrap-conf>`` is the bootstrap ``shirudo.conf`` that names the+runtime image (:doc:`/reference/formats/configuration`).++Related+-------++- :doc:`image`+- :doc:`/operate/boot-integration`+- :doc:`/internals/boot-flow`+- :doc:`/internals/config-images`+- :doc:`/reference/formats/configuration`diff --git a/Documentation/reference/cli/genkey.rst b/Documentation/reference/cli/genkey.rstnew file mode 100644index 00000000..13006764--- /dev/null+++ b/Documentation/reference/cli/genkey.rst@@ -0,0 +1,123 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo genkey+==============++Generate an ML-DSA-87 private key and a self-signed X.509 certificate for+signing upatches.++Runs on: operator host, without the image gate. Requires: write+access to the keys directory. Changes measured state: no.++Usage+-----++.. code-block:: none++ shirudo genkey [--force | -f] [--keys-dir <dir> | --keys-dir=<dir>]++Description+-----------++#. ``genkey`` selects the keys directory: ``--keys-dir``, else+ ``$SHIRUDO_KEYS_DIR``, else ``/var/lib/shirudo/keys``.+#. It creates the directory with mode 0700 when it is missing.+#. Run as a user other than root with the default directory, it requires+ every component of the path to be owned by root or that user and not+ writable by group or others, and the directory itself to be owned by+ that user.+#. Without ``--force``, it refuses when ``signing_key.pem`` or+ ``cert.der`` exists in the directory.+#. It generates an ML-DSA-87 key and writes:++ - ``<dir>/signing_key.pem``: the private key, PEM, mode 0600.+ - ``<dir>/cert.der``: a self-signed X.509 certificate, DER, mode 0600,+ subject and issuer ``CN=shirudo``, valid for 3650 days.++#. It logs ``genkey: created shirudo ML-DSA-87 signing material at+ <dir>`` at audit priority.++With ``--force``, ``genkey`` writes the new pair as ``*.new``, keeps the+old key as ``signing_key.pem.old`` until both new files are in place,+then removes the old key. A failure between the two renames puts the old+key back.++The signing commands read a key only when it is a regular file with mode+0600. Pass the same ``--keys-dir`` to :doc:`build`, :doc:`keys`+``vouch``, :doc:`bpm` ``build`` and ``tree append``, and :doc:`image`+``build``. ``bpm push`` ignores ``SHIRUDO_KEYS_DIR`` and signs only with+an explicit ``--keys-dir`` or ``--index-key`` and ``--index-cert``.++.. warning::++ ``--force`` deletes the old private key. A target that trusts only the+ old certificate refuses everything the new key signs, and nothing can+ sign for the old certificate any more. Generate the new pair in+ another directory and vouch for it with the old key first, as+ :doc:`/operate/keys` describes.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 22 12 26 40++ * - Option+ - Argument+ - Default+ - Description+ * - ``--force``, ``-f``+ - none+ - off+ - Replace an existing key and certificate.+ * - ``--keys-dir``+ - ``<dir>``, as the next argument or after ``=``+ - ``$SHIRUDO_KEYS_DIR``, else ``/var/lib/shirudo/keys``+ - Directory to write the pair to.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The pair was written.+ * - 1+ - The pair exists and ``--force`` was not given, the directory is+ unsafe or not writable, or generating or writing failed.+ * - 2+ - An unknown option, or ``--keys-dir`` without a value.++Files and environment+---------------------++- ``<dir>/signing_key.pem``, ``<dir>/cert.der``, and during ``--force``+ ``<dir>/signing_key.pem.new``, ``<dir>/cert.der.new`` and+ ``<dir>/signing_key.pem.old``.+- ``SHIRUDO_KEYS_DIR``: the default directory.++Examples+--------++Create a key pair in a directory the operator owns:++.. code-block:: console++ operator$ shirudo genkey --keys-dir ~/shirudo-keys++Related+-------++- :doc:`keys`+- :doc:`/operate/keys`+- :doc:`/security/cryptography`diff --git a/Documentation/reference/cli/image.rst b/Documentation/reference/cli/image.rstnew file mode 100644index 00000000..fd8aafcb--- /dev/null+++ b/Documentation/reference/cli/image.rst@@ -0,0 +1,219 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo image+=============++Build and verify signed dm-verity images on the operator host, and+activate a signed config image on a target.++Runs on: ``build`` and ``verify`` on the operator host, through the+``shirudo-build`` helper, without the image gate. ``update`` and+``status`` on a target, as root with the runtime binary. Requires: ``veritysetup`` on the+operator host. Changes measured state: ``update`` yes, the others no.++Usage+-----++.. code-block:: none++ shirudo image build <filesystem-image> (--output | -o) <prefix>+ [--kind config|runtime] [--keys-dir <dir>]+ [--key <signing-key>] [--cert <certificate>]+ [--salt <salt>]+ shirudo image verify <prefix> --cert <certificate>+ shirudo image update <prefix>+ shirudo image status+ shirudo image --list-cmds++The subcommand names must be spelled out. ``image`` without a subcommand+prints the usage and exits with 2. ``--list-cmds`` prints+``build verify update status`` on one line.++An image is four files that share a prefix: ``<prefix>.img`` (the ext4+file system), ``<prefix>.verity`` (the hash tree), ``<prefix>.roothash``+(64 lowercase hexadecimal characters) and ``<prefix>.p7s`` (the+ML-DSA-87 signature over those 64 characters).++image build+-----------++The helper runs ``shirudo-gen-verity`` (see :doc:`gen-tools`) with the+arguments, which:++#. checks that the input is a regular file, not a symbolic link,+ non-empty, a multiple of 4096 bytes and at most 1 TiB, and that none of+ the four output files exists,+#. copies the input and runs ``veritysetup format`` with SHA-256, 4096-byte+ blocks and, with ``--salt``, the given salt,+#. signs the root hash with ``shirudo-build image sign-root``, verifies+ the result with ``shirudo-build image verify``, and links the four+ files into place,+#. prints the root hash.++Every option takes its value as the next argument. ``--kind`` must be+``config`` or ``runtime`` and changes nothing else. ``image build+--help`` prints the usage of ``shirudo-gen-verity``. To build the file+system from a directory, use ``shirudo-gen-image`` or+``shirudo-gen-runtime`` (:doc:`gen-tools`).++image verify+------------++The helper reads ``<prefix>.roothash`` and ``<prefix>.p7s``, checks that+``--cert`` is an ML-DSA-87 certificate that signed the root hash, runs+``veritysetup verify`` on the data and hash files it opened, and prints the+root hash. The arguments must come in exactly this order:+``verify <prefix> --cert <certificate>``.++image update+------------++``update`` activates a new signed config image on a target. ``<prefix>``+is a local path prefix or an ``https://`` URL prefix.++#. It fetches ``<prefix>.roothash``, ``.p7s``, ``.img`` and ``.verity``+ into a staging directory under ``/var/lib/shirudo/images``, over HTTPS+ with redirects to HTTPS only, or from local regular files.+#. It checks the signature through the kernel's dm-verity trust path,+ maps the image read-only and reads it completely.+#. It links the files to ``/var/lib/shirudo/images/<root-hash>.*``. When+ the root hash is the active one, it stops here.+#. It maps and mounts the candidate, validates its settings, and checks+ that every signer its trusted set names is already in the ``.bpf``+ keyring. A live update cannot enroll a new key.+#. It records the activation as pending, extends the config PCR named in+ the bootstrap settings with an ``UPDATE`` event, checks the PCR value+ and appends the event to the activation records.+#. It applies the revocations in the image: each revoked certificate+ leaves the ``.bpf`` keyring, the register receives a ``key_revoke``+ event, and every archived upatch the certificate signed is unloaded+ and measured. It mounts the image at ``/run/shirudo/config``.+#. It clears the pending record.++When ``update`` stops between steps 5 and 7, the activation stays pending.+Every command except ``status`` is then refused until the next reboot.+shirudo does not reboot the target.++image status+------------++``status`` prints one JSON object with the active selection:+``root_hash``, ``pcr``, ``sequence``, ``reset_count``, ``restart_count``,+``pending`` and ``consistent``.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 16 22 30 32++ * - Option+ - Argument+ - Default+ - Description+ * - ``-o``, ``--output``+ - ``<prefix>``+ - none, required+ - ``build``: the output prefix.+ * - ``--kind``+ - ``config`` or ``runtime``+ - ``config``+ - ``build``: validated, no other effect.+ * - ``--keys-dir``+ - ``<dir>``+ - ``$SHIRUDO_KEYS_DIR``, else ``/var/lib/shirudo/keys``+ - ``build``: directory of the signing key and certificate.+ * - ``--key``+ - ``<signing-key>``+ - ``<dir>/signing_key.pem``+ - ``build``: the signing key.+ * - ``--cert``+ - ``<certificate>``+ - ``<dir>/cert.der`` for ``build``, required for ``verify``+ - ``build``: the signing certificate. ``verify``: the certificate+ to verify against.+ * - ``--salt``+ - ``<salt>``, 64 hex characters+ - chosen by ``veritysetup``+ - ``build``: the dm-verity salt.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - Success. ``status``: the activation is complete and consistent.+ * - 1+ - ``build``: a failure or a usage error reported by+ ``shirudo-gen-verity``. ``verify``: the signature or the hash tree+ does not verify, or a file is missing. ``update``: refused or+ failed, and while pending ``image: activation is pending; further+ changes are blocked``. ``status``: the activation is pending or+ inconsistent, and the JSON is still printed. ``update`` and ``status``+ on a host without config images fail with ``No such device``.+ * - 2+ - No subcommand, an unknown subcommand, a wrong number of arguments+ to ``update`` or ``status``, or ``verify`` arguments in another+ form.+ * - 127+ - ``build``, ``verify``: ``shirudo`` cannot execute the helper.++``shirudo-gen-verity`` stops at the first failing tool, so ``build`` can+also exit with that tool's status, for example ``veritysetup``'s.++Files and environment+---------------------++- ``build``: the four output files and a temporary directory beside+ them. ``SHIRUDO_KEYS_DIR`` and ``SHIRUDO_BUILD`` set the defaults of+ ``shirudo-gen-verity``.+- ``update``: ``/var/lib/shirudo/images``, ``/var/lib/shirudo/config-update``,+ ``/run/shirudo/config``, the config PCR and the register.++Examples+--------++Sign an ext4 image as a config image:++.. code-block:: console++ operator$ shirudo image build config.ext4 --output config --keys-dir ~/shirudo-keys++Verify an image offline:++.. code-block:: console++ operator$ shirudo image verify config --cert config-cert.der++Activate a config image a web server publishes:++.. code-block:: console++ target# shirudo image update https://config.example/shirudo/config++Show the active selection:++.. code-block:: console++ target# shirudo image status+ {"root_hash":"12dbf3c750834908c0f6510481e35fbb0cc76cf6b1896de524304535e63aff0f","pcr":14,"sequence":1,"reset_count":1,"restart_count":0,"pending":false,"consistent":true}++Related+-------++- :doc:`/internals/config-images`+- :doc:`/concepts/background/dm-verity`+- :doc:`gen-tools`+- :doc:`/reference/formats/configuration`+- :doc:`/operate/keys`diff --git a/Documentation/reference/cli/index.rst b/Documentation/reference/cli/index.rstnew file mode 100644index 00000000..317d09cd--- /dev/null+++ b/Documentation/reference/cli/index.rst@@ -0,0 +1,42 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++CLI+===++One page per command, with the syntax the parser accepts. Every page+states where the command runs, what it requires and whether it changes+measured state, and lists its options, exit statuses and failure+categories.++:doc:`/reference/cli/shirudo` describes what every command shares: how+command names resolve, the runtime binary a target must use, the image+gate that runs before most commands, the ``shirudo-build`` helper and+the exit statuses. :doc:`/reference/cheat-sheet` collects command lines+for common tasks.++.. toctree::+ :titlesonly:++ shirudo+ init+ status+ config+ version+ genkey+ build+ keys+ upatch-load+ upatch-unload+ upatch-list+ upatch-info+ upatch-get+ upatch-map+ bpm+ attest+ attest-verify+ attest-predict+ attest-challenge+ image+ gen-toolsdiff --git a/Documentation/reference/cli/init.rst b/Documentation/reference/cli/init.rstnew file mode 100644index 00000000..73e0f059--- /dev/null+++ b/Documentation/reference/cli/init.rst@@ -0,0 +1,187 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo init+============++Bring up enforcement on a target: enroll and seal the keyrings, attach the+LSM programs, restore the archived upatches and bind the measurement+register.++Runs on: target, as root. In production ``shirudo-initrd.service`` runs it+from the initrd and ``shirudo.service`` runs it again with the runtime+binary after the switch to the root file system. The image gate does not+apply. Requires: the pre-flight checks below, the bootstrap settings in+``/etc/shirudo/shirudo.conf``, and for the first run in a boot the kernel+parameters ``bpf.keyring_unsealed=1`` and ``dm_verity.keyring_unsealed=1``.+Changes measured state: yes.++Usage+-----++.. code-block:: none++ shirudo init [--check-only]++Description+-----------++#. ``init`` loads the authenticated bootstrap settings: from+ ``/etc/shirudo/shirudo.conf``, which must name the runtime image and its+ root hash, or from the frozen identity when enforcement is already up.+#. It runs the pre-flight checks and prints them. With ``--check-only`` it+ stops here.+#. In the initrd (``/etc/initrd-release`` exists), it requires a tmpfs or+ ramfs root and binds ``/sysroot/var/lib/shirudo`` writable over+ ``/var/lib/shirudo``. The bind is detached when ``init`` exits.+#. It mounts the private bpffs at ``/run/shirudo/bpffs``.+#. On the first run in a boot it mounts the runtime image, enrolls the+ config certificate into the ``.dm-verity`` keyring and seals it,+ selects the signed config for this boot, then enrolls the trusted+ certificate set into the ``.bpf`` keyring and seals it. On a later run+ it checks that the frozen identity names the same ``.bpf`` keyring and+ runtime image.+#. It labels the persistent state, adopts the eventlog that the initrd+ run left in ``/run/shirudo/eventlog.pending``, and loads and pins the+ enforcement programs.+#. It mounts the authenticated runtime image at ``/run/shirudo/runtime``.+#. It begins the config ``BOOT`` event: it records the selection as+ pending, extends the config PCR named in the bootstrap settings and+ mounts the config image at ``/run/shirudo/config``.+#. It restores every upatch archived in ``/var/lib/shirudo/upatches``,+ all or nothing. An upatch already loaded with the archived payload is+ kept. An archived upatch that is not loaded after this boot's register+ was bound is refused as tampered.+#. It binds the measurement register under PCRs 9 and 11 and records one+ init event that covers the certificate set, the restored upatches and+ the upatch tree root.+#. It completes the config ``BOOT`` event.++Measurement: the config PCR receives one ``BOOT`` event per boot. The+measurement register receives one init event per boot. A second run in the+same boot after a successful first one adds no event.++A failure after the ``BOOT`` event began, in the restore or in binding the+register, leaves the config activation pending. The help text of+``init`` calls it idempotent, but in that state a second run fails and the+image gate refuses every command except ``status`` until the next reboot.+The next boot restores the same archive. See+:doc:`/operate/troubleshooting`.++Pre-flight checks+~~~~~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Check+ - Passes when+ * - ``root``+ - ``init`` runs as root.+ * - ``bpf_lsm_active``+ - The BPF LSM is active.+ * - ``bpffs_supported``+ - The kernel supports bpffs.+ * - ``signed_loader_kernel_abi``+ - The kernel has the signed-loader interface.+ * - ``cert_on_disk``+ - The primary certificate exists: ``/etc/shirudo/keys/cert.der`` in+ the initrd, ``/run/shirudo/runtime/keys/cert.der`` with an active+ config image, ``/var/lib/shirudo/keys/cert.der`` otherwise.+ * - ``cert_algorithm``+ - Every trusted certificate holds an ML-DSA-87 key.+ * - ``cert_kernel_support``+ - The kernel can parse every trusted certificate. The check adds+ each to the thread keyring and clears it again.+ * - ``kernel_keyring``+ - The kernel has keyrings and a ``.bpf`` keyring.+ * - ``embedded_loader``+ - The enforcement BPF objects embedded in the binary are present.+ * - ``tpm2_reachable``+ - A TPM answers on the configured TCTI.++``--check-only`` changes no persistent or enforcement state. It reads the+TPM and probes the keyring as described.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 22 12 12 54++ * - Option+ - Argument+ - Default+ - Description+ * - ``--check-only``+ - none+ - off+ - Run and print the pre-flight checks, then exit.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - Enforcement is up, or with ``--check-only`` every check passed.+ * - 1+ - The bootstrap settings cannot be loaded+ (``init: authenticated image settings: <error>``), a pre-flight+ check failed (``init: pre-flight failed (<n>/<m> checks)``), or a+ phase failed (``init: <phase> failed: <error>``).+ * - 2+ - An unknown option.++Files and environment+---------------------++- Reads ``/etc/shirudo/shirudo.conf``, ``/etc/shirudo/keys/`` in the+ initrd, the runtime and config images the bootstrap settings name,+ ``/var/lib/shirudo/images``, ``/var/lib/shirudo/upatches``, ``/var/lib/shirudo/eventlog`` and+ ``/var/lib/shirudo/config-update``.+- Writes ``/run/shirudo/bpffs``, ``/run/shirudo/eventlog.pending`` in the+ initrd, ``/var/lib/shirudo/eventlog`` and the config activation records+ in ``/var/lib/shirudo/config-update``.+- ``SHIRUDO_INIT_ARGS`` in ``/etc/shirudo/init.env`` is passed by the+ shipped ``shirudo.service``. The runtime drop-in replaces that command+ line with ``init`` alone.++Examples+--------++Run the pre-flight checks on a target:++.. code-block:: console++ target# shirudo init --check-only+ pre-flight checks:+ root OK+ bpf_lsm_active OK+ bpffs_supported OK+ signed_loader_kernel_abi OK+ cert_on_disk OK+ cert_algorithm OK+ cert_kernel_support OK+ kernel_keyring OK+ embedded_loader OK+ tpm2_reachable OK: TCTI override: device:/dev/tpmrm0+ 10/10 passed (0 failed)++Related+-------++- :doc:`/operate/initialize`+- :doc:`/internals/boot-flow`+- :doc:`/operate/boot-integration`+- :doc:`status`diff --git a/Documentation/reference/cli/keys.rst b/Documentation/reference/cli/keys.rstnew file mode 100644index 00000000..1a29eb97--- /dev/null+++ b/Documentation/reference/cli/keys.rst@@ -0,0 +1,227 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo keys+============++Show the key material this host holds, and vouch for or add a signing+certificate.++Runs on: any host for the display, the operator host for ``vouch``, and+only a host without an active config image for ``add``. Requires: root on a target,+with the runtime binary. Changes measured state: no.++Usage+-----++.. code-block:: none++ shirudo keys [--keys-dir <dir> | --keys-dir=<dir>]+ shirudo keys add <certificate> (--vouch <vouch> | --vouch=<vouch>)+ [--keys-dir <dir> | --keys-dir=<dir>]+ shirudo keys vouch <certificate> [-o <vouch>]+ [--keys-dir <dir> | --keys-dir=<dir>]+ [--key <signing-key>] [--cert <certificate>]+ shirudo keys revoke+ shirudo keys --list-cmds++``keys`` without a subcommand, or with an option first, shows the key+material. ``shirudo keys --help`` advertises ``keys revoke <fingerprint>+[--promote <fp>]``, but the parser takes no argument and always refuses.++Display+-------++``shirudo keys`` prints what is present:++- the certificate ``cert.der`` and the signing key ``signing_key.pem`` in+ the keys directory: subject, issuer, algorithm, both fingerprints and+ validity.+- the trusted set, when it has more than the primary certificate or+ holds revoked or unvouched entries: each member's SPKI fingerprint, the+ SHA-256 of its certificate and the certificate that vouched for it.+- the ``.bpf`` keyring ``init`` froze: its serial, the frozen serial and+ the keys in it.++The keys directory is ``--keys-dir``, else ``$SHIRUDO_KEYS_DIR``, else+``/var/lib/shirudo/keys``. On a target with an active config image it is+always the runtime image's ``/run/shirudo/runtime/keys``, and the image+gate refuses ``--keys-dir``.++keys add+--------++``keys add`` installs a certificate into the trusted set of a keys+directory, so that ``init`` enrolls it at the next boot:++#. It refuses on a host with an active config image, which every+ production target has, with ``target: add vouched BPF signers to the+ signed config selected for boot and reboot to enroll them``. On such a+ target, add vouched signers to the signed config image instead (see+ :doc:`/operate/keys`).+#. It requires an ML-DSA-87 certificate and a trusted set under the keys+ directory, and refuses a certificate listed under ``<dir>/revoked``.+#. The vouch must verify under a certificate already in the set. With the+ default keys directory, that certificate must also be in the ``.bpf``+ keyring this boot.+#. A certificate already in the set is reported and left alone. The set+ holds at most 16 certificates.+#. It installs the certificate and its vouch under ``<dir>/trusted``,+ logs ``keys add: fingerprint=<fp> vouched_by=<fp> path=<path>`` at+ audit priority, and prints the certificate's fingerprint.++The new certificate takes effect when the initrd is rebuilt with it+(``shirudo-gen-initrd``) and the target reboots.++keys vouch+----------++``keys vouch`` executes the ``shirudo-build`` helper, which signs a vouch+for another certificate with this operator's key:++#. It resolves the key and certificate like :doc:`build`.+#. It refuses a certificate that is not ML-DSA-87 and the operator's own+ certificate.+#. It writes the vouch to ``-o``, else ``<certificate>.vouch``, and prints+ the vouched certificate's fingerprint.++keys revoke+-----------++``keys revoke`` takes no argument and always fails with:++.. code-block:: none++ keys revoke: put revocation records in a signed config image, then run `shirudo image update`++A revocation is the revoked certificate, placed in a signed config image as+``keys/revoked/<fingerprint>.der``, where ``<fingerprint>`` is the+lowercase hexadecimal SHA-256 of its public key (SPKI). When :doc:`image` ``update`` activates that image, the target+removes the certificate from the ``.bpf`` keyring, measures a+``key_revoke`` event in the register and unloads every archived upatch the+certificate signed (see :doc:`/operate/keys`).++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 18 22 25 35++ * - Option+ - Argument+ - Default+ - Description+ * - ``--keys-dir``+ - ``<dir>``, next argument or after ``=``+ - ``$SHIRUDO_KEYS_DIR``, else ``/var/lib/shirudo/keys``+ - Display, ``add`` and ``vouch``: the keys directory.+ * - ``--vouch``+ - ``<vouch>``, next argument or after ``=``+ - none, required+ - ``add``: the vouch an enrolled key signed for the certificate.+ * - ``-o``+ - ``<vouch>``+ - ``<certificate>.vouch``+ - ``vouch``: where to write the vouch.+ * - ``--key``+ - ``<signing-key>``+ - from the keys directory+ - ``vouch``: the signing key.+ * - ``--cert``+ - ``<certificate>``+ - from the keys directory+ - ``vouch``: the signing certificate.+ * - ``--list-cmds``+ - none+ -+ - Print ``add``, ``revoke`` and ``vouch``, one per line.++``vouch`` takes ``-o``, ``--key`` and ``--cert`` with the value as the next+argument only.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - Display: key material was found and the keyring is consistent.+ ``add``: the certificate is trusted. ``vouch``: the vouch was+ written.+ * - 1+ - Display: no key material on the host, or a certificate or the+ frozen keyring cannot be read. ``add``: refused or failed, including on a host with an+ active config image. ``vouch``: the key is unusable or signing+ failed. ``revoke``: always.+ * - 2+ - An unknown option or subcommand, a missing certificate or+ ``--vouch``, an extra argument, or an unusable keys directory path.+ * - 127+ - ``vouch``: ``shirudo`` cannot execute the helper.++Files and environment+---------------------++- ``<dir>/cert.der``, ``<dir>/signing_key.pem``, ``<dir>/trusted/``,+ ``<dir>/revoked/``.+- ``/run/shirudo/runtime/keys`` on a target with a config image.+- ``SHIRUDO_KEYS_DIR``: the default keys directory, refused by the image+ gate.++Examples+--------++Show the key material on a target:++.. code-block:: console++ target# shirudo keys+ Cert (/run/shirudo/runtime/keys/cert.der):+ Subject: /CN=shirudo+ Issuer: /CN=shirudo (self-signed)+ Public-key: ML-DSA-87+ Fingerprint: SHA256:d95db97ff4658b96b8b538afef41a25ca9f7a2c4d0abffdb26cbac7b0ba294b9+ SPKI fingerprint: SHA256:d1dc6624ee6bd0c277864fab0a8a15f8509308aa2338768cb772117c157f8d61+ Valid from: 2026-10-29T16:16:30Z+ Valid until: 2036-10-26T16:16:30Z+ Expires in: 9y 364d++ Signing key (/run/shirudo/runtime/keys/signing_key.pem):+ Present: no (target host -- private key lives on the operator)++ Trusted set (2 members, 0 revoked, 0 unvouched):+ 2edb279c05efee6b489a65ae07fd6d402a54b6e495be68f6d364544e9b5a37e2+ sha256 3702e8ffe817ade6151eea338194649cc3a5be1e0b940e462a1a75e52f7095d0+ vouched by d1dc6624ee6bd0c277864fab0a8a15f8509308aa2338768cb772117c157f8d61+ d1dc6624ee6bd0c277864fab0a8a15f8509308aa2338768cb772117c157f8d61 (primary)+ sha256 d95db97ff4658b96b8b538afef41a25ca9f7a2c4d0abffdb26cbac7b0ba294b9++ Keyring (.bpf):+ Serial: 420195959+ Frozen serial: 420195959 (matches)+ Members (2):+ serial=410418068 type=asymmetric shirudo: d10a391a9f1067ed9f64e4ea9b738cf9258b478a+ serial=746517937 type=asymmetric shirudo: 6935ce2048ec5a5ed607db8f5ac1c005c29f32a4++Vouch for a second operator's certificate:++.. code-block:: console++ operator$ shirudo keys vouch other-cert.der -o other-cert.der.vouch --keys-dir ~/shirudo-keys++Related+-------++- :doc:`/operate/keys`+- :doc:`genkey`+- :doc:`image`+- :doc:`/security/cryptography`diff --git a/Documentation/reference/cli/shirudo.rst b/Documentation/reference/cli/shirudo.rstnew file mode 100644index 00000000..37955b14--- /dev/null+++ b/Documentation/reference/cli/shirudo.rst@@ -0,0 +1,264 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: All readers++shirudo+=======++``shirudo`` runs one command of the operator or the target, and hands the+operator-only commands to the ``shirudo-build`` helper.++Runs on: any host. Requires: locked process memory (``CAP_IPC_LOCK`` or a+large enough ``RLIMIT_MEMLOCK``). Changes measured state: depends on the+command.++Usage+-----++.. code-block:: none++ shirudo <command> [<args>]+ shirudo help [--list-cmds]+ shirudo --help | -h+ shirudo --list-cmds++Commands+--------++.. list-table::+ :header-rows: 1+ :widths: 18 30 52++ * - Command+ - Runs on+ - Summary+ * - :doc:`genkey`+ - operator host+ - Generate the ML-DSA-87 signing key and certificate.+ * - :doc:`build`+ - operator host, through the helper+ - Compile and sign a ``.upatch``, or sign an unload directive.+ * - :doc:`init`+ - target+ - Bring up enforcement and bind the measurement register.+ * - ``upatch``+ - target, and ``info`` on any host+ - :doc:`upatch-load`, :doc:`upatch-unload`, :doc:`upatch-list`,+ :doc:`upatch-info`, :doc:`upatch-get`, :doc:`upatch-map`.+ * - :doc:`bpm`+ - target, and the operator host for ``build``, ``push``,+ ``tree append`` and ``config update``+ - Install, upgrade and remove signed packages. Build and publish+ them.+ * - :doc:`image`+ - the operator host for ``build`` and ``verify``, the target for+ ``update`` and ``status``+ - Build, verify and activate signed config images.+ * - :doc:`status`+ - any host+ - Readiness and state report.+ * - ``attest``+ - target for :doc:`evidence <attest>`, operator host for+ :doc:`attest-verify`, :doc:`attest-predict` and+ :doc:`attest-challenge`+ - TPM-signed evidence and its offline verification.+ * - :doc:`keys`+ - any host, and the operator host for ``vouch``+ - Show key material and vouch for a certificate.+ * - :doc:`version`+ - any host+ - Print the release and ``SHIRUDO_VERSION_ID``.+ * - :doc:`config`+ - any host+ - Print the effective ``shirudo.conf``.+ * - ``help``+ - any host+ - Print the command list.++Description+-----------++Every invocation goes through the same steps before the command runs:++#. Standard input, output and error that are closed are reopened on+ ``/dev/null``.+#. The process hardens itself: it is not dumpable, sets+ ``no_new_privs``, writes no core file, loads no OpenSSL configuration+ file, resolves host names through ``files`` and ``dns`` only and locks+ all its memory with ``mlockall()``. When the lock fails, ``shirudo``+ prints ``hardening: cannot lock process memory: <error>`` and exits+ with 1. The shipped systemd units set ``LimitMEMLOCK=infinity``.+#. ``shirudo`` resolves the command name (see below).+#. On a target where enforcement is up, the image gate runs (see below).+#. The command runs.++Progress, warning and error messages go to standard error and to syslog+with the identifier ``shirudo`` and the facility ``LOG_AUTHPRIV``, where+journald picks them up. Results go to standard output. Help text goes to+standard error, except the help of the+``shirudo-build`` helper and of the generator scripts, which goes to+standard output.++Command names+~~~~~~~~~~~~~++``shirudo`` accepts a command name in three forms, tried in this order:++#. The exact name.+#. A unique prefix: ``shirudo stat`` runs ``status``. A prefix that+ matches more than one command (``shirudo i``) prints the matches and+ exits with 1.+#. An input that starts with a command name: ``shirudo initialize`` runs+ ``init``.++An unknown name prints ``'<input>' is not a shirudo command.``, a list of+similar names, and exits with 1. The subcommands of ``upatch``, ``keys``,+``attest``, ``bpm`` and ``bpm key`` resolve the same way. The subcommands+of ``image``, the actions of ``bpm config register`` and the words+``repo update``, ``tree sync`` and ``tree append`` must be spelled out.++``shirudo --list-cmds`` and ``shirudo help --list-cmds`` print the+command names one per line. Bash completion reads them from there.++Runtime binary+~~~~~~~~~~~~~~++On a production target, run every target command with the binary on the+authenticated runtime image, ``/run/shirudo/runtime/usr/bin/shirudo``. A+dynamically linked build runs through the loader and libraries on the+same image:++.. code-block:: none++ /run/shirudo/runtime<interpreter> --inhibit-cache --library-path <library-path> \+ /run/shirudo/runtime/usr/bin/shirudo <command> [<args>]++``<interpreter>`` and ``<library-path>`` are the values+``shirudo-gen-runtime`` prints when it builds the image (see+:doc:`gen-tools`). The examples in this reference show the runtime binary+as ``shirudo``.++The LSM grants runtime authority only to a process that executed the+authenticated runtime binary (see :doc:`/internals/seal`). Any other copy+of the binary, the one in ``/usr/bin`` included, is refused before the+command runs:++.. code-block:: console++ target# /usr/local/bin/shirudo status+ shirudo: image state: Permission denied++The drop-in that ``shirudo-gen-runtime --unit-output`` writes changes+``shirudo.service`` only. The other shipped services run the+``shirudo`` installed in ``bindir`` (see :doc:`/reference/systemd-units`).++Image gate+~~~~~~~~~~++Before every command except ``init``, ``genkey``, ``build``, ``help``,+``version``, ``image build`` and ``image verify``, ``shirudo`` checks the+state of the target:++- On a host where enforcement is not up and the identity pin+ ``/run/shirudo/bpffs/identity`` does not exist or cannot be read, the+ gate does nothing. Operator hosts are in this state.+- Where enforcement is up, the gate reads the frozen identity, loads the+ authenticated bootstrap and runtime settings, and then refuses with+ ``EPERM``:++ - any argument that begins with ``--keys-dir``, ``--cert`` or+ ``--tcti``,+ - any of the environment variables ``SHIRUDO_KEYS_DIR``,+ ``SHIRUDO_TPM_TCTI``, ``SHIRUDO_TPM_OWNER_AUTH``,+ ``SHIRUDO_EVENTLOG_PATH``, ``SHIRUDO_EVENTLOG_PENDING_PATH``,+ ``SHIRUDO_INITRD_RELEASE`` and ``SHIRUDO_SYSROOT``, with+ ``bootstrap override <name> is forbidden``.++- The gate then requires a config activation that is complete and+ consistent with its records. While an activation is pending or cannot+ be verified, only ``status`` runs.++A refusal prints ``shirudo: image state: <error>`` and exits with 1.++Operator helper+~~~~~~~~~~~~~~~++``build``, ``keys vouch``, ``image build``, ``image verify``, ``bpm+build``, ``bpm push``, ``bpm tree append`` and ``bpm config update`` run+in the separate ``shirudo-build`` binary, which the operator package+installs. ``shirudo`` executes the first of:++#. ``$SHIRUDO_BUILD``. An empty value is refused.+#. The path compiled in from ``libexecdir``:+ ``/usr/libexec/shirudo/shirudo-build`` in the distribution packages,+ ``/usr/local/libexec/shirudo/shirudo-build`` after ``make install``.+ ``shirudo build --help`` prints the path this binary uses.+#. ``shirudo-build`` on ``PATH``.++When the helper cannot be executed, ``shirudo`` prints why and exits with+127. ``shirudo bpm --help`` lists ``build`` and ``push`` only when the+helper resolves.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The command succeeded.+ * - 1+ - The command failed or was refused, the image gate refused it, the+ command name is unknown or ambiguous, or ``shirudo`` ran without+ a command.+ * - 2+ - Most commands: a usage error. Several commands use 1 and 2+ differently. Each command page lists its own.+ * - 127+ - The ``shirudo-build`` helper is missing or cannot be executed.++``shirudo status`` exits with 0 whatever the verdict. Read the verdict+from its output, not from the exit status. The failure categories that+``upatch load``, ``upatch unload`` and the reports name are listed in+:doc:`/reference/failure-categories`.++Files and environment+---------------------++- ``SHIRUDO_BUILD``: the helper to execute.+- ``PATH``: searched for ``shirudo-build`` last.+- ``/run/shirudo/bpffs/identity``: the identity pin the image gate reads.++:doc:`/reference/environment` and :doc:`/reference/files` list every+variable and path.++Examples+--------++Print the version of any copy of the binary. ``version`` does not go+through the image gate:++.. code-block:: console++ $ shirudo version+ shirudo (58d3fa7-dirty-rc0, "Social BPF Coding")+ version-id: 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0++Run an operator command with a helper from a checkout:++.. code-block:: console++ operator$ SHIRUDO_BUILD=$PWD/tools/shirudo-build/shirudo-build shirudo build fix.bpf.c++Related+-------++- :doc:`/concepts/operator-and-target`+- :doc:`/reference/cheat-sheet`+- :doc:`/reference/failure-categories`diff --git a/Documentation/reference/cli/status.rst b/Documentation/reference/cli/status.rstnew file mode 100644index 00000000..6c09f00c--- /dev/null+++ b/Documentation/reference/cli/status.rst@@ -0,0 +1,248 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo status+==============++Report the local readiness and state of this host, and optionally send the+report as an OTLP keepalive.++Runs on: any host, and on a target as root with the runtime binary. It is the+only command that runs while a config activation is pending or cannot be+verified. Requires: nothing. It runs before ``init`` too. Changes measured+state: no.++Usage+-----++.. code-block:: none++ shirudo status [--json] [--otel] [--include-system] [--include-eventlog]+ [--include-kernellog | --include-kernellog=<lines>]+ [--include-modules] [--show-full]++Description+-----------++``status`` reads the state of the host without changing it and prints a+report. The roles come from what is present:++- target: the certificate (:doc:`init` lists its path), the pinned LSM+ link ``/run/shirudo/bpffs/lsm_link`` or the ``.bpf`` keyring that+ ``init`` froze.+- operator: ``/var/lib/shirudo/keys/signing_key.pem``.++``Mode`` is ``production`` when the LSM link is pinned and ``inactive``+otherwise. It says nothing about the keyring. The ``KeyringSealed``+condition does.++The report shows five conditions, each ``OK``, ``WARN`` or ``ALERT``:+``LsmAttached``, ``KeyringSealed``, ``ChainIntact``, ``TpmMeasured`` and+``ConfigActive``. The verdict is the first of these that applies:++.. list-table::+ :header-rows: 1+ :widths: 20 80++ * - Verdict+ - Applies when+ * - ``tampered``+ - The live register differs from the eventlog replay, the ``.bpf``+ keyring is not the one ``init`` froze or is gone, or the selected+ config cannot be verified against its records.+ * - ``lsm-off``+ - The LSM link is not pinned.+ * - ``init-pending``+ - ``init`` has not frozen a ``.bpf`` keyring this boot.+ * - ``reboot-pending``+ - A config activation is pending until the next reboot.+ * - ``degraded``+ - No TPM answered, or no register is bound this boot.+ * - ``ok``+ - None of the above.++The human report follows the verdict with the tamper counters that moved+this boot, the ``.bpf`` keyring and the trusted certificates, the loaded+upatches, the TPM measurement state and the assets under+``/var/lib/shirudo``. :doc:`/operate/read-status` explains each field and+:doc:`/reference/formats/status-json` the JSON document.++With ``--otel``, ``status`` builds the JSON report and sends it as one+OTLP log record named ``shirudo.keepalive``, only when an endpoint is+configured: ``map_export.otel_endpoint``, else+``OTEL_EXPORTER_OTLP_LOGS_ENDPOINT``, else+``OTEL_EXPORTER_OTLP_ENDPOINT``. Without an endpoint it sends nothing and+says nothing, except while a config activation is pending or unverifiable,+when it prints a warning. ``--otel`` alone prints nothing on standard+output. Add ``--json`` to print the document too.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 26 14 12 48++ * - Option+ - Argument+ - Default+ - Description+ * - ``--json``+ - none+ - off+ - Print the report as one JSON document.+ * - ``--otel``+ - none+ - off+ - Send the JSON report as an OTLP keepalive log record.+ * - ``--include-system``+ - none+ - off+ - Add a ``system`` section: host, operating system, kernel and its+ build ID, machine, boot ID, CPUs, memory, disk and uptime.+ * - ``--include-eventlog``+ - none+ - off+ - Add the eventlog entries.+ * - ``--include-kernellog``+ - ``<lines>``, 1 to 100, after ``=``+ - 10+ - Add the last lines of the kernel ring buffer.+ * - ``--include-modules``+ - none+ - off+ - Add the 10 most recently loaded kernel modules.+ * - ``--show-full``+ - none+ - off+ - Turn on every ``--include-*`` option and print the module+ dependency tree.++Exit status+-----------++``status`` exits with 0 whatever the verdict, ``tampered`` included.+Monitoring must read ``.status`` and the conditions from the JSON+document.++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The report was produced.+ * - 1+ - With ``--otel``: the configuration cannot be loaded or the OTLP+ request failed. With ``--json``: the document does not fit the+ output buffer. Also an allocation failure.+ * - 2+ - An unknown option, a ``--include-kernellog`` value outside 1 to+ 100, or with ``--otel`` an invalid ``map_export`` configuration.++Files and environment+---------------------++- Reads ``/run/shirudo/bpffs`` (pins, identity, tamper counters), the+ ``.bpf`` keyring, the TPM register, ``/var/lib/shirudo/eventlog``,+ ``/var/lib/shirudo/keys`` and the config activation records.+- With ``--otel``: ``map_export.*`` and the ``OTEL_EXPORTER_OTLP_*``+ variables (see :doc:`/reference/environment`).+ ``shirudo-keepalive.service`` reads them from+ ``/etc/shirudo/map-export.env``.++Examples+--------++Show the state of a target:++.. code-block:: console++ target# shirudo status+ Host: docs+ Roles: target+ Mode: production+ Status: ok+ Version-ID: 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0++ Conditions:+ TYPE STATUS DETAIL+ LsmAttached OK lsm/bpf link present and pinned+ KeyringSealed OK serial=420195959 in the BPF keyring, pin matches+ ChainIntact OK live register == eventlog replay+ TpmMeasured OK NV index 0x01818E00 readable+ ConfigActive OK config 12dbf3c75083.. is active++ Tamper attempts (refused this boot):+ LoadNotLoader 27 program load that is not a signed loader+ MapCreate 1 map creation by another executable+ BpfCommand 12 detach, update, delete or unclassified bpf() command+ SealPtrace 7 ptrace of a shirudo task++ Keyring (.bpf):+ Serial: 420195959+ Frozen serial: 420195959 (matches)+ Certificates: 2 trusted, 0 revoked, 0 unvouched, 2 in the bpf keyring+ 2edb279c05efee6b489a65ae07fd6d402a54b6e495be68f6d364544e9b5a37e2+ d1dc6624ee6bd0c277864fab0a8a15f8509308aa2338768cb772117c157f8d61 (primary)++ upatches loaded (1):+ NAME LOCATION MAPS STATUS AGE+ shirudo-test-basic fentry/do_nanosleep 0 success 1s++ TPM Measurement:+ TPM: reachable (device:/dev/tpmrm0)+ NV index: 0x01818E00 (anchored in PCR 9)+ Chain: c50b22ac27c5bb6a90ee5ff9b440fbbd5bb60b84a2aa7b395daec3f330886fcd+ Register name: 000be3a552e2219550d2597ab96f3fffdeec0d01ce27cde858e0858ab0cdaba6c045+ Anchored: yes (name on record)+ PCR before init: 0000000000000000000000000000000000000000000000000000000000000000+ Phase at init: 0000000000000000000000000000000000000000000000000000000000000000 (PCR 11)+ Bound in: initrd+ Chain vs eventlog: matches+ Eventlog: /var/lib/shirudo/eventlog (2 entries, 2324 bytes)++ Assets (/var/lib/shirudo):+ keys/cert.der present+ keys/signing_key.pem absent+ eventlog present (2324 bytes)+ upatches/ 1 .upatch+ incoming/ empty+ bpffs/ mounted++Read the verdict in a script:++.. code-block:: console++ target# shirudo status --json | jq -r .status+ ok++Add this boot's eventlog to the report:++.. code-block:: console++ target# shirudo status --include-eventlog++The eventlog section of that report:++.. code-block:: none++ Eventlog (audit trail):+ TIME TYPE DIGEST DETAIL+ 2026-10-29T16:17:38Z init cb206abf8e51 set_digest=e3b0c44298fc..+ 2026-10-29T16:21:19Z upatch_load d979b373d4e5 shirudo-test-basic payload=8aee7072a1a1..+ 2026-10-29T16:21:20Z upatch_unload 26dae981e9bb shirudo-test-basic payload=8aee7072a1a1..++Related+-------++- :doc:`/operate/read-status`+- :doc:`/reference/formats/status-json`+- :doc:`/security/tamper-counters`+- :doc:`/operate/incident-tampered`+- :doc:`/operate/telemetry`diff --git a/Documentation/reference/cli/upatch-get.rst b/Documentation/reference/cli/upatch-get.rstnew file mode 100644index 00000000..e797e261--- /dev/null+++ b/Documentation/reference/cli/upatch-get.rst@@ -0,0 +1,109 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo upatch get+==================++Describe a loaded upatch as the kernel holds it: attach point, program+source from BTF line info, and its pinned maps with their contents.++Runs on: target, as root with the runtime binary. Requires: the upatch is+loaded. Changes measured state: no.++Usage+-----++.. code-block:: none++ shirudo upatch get <name> [--json] [--show-full]++Description+-----------++``get`` opens the first link of the upatch ``<name>`` and reports:++- ``Location``: the attach point in ``SEC()`` form, for example+ ``fentry/do_nanosleep``.+- the program ID, the load time and the payload digest recorded on the+ pin.+- the source lines from the program's BTF line info, which the signed+ loader installed. They are exact but cover only the lines the compiler+ kept.+- every pinned map with its BTF key and value types and its contents.++``get`` reads serializer-backed maps without draining them, so it does not+take records from the export timer. It uses only reads the LSM allows to+the runtime binary.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 18 12 12 58++ * - Option+ - Argument+ - Default+ - Description+ * - ``--json``+ - none+ - off+ - Print one JSON object: ``schema`` and ``upatch`` with ``name``,+ ``location``, ``prog_id``, ``loaded_at``, ``age``,+ ``payload_sha256``, ``source`` and ``maps``.+ * - ``--show-full``+ - none+ - off+ - Print every map entry instead of the first 256 of each map.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The upatch was described. A map that cannot be read is reported in+ the output.+ * - 1+ - The upatch is not loaded or its program cannot be read+ (``upatch get: '<name>': <error>``), or the JSON document could not+ be built.+ * - 2+ - No name, a second name, an unknown option or an invalid name.++Examples+--------++Describe a loaded upatch:++.. code-block:: console++ target# shirudo upatch get shirudo-test-basic+ upatch: shirudo-test-basic+ Location: fentry/do_nanosleep+ Prog id: 65+ Loaded at: 2026-10-29T16:21:18Z (1s ago)+ Payload: 8aee7072a1a15e4dddc93ad6b253a0e2e70ad6cdf767442aa8a1c1997bc3069f (signature-bound)+ Maps (0):++ Source (kernel BTF line_info):++ /home/darkstar/shirudo/testing/fixtures/basic.bpf.c:+ 9: int BPF_PROG(shirudo_test_basic)++Related+-------++- :doc:`upatch-list`+- :doc:`upatch-map`+- :doc:`upatch-info`+- :doc:`/upatches/debugging`diff --git a/Documentation/reference/cli/upatch-info.rst b/Documentation/reference/cli/upatch-info.rstnew file mode 100644index 00000000..14d46297--- /dev/null+++ b/Documentation/reference/cli/upatch-info.rst@@ -0,0 +1,136 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: All readers++shirudo upatch info+===================++Describe a ``.upatch`` file offline: header, signature, payload digest,+signed sections and decoders.++Runs on: any host, and on a target with the runtime binary. Requires: read+access to the file. Changes measured state: no.++Usage+-----++.. code-block:: none++ shirudo upatch info [--json] <file>++Description+-----------++``info`` parses the file and prints what it carries. It reads no kernel+state and checks no signature. The target checks the signature when it+loads the artifact. For a loaded upatch as the kernel holds it, use+:doc:`upatch-get`.++The human output has these parts:++- the file, name, type (``LOAD`` or ``UNLOAD-directive``), payload type,+ format version, payload digest and size.+- the loader: offset and length of its instructions, the log buffer+ size, its metadata and its data.+- the signature: offset and length.+- the signed sections: the name, the length of the attach metadata and,+ for a directive, the expected payload digest.+- the decoders: target upatch and map, language and API version, input+ format, export signal (``log`` or ``metric``) and source.++:doc:`/reference/formats/upatch-format` describes each field.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 14 12 12 62++ * - Option+ - Argument+ - Default+ - Description+ * - ``--json``+ - none+ - off+ - Print one JSON object: ``schema``, ``path``, ``name``, ``type``,+ ``payload_type``, ``version``, ``payload_sha256``,+ ``loader_insns_len``, ``signature_len``, ``metadata_len``,+ ``data_len``, ``log_buf_sz``, ``file_size``, ``signed_name``,+ ``attach_metadata_len``, ``unload_payload_sha256`` and+ ``decoders``.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The file was described.+ * - 1+ - The file cannot be opened or is not a valid ``.upatch``.+ * - 2+ - No file, a second file or an unknown option.++Examples+--------++Describe an artifact:++.. code-block:: console++ operator$ shirudo upatch info basic.upatch+ File: basic.upatch+ Name: basic+ Type: LOAD+ Payload type: bpf+ Version: 1+ Payload SHA256: 46f3d9f5f6568bddb7692cad28e99a86a3104192d8a2251f9ef9ec6d593c2035+ File size: 8661 bytes++ Loader:+ Instructions: off=360 len=992+ Log buffer size: 1048576+ Metadata: (none)+ Data: off=6205 len=2456++ Signature:+ Offset: 1352+ Length: 4853 bytes++ Signed sections:+ Name: basic+ Attach metadata: 176 bytes+ Unload payload: (none)++ Decoders:+ (none)++Read the payload digest for ``build --unload --payload-sha256``:++.. code-block:: console++ operator$ shirudo upatch info --json basic.upatch | jq -r .payload_sha256+ 46f3d9f5f6568bddb7692cad28e99a86a3104192d8a2251f9ef9ec6d593c2035++The JSON form of another artifact:++.. code-block:: console++ target# shirudo upatch info --json shirudo-test-basic.upatch+ {"schema":1,"path":"shirudo-test-basic.upatch","name":"shirudo-test-basic","type":"load","payload_type":"bpf","version":1,"payload_sha256":"8aee7072a1a15e4dddc93ad6b253a0e2e70ad6cdf767442aa8a1c1997bc3069f","loader_insns_len":992,"signature_len":4853,"metadata_len":0,"data_len":2400,"log_buf_sz":1048576,"file_size":8605,"signed_name":"shirudo-test-basic","attach_metadata_len":176,"unload_payload_sha256":null,"decoders":[]}++Related+-------++- :doc:`build`+- :doc:`upatch-get`+- :doc:`/reference/formats/upatch-format`diff --git a/Documentation/reference/cli/upatch-list.rst b/Documentation/reference/cli/upatch-list.rstnew file mode 100644index 00000000..e1c8e091--- /dev/null+++ b/Documentation/reference/cli/upatch-list.rst@@ -0,0 +1,100 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo upatch list+===================++List the upatches archived on this host next to the ones loaded now, and+flag drift between the two.++Runs on: target, as root with the runtime binary. On a host without+shirudo state it lists nothing. Requires: nothing. Changes measured state:+no.++Usage+-----++.. code-block:: none++ shirudo upatch list [--json]++Description+-----------++``list`` reads the archive ``/var/lib/shirudo/upatches/*.upatch``, which+``init`` restores at boot, and the pin directories under+``/run/shirudo/bpffs/upatches/``:++- one row per archived artifact, with ``loaded`` ``yes`` or ``no``, its+ type (``load`` or ``unload``), its payload kind, the first 16+ hexadecimal characters of its payload digest and its name.+- one row per pinned upatch without an archive copy, marked+ ``(orphan: no persisted .upatch, will not survive reboot)``.++An archived artifact that cannot be read is listed as ``(unreadable)``.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 18 12 12 58++ * - Option+ - Argument+ - Default+ - Description+ * - ``--json``+ - none+ - off+ - Print one JSON object: ``schema`` (1) and ``upatches``, a list of+ ``name``, ``type``, ``payload_type``, ``loaded``, ``persisted`` and+ ``payload_sha256``. An orphan has ``type`` and+ ``payload_sha256`` ``null`` and no ``payload_type``.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The list was printed.+ * - 1+ - The JSON document could not be built.+ * - 2+ - An unknown option.++Examples+--------++List the upatches of a target with one loaded upatch:++.. code-block:: console++ target# shirudo upatch list+ upatches (/var/lib/shirudo/upatches):+ loaded type kind payload-sha256 name+ yes load bpf 46f3d9f5f6568bdd.. basic++The same target after the unload:++.. code-block:: console++ target# shirudo upatch list+ upatches (/var/lib/shirudo/upatches):+ (none persisted)++Related+-------++- :doc:`upatch-get`+- :doc:`upatch-load`+- :doc:`status`diff --git a/Documentation/reference/cli/upatch-load.rst b/Documentation/reference/cli/upatch-load.rstnew file mode 100644index 00000000..64451a05--- /dev/null+++ b/Documentation/reference/cli/upatch-load.rst@@ -0,0 +1,244 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo upatch load+===================++Load a signed ``.upatch`` into the target kernel: verify the signature, run+the loader, pin the resulting links and extend this boot's measurement+register.++Runs on: target, as root with the runtime binary. Requires: ``init``+completed this boot. Changes measured state: yes, one ``upatch_load``+event.++Usage+-----++.. code-block:: none++ shirudo upatch load [--expect-chain=<register>] [--expect-version-id=<version-id>]+ [--no-precheck] [--no-version-check] [--report=<path>]+ <file>++Every option with a value takes it after ``=``. ``--help`` anywhere on the+line prints the help. Progress and error messages go to standard error,+so with ``--report=-`` standard output carries only the report.++Description+-----------++#. With ``--expect-version-id``, ``load`` compares the value with this+ binary's ``SHIRUDO_VERSION_ID`` and refuses on a difference+ (``version_mismatch``).+#. It copies the file to a private staging file and reads it once. Every+ later step uses that copy.+#. Pre-flight, unless ``--no-precheck``: the kernel has the+ signed-loader interface (``kernel_abi_unsupported``), ``init`` froze a+ trust anchor this boot (``keyring_missing``), the ``.bpf`` keyring is+ the frozen one and the LSM link is pinned (``tampered``), and with+ ``--expect-chain`` the register holds that value (``tampered``,+ message ``chain_drift``).+#. It refuses when the eventlog would exceed ``eventlog.max_bytes``+ (``eventlog_full``).+#. It parses the artifact: a LOAD artifact, a safe and signed name, a+ payload digest that matches the payload, valid attach metadata+ (``parser_rejected``). For a uprobe it checks each target binary+ against its recorded build ID (``target_verify`` phase).+#. It loads the loader with ``BPF_PROG_LOAD`` against the ``.bpf``+ keyring. The kernel checks the signature before the verifier runs+ (``signed_loader_load`` phase).+#. It runs the loader, which loads the payload programs and maps+ (``payload_load`` phase).+#. It attaches every program and pins the links under+ ``/run/shirudo/bpffs/upatches/<name>/``, where a dot in the name becomes+ ``~d``, with the payload digest in the directory's+ ``security.bpf.shirudo.payload`` extended attribute (``link_create``+ phase).+#. It copies the artifact to ``/var/lib/shirudo/upatches/<name>.upatch``,+ the archive that ``init`` restores at boot (``persist`` phase).+#. It extends the register with the ``upatch_load`` event for the name and+ payload digest, and appends the event to the eventlog (``tpm_extend``+ phase).++When the copy to the archive or the register extend fails, ``load``+removes the pins and the archive again, so that no upatch runs+unmeasured. When the extend succeeded and only the eventlog append failed,+the upatch stays loaded and the report says ``tpm_error``.++``--no-precheck`` skips step 3 only. The kernel signature check and the+LSM still apply. ``bpm`` passes it when it loads the upatches of a+package.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 24 20 10 46++ * - Option+ - Argument+ - Default+ - Description+ * - ``--expect-chain``+ - ``<register>``, 64 hex characters+ - none+ - Refuse unless the register holds this value before the load, for+ example ``register_at_boot`` from :doc:`attest-predict`.+ * - ``--expect-version-id``+ - ``<version-id>``+ - none+ - Refuse unless this binary's ``SHIRUDO_VERSION_ID`` equals the+ value (string comparison).+ * - ``--no-version-check``+ - none+ - off+ - Skip the ``--expect-version-id`` comparison.+ * - ``--no-precheck``+ - none+ - off+ - Skip the pre-flight checks, ``--expect-chain`` included, with a+ warning.+ * - ``--report``+ - ``<path>`` or ``-``+ - none+ - Write the JSON report to ``<path>`` (mode 0644), or to standard+ output with ``-``. A path in sealed state is refused.++.. _upatch-report:++Report+------++``--report`` writes one JSON object, also when the command fails:++.. list-table::+ :header-rows: 1+ :widths: 25 75++ * - Key+ - Value+ * - ``schema``+ - ``1``+ * - ``result``+ - ``ok`` or ``failed``+ * - ``op``+ - ``upatch_load`` or ``upatch_unload``+ * - ``phase``+ - ``pre_flight``, ``parse``, ``target_verify``,+ ``signed_loader_load``, ``payload_load``, ``link_create``, ``pin``,+ ``persist``, ``tpm_extend`` or ``done``+ * - ``errno``, ``errno_name``+ - the error number and its name, or ``null``+ * - ``category``+ - the failure category, ``ok`` on success+ * - ``message``+ - a short description+ * - ``verifier_log``+ - the kernel verifier's log, when it gave one+ * - ``loader_return``+ - the loader's return value+ * - ``upatch``+ - ``path``, ``name`` and ``payload_sha256`` of the artifact+ * - ``kernel``+ - ``release``, the running kernel+ * - ``tpm``+ - ``nv_index`` and ``chain_after``, the register after the event, on+ success, ``null`` otherwise++Exit status and failure categories+----------------------------------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The upatch is loaded and measured.+ * - 1+ - Refused or failed. The report and the message name the category.+ * - 2+ - A usage error: an unknown option, a second file, no file, or an+ ``--expect-chain`` that is not 64 hexadecimal characters. Also the+ category ``attach_target_missing``.++``load`` reports these categories: ``version_mismatch``,+``kernel_abi_unsupported``, ``keyring_missing``, ``tampered``,+``eventlog_full``, ``parser_rejected``, ``signature_rejected``,+``signature_unsupported``, ``lsm_denied``, ``verifier_rejected``,+``attach_target_missing``, ``binary_mismatch``,+``attach_scope_mismatch``, ``tpm_error`` and ``unknown``.+:doc:`/reference/failure-categories` gives the cause and the action for+each. Handle ``tampered`` as an incident (:doc:`/operate/incident-tampered`).++Files and environment+---------------------++- Reads the artifact, ``/var/lib/shirudo/eventlog`` and+ ``eventlog.max_bytes``.+- Writes ``/run/shirudo/bpffs/upatches/<name>/``,+ ``/var/lib/shirudo/upatches/<name>.upatch``, the eventlog and the+ register.++Examples+--------++Load an artifact and print the report:++.. code-block:: console++ target# shirudo upatch load --report=- shirudo-test-basic.upatch+ loaded signed loader: prog_fd=10 keyring=420195959 sig=4853B insns=124 data=2400B+ loader ok, retval=0 (maps=0 progs=1)+ attached + pinned prog 0 (raw_tracepoint) -> /run/shirudo/bpffs/upatches/shirudo-test-basic/link+ upatch load: name=shirudo-test-basic keyring=420195959 progs=1+ upatch load: chain extended, value=c50b22ac27c5bb6a90ee5ff9b440fbbd5bb60b84a2aa7b395daec3f330886fcd+ upatch load measured: name=shirudo-test-basic chain=c50b22ac27c5bb6a90ee5ff9b440fbbd5bb60b84a2aa7b395daec3f330886fcd+ {"schema":1,"result":"ok","op":"upatch_load","phase":"done","errno":null,"errno_name":null,"category":"ok","message":"","verifier_log":"","loader_return":0,"upatch":{"path":"shirudo-test-basic.upatch","name":"shirudo-test-basic","payload_sha256":"8aee7072a1a15e4dddc93ad6b253a0e2e70ad6cdf767442aa8a1c1997bc3069f"},"kernel":{"release":"7.3.0-bpf-next+"},"tpm":{"nv_index":"0x01818E00","chain_after":"c50b22ac27c5bb6a90ee5ff9b440fbbd5bb60b84a2aa7b395daec3f330886fcd"}}++Load only when the register holds the value you predicted:++.. code-block:: console++ target# shirudo upatch load --expect-chain=<register> fix.upatch++``<register>`` is the ``register_at_boot`` or ``register_after_events``+line of :doc:`attest-predict` for the state you expect. When the register+differs, ``load`` refuses before it touches the kernel:++.. code-block:: none++ upatch load: pre-flight refused (category: tampered, message: chain_drift) -- live chain c50b22ac27c5bb6a90ee5ff9b440fbbd5bb60b84a2aa7b395daec3f330886fcd != expected; re-status and re-issue with the refreshed value++The message suggests repeating the command with the live value. Do not.+A register that differs from your prediction is an incident+(:doc:`/operate/incident-tampered`).++A refusal for an artifact signed by a key the target does not trust:++.. code-block:: console++ target# shirudo upatch load --report=- shirudo-test-foreign.upatch+ BPF_PROG_LOAD (signed loader): Required key not available+ loader verifier log:+ signature verification failed: -126++The report of that refusal names ``"phase":"signed_loader_load"``,+``"errno_name":"ENOKEY"`` and ``"category":"keyring_missing"``.++Related+-------++- :doc:`upatch-unload`+- :doc:`build`+- :doc:`attest-predict`+- :doc:`/reference/failure-categories`+- :doc:`/internals/signed-loader`+- :doc:`/upatches/debugging`diff --git a/Documentation/reference/cli/upatch-map.rst b/Documentation/reference/cli/upatch-map.rstnew file mode 100644index 00000000..47b7dd41--- /dev/null+++ b/Documentation/reference/cli/upatch-map.rst@@ -0,0 +1,200 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo upatch map+==================++List the pinned maps of the loaded upatches, print one map's contents, or+export maps as JSON lines, OTLP or S3 objects.++Runs on: target, as root with the runtime binary. Requires: loaded+upatches with pinned maps. Changes measured state: no.++Usage+-----++.. code-block:: none++ shirudo upatch map [<upatch>] [--json | --json=<path>]+ shirudo upatch map <upatch> <map> [--json | --json=<path>] [--show-full] [--peek]+ [--otel [--otel-endpoint=<url>] [--tenant-id=<id>]+ [--otel-insecure] [--otel-retries=<retries>]+ [--s3-uri=<uri>]]+ shirudo upatch map --all [--json | --json=<path>] [--show-full] [--peek]+ [--otel [<otlp-options>]]++Every option with a value takes it after ``=``.++Description+-----------++Listing+~~~~~~~++Without arguments, ``map`` lists every pinned map of every loaded upatch+with its type and maximum number of entries. With ``<upatch>``, it lists the maps of that+upatch. ``--json`` prints the list as ``{"schema":1,"maps":[...]}`` with+``upatch``, ``name``, ``type``, ``max_entries`` and, for a per-CPU map,+``n_cpus`` per map.++One map+~~~~~~~++With ``<upatch> <map>``, ``map`` reads the map:++- A map is decoded through its BTF types when the build kept them+ (``shirudo build`` compiles with ``-g``).+- When the upatch pins a serializer program for the map, ``map`` runs it+ and prints the pages it returns. Such a read drains the serializer:+ records it returns are gone for the next reader, the export timer+ included. ``--peek`` reads the interval being collected without taking+ it.+- The human output shows at most 256 entries unless ``--show-full``.+ JSON and OTLP output have no limit.+- ``--json`` prints one JSON line to standard output. ``--json=<path>``+ appends it to ``<path>``.+- ``--otel`` sends the map to an OTLP collector. A map with a signed Lua+ decoder is sent as the log or metric the decoder declares. A map+ without one is classified by shirudo (see+ :doc:`/reference/formats/otlp`).++Every map+~~~~~~~~~++``--all`` handles every map of every loaded upatch as above and loads the+``map_export`` settings (:doc:`/reference/formats/configuration`):+``map_export.json_path`` turns on JSON output to that file and+``map_export.otel_endpoint`` turns on OTLP, together with the tenant,+TLS, retry, size and S3 settings. Options on the command line take+precedence.++With neither a JSON nor an OTLP destination, ``--all`` prints every map in+full detail on standard output, draining every serializer-backed map+unless ``--peek``. ``shirudo-map-export.timer`` runs ``upatch map --all``+every five seconds, so without a configured destination it drains the+maps into the journal.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 22 22 12 44++ * - Option+ - Argument+ - Default+ - Description+ * - ``--all``+ - none+ - off+ - Handle every map of every loaded upatch. Takes no positional+ argument.+ * - ``--json``+ - optional ``<path>`` after ``=``+ - off+ - Print JSON, or append it to ``<path>``.+ * - ``--show-full``+ - none+ - off+ - Lift the 256-entry limit of the human output.+ * - ``--peek``+ - none+ - off+ - Read serializer-backed maps without draining them.+ * - ``--otel``+ - none+ - off+ - Export through OTLP. Without ``--all`` it needs ``<upatch>`` and+ ``<map>``.+ * - ``--otel-endpoint``+ - ``<url>``+ - ``map_export.otel_endpoint`` with ``--all``, else the+ ``OTEL_EXPORTER_OTLP_*`` variables, else ``http://localhost:4318``+ - OTLP base URL. The signal path is appended.+ * - ``--tenant-id``+ - ``<id>``, 1 to 128 of ``A-Z a-z 0-9 . _ -``+ - ``map_export.tenant_id`` with ``--all``+ - Send an ``X-Tenant-ID`` header.+ * - ``--otel-insecure``+ - none+ - ``map_export.otel_insecure`` with ``--all``+ - Allow cleartext OTLP to a remote host, or turn off HTTPS+ certificate verification.+ * - ``--otel-retries``+ - ``<retries>``, 0 to 10+ - 3+ - Retries after the first attempt.+ * - ``--s3-uri``+ - ``<uri>``+ - ``map_export.s3_uri`` with ``--all``+ - Where to store an OTLP payload that is too large to send.++The OTLP options require ``--otel``. ``--all``, ``--json``, ``--otel`` and+each OTLP option may appear once.++Exit status+-----------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - Every map was read and exported.+ * - 1+ - A map could not be read, written as JSON or sent. With ``--all``+ the other maps are still handled. Also, with ``--all``, the+ configuration cannot be loaded.+ * - 2+ - A usage error: an unknown or repeated option, an invalid value,+ positional arguments with ``--all``, ``--otel`` without a map, OTLP+ options without ``--otel``, an invalid upatch name, or with+ ``--all`` an invalid ``map_export`` configuration.++Files and environment+---------------------++- Reads the pinned maps under ``/run/shirudo/bpffs/upatches/``.+- Appends to the ``--json`` or ``map_export.json_path`` file.+- OTLP and S3: the ``OTEL_EXPORTER_OTLP_*`` and ``AWS_*`` variables (see+ :doc:`/reference/environment`). ``shirudo-map-export.service`` reads+ them from ``/etc/shirudo/map-export.env``.++Examples+--------++List the pinned maps of a target without any:++.. code-block:: console++ target# shirudo upatch map+ (no pinned maps)++Look at a serializer-backed map without taking its records from the+exporter:++.. code-block:: console++ target# shirudo upatch map kernel-obs exec --json --peek++Send one map to a collector:++.. code-block:: console++ target# shirudo upatch map kernel-obs exec --otel --otel-endpoint=https://collector.example:4318 --tenant-id=fleet-eu-1++Related+-------++- :doc:`/operate/telemetry`+- :doc:`/reference/formats/otlp`+- :doc:`/upatches/maps-arenas-serializers`+- :doc:`/upatches/decoders`+- :doc:`upatch-get`diff --git a/Documentation/reference/cli/upatch-unload.rst b/Documentation/reference/cli/upatch-unload.rstnew file mode 100644index 00000000..79107eb2--- /dev/null+++ b/Documentation/reference/cli/upatch-unload.rst@@ -0,0 +1,165 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++shirudo upatch unload+=====================++Apply a signed unload directive: measure the unload, detach the named+upatch and remove its pin and archive copy.++Runs on: target, as root with the runtime binary. Requires: ``init``+completed this boot, and a directive signed by a key in the ``.bpf``+keyring. Changes measured state: yes, one ``upatch_unload`` event, except+when the upatch is not loaded.++Usage+-----++.. code-block:: none++ shirudo upatch unload [--expect-chain=<register>] [--expect-version-id=<version-id>]+ [--no-precheck] [--no-version-check] [--report=<path>]+ <directive>++The options are those of :doc:`upatch-load`, with the same meaning.++Description+-----------++An unload directive names the upatch and the payload digest it expects,+both in signed sections (see :doc:`build`). ``unload``:++#. Compares ``--expect-version-id``, as ``load`` does.+#. Reads the directive once into a private staging file and refuses a+ LOAD artifact, a directive whose target name is not signed or differs+ from the header, and an unsafe name (``parser_rejected``).+#. Runs the pre-flight checks of ``load``, unless ``--no-precheck``.+#. Refuses when the eventlog would exceed ``eventlog.max_bytes``+ (``eventlog_full``).+#. Loads the directive's loader with ``BPF_PROG_LOAD`` against the+ ``.bpf`` keyring, so that the kernel verifies its signature before+ anything is removed.+#. Reads the payload digest that ``load`` recorded on the upatch's pin+ directory and compares it with the signed one. A difference, or a+ digest that cannot be read, is refused with ``payload_mismatch``. A+ directive signed with an all-zero digest never matches.+#. When the upatch has no pin, it removes any archive copy, reports+ ``already_unloaded`` and exits with 0 without measuring.+#. It extends the register with the ``upatch_unload`` event and appends+ it to the eventlog. The event comes first: a failed extend leaves the+ upatch attached.+#. It removes the pin directory, which detaches the links, and then+ ``/var/lib/shirudo/upatches/<name>.upatch``. When the pin cannot be+ removed after the event was measured, the report says+ ``detach_failed``. Repeat the unload.++An unload moves the register forward. It never returns the register to+the value it had before the load.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 24 20 10 46++ * - Option+ - Argument+ - Default+ - Description+ * - ``--expect-chain``+ - ``<register>``, 64 hex characters+ - none+ - Refuse unless the register holds this value before the unload.+ * - ``--expect-version-id``+ - ``<version-id>``+ - none+ - Refuse unless this binary's ``SHIRUDO_VERSION_ID`` equals the+ value.+ * - ``--no-version-check``+ - none+ - off+ - Skip the ``--expect-version-id`` comparison.+ * - ``--no-precheck``+ - none+ - off+ - Skip the pre-flight checks, with a warning.+ * - ``--report``+ - ``<path>`` or ``-``+ - none+ - Write the JSON report (:ref:`upatch-report`) to ``<path>`` or to+ standard output.++Exit status and failure categories+----------------------------------++.. list-table::+ :header-rows: 1+ :widths: 15 85++ * - Status+ - Meaning+ * - 0+ - The upatch was unloaded and the unload measured, or it was not+ loaded (``already_unloaded``).+ * - 1+ - Refused or failed.+ * - 2+ - A usage error: an unknown option, a second file, no file, or an+ ``--expect-chain`` that is not 64 hexadecimal characters.++``unload`` reports these categories: ``version_mismatch``,+``kernel_abi_unsupported``, ``keyring_missing``, ``tampered``,+``eventlog_full``, ``parser_rejected``, ``signature_rejected``,+``signature_unsupported``, ``lsm_denied``, ``verifier_rejected``,+``payload_mismatch``, ``detach_failed``, ``tpm_error``,+``already_unloaded`` and ``unknown``. See+:doc:`/reference/failure-categories`.++Files and environment+---------------------++- Reads the directive, the pin directory's+ ``security.bpf.shirudo.payload`` attribute and+ ``/var/lib/shirudo/eventlog``.+- Removes ``/run/shirudo/bpffs/upatches/<name>/`` and+ ``/var/lib/shirudo/upatches/<name>.upatch``. Extends the register and+ appends to the eventlog.++Examples+--------++Unload with a directive bound to the loaded payload:++.. code-block:: console++ target# shirudo upatch unload basic.unload.upatch+ loaded signed loader: prog_fd=10 keyring=531121468 sig=4853B insns=165 data=2808B+ upatch unload: payload matches for 'basic'+ upatch unload: chain extended, value=fe7bd139c02aca0d6e5efc3940c1cd902adbe676b7875be4c73c878b3f5212b8+ upatch unload measured: name=basic chain=fe7bd139c02aca0d6e5efc3940c1cd902adbe676b7875be4c73c878b3f5212b8+ upatch unload: detached + unpinned basic++A directive that expects a different payload is refused:++.. code-block:: console++ target# shirudo upatch unload --report=- shirudo-test-basic-mismatch.unload.upatch+ loaded signed loader: prog_fd=10 keyring=420195959 sig=4853B insns=165 data=2808B+ upatch unload: payload_mismatch -- the upatch loaded under 'shirudo-test-basic' is not what the directive expects; refusing+ upatch unload failed: name=shirudo-test-basic phase=pin category=payload_mismatch err=1 (Operation not permitted) message=loaded payload does not match directive++The report of that refusal carries ``"phase":"pin"``,+``"errno_name":"EPERM"`` and ``"category":"payload_mismatch"``.++Related+-------++- :doc:`upatch-load`+- :doc:`build`+- :doc:`upatch-list`+- :doc:`/reference/failure-categories`diff --git a/Documentation/reference/cli/version.rst b/Documentation/reference/cli/version.rstnew file mode 100644index 00000000..da80b48b--- /dev/null+++ b/Documentation/reference/cli/version.rst@@ -0,0 +1,86 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: All readers++shirudo version+===============++Print the release and the ``SHIRUDO_VERSION_ID`` that ``upatch load+--expect-version-id`` compares against.++Runs on: any host, with any copy of the binary, since the image gate does+not apply. Requires: nothing. Changes measured state: no.++Usage+-----++.. code-block:: none++ shirudo version [--version-id]++Description+-----------++Without an option, ``version`` prints two lines::++ shirudo (<describe><extraversion>, "<release-name>")+ version-id: <version-id>++``<describe>`` is ``git describe`` of the build tree, or the ``VERSION``+file outside a git checkout. ``<version-id>`` is a SHA-256 over the git+commit, a dirty-tree flag and a digest of the build configuration+(``config.mk`` and ``Makefile.shirudo``). Two builds of one commit with+different build configurations therefore have different ids, for+example an operator package and a target package built on different+hosts.++Options+-------++.. list-table::+ :header-rows: 1+ :widths: 22 12 12 54++ * - Option+ - Argument+ - Default+ - Description+ * - ``--version-id``+ - none+ - off+ - Print only the version id, on one line.++Only the first argument is read. Any argument other than ``--version-id``+and ``--help`` is ignored.++Exit status+-----------++0 in every case.++Examples+--------++Print the release and the id:++.. code-block:: console++ target# shirudo version+ shirudo (58d3fa7-dirty-rc0, "Social BPF Coding")+ version-id: 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0++Print the id alone, to pass to ``--expect-version-id``:++.. code-block:: console++ target# shirudo version --version-id+ 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0++Related+-------++- :doc:`upatch-load`+- :doc:`/operate/upgrade`diff --git a/Documentation/reference/environment.rst b/Documentation/reference/environment.rstnew file mode 100644index 00000000..8737436f--- /dev/null+++ b/Documentation/reference/environment.rst@@ -0,0 +1,291 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Environment variables+=====================++Every environment variable that ``shirudo``, ``shirudo-build``, the+generator scripts and the libraries they link read. shirudo does not+clear or filter its environment beyond the refusals listed here.++Refused on a target+-------------------++``init``, and on a target that enforces every command except+``genkey``, ``build``, ``help``, ``version``, ``image build`` and+``image verify``, refuse to run when one of these variables is set, even+to an empty value. The command logs ``bootstrap override <name> is+forbidden`` and fails with ``EPERM`` and exit status 1.++.. list-table::+ :header-rows: 1+ :widths: 32 68++ * - Variable+ - Effect on a host without a config image+ * - ``SHIRUDO_KEYS_DIR``+ - Key directory of ``genkey``, ``keys`` and ``shirudo-build``, in+ place of ``/var/lib/shirudo/keys``. A ``--keys-dir`` option takes+ precedence.+ * - ``SHIRUDO_TPM_TCTI``+ - TCTI in place of ``tpm.tcti``.+ * - ``SHIRUDO_TPM_OWNER_AUTH``+ - TPM owner password in place of ``tpm.owner_auth``, as a literal+ or ``hex:<even number of hex digits>``.+ * - ``SHIRUDO_EVENTLOG_PATH``+ - Eventlog path in place of ``/var/lib/shirudo/eventlog``.+ * - ``SHIRUDO_EVENTLOG_PENDING_PATH``+ - Pending eventlog record in place of+ ``/run/shirudo/eventlog.pending``.+ * - ``SHIRUDO_INITRD_RELEASE``+ - File whose existence means "running in the initrd", in place of+ ``/etc/initrd-release``.+ * - ``SHIRUDO_SYSROOT``+ - Root file system mount point in the initrd, in place of+ ``/sysroot``.++``SHIRUDO_KEYS_DIR`` also serves operator hosts. The others serve+development and tests.++shirudo and shirudo-build+-------------------------++.. list-table::+ :header-rows: 1+ :widths: 24 30 46++ * - Variable+ - Read by+ - Effect+ * - ``SHIRUDO_BUILD``+ - ``shirudo`` when it hands an operator command to the helper;+ ``shirudo-gen-image``, ``shirudo-gen-runtime``,+ ``shirudo-gen-verity``+ - Path of ``shirudo-build``. Unset, ``shirudo`` uses+ ``$(libexecdir)/shirudo/shirudo-build`` and then+ ``shirudo-build`` on ``PATH``, and the scripts use+ ``shirudo-build`` on ``PATH``. ``shirudo`` fails with exit status+ 127 when the value is empty.+ * - ``PATH``+ - ``shirudo`` looking up ``shirudo-build``; ``shirudo-build``+ running ``veritysetup``; the generator scripts+ - Search path. ``shirudo-build`` runs ``clang`` from the fixed path+ ``/usr/bin/clang`` only.+ * - ``SHIRUDO_INIT_ARGS``+ - ``shirudo.service``, from ``/etc/shirudo/init.env``+ - Arguments appended to ``init``. ``init`` accepts only+ ``--check-only``. The runtime drop-in clears ``ExecStart=`` and+ ``EnvironmentFile=``, so the variable has no effect with it.+ * - ``TMPDIR``+ - ``upatch map`` (snapshot file), ``shirudo-build bpm build``+ (staging directory), the generator scripts (``mktemp -d``)+ - Directory for temporary files, ``/tmp`` when unset or empty.+ * - ``HOME``+ - Registry credential lookup; ``shirudo-build bpm build`` expanding+ ``~`` in its key directory+ - ``$HOME/.docker/config.json`` holds registry credentials.+ ``/root`` when unset.++Registry access+---------------++Read by the target's ``bpm`` commands and by ``shirudo-build bpm push``+and ``shirudo-build bpm tree append``. Honored on a target.++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Variable+ - Effect+ * - ``BPM_OCI_SCHEME``+ - ``https`` (default) or ``http``. ``http`` sends registry traffic+ without TLS. Any other value fails with ``bpm OCI: BPM_OCI_SCHEME+ must be https or http``.+ * - ``BPM_OCI_CA_FILE``+ - PEM file whose first certificate is added to the trusted CAs of+ registry connections.+ * - ``BPM_OCI_USERNAME``, ``BPM_OCI_PASSWORD``+ - Registry credentials. Used only when both are set, ahead of any+ auth file.+ * - ``BPM_OCI_BEARER_TOKEN``+ - Bearer token sent when a registry asks for one, in place of a+ token from the registry's token service.+ * - ``REGISTRY_AUTH_FILE``+ - Auth file in ``config.json`` form, read when the two variables+ above are not both set.+ * - ``DOCKER_CONFIG``+ - Directory holding ``config.json``, read when+ ``REGISTRY_AUTH_FILE`` is unset. Without either,+ ``$HOME/.docker/config.json`` is read.++Telemetry export+----------------++Read by ``status --otel`` and by ``upatch map --otel`` and ``--all``.+Honored on a target. ``<SIGNAL>`` is ``LOGS`` or ``METRICS``. A+per-signal variable takes precedence over the generic one. See+:doc:`/reference/formats/otlp`.++.. list-table::+ :header-rows: 1+ :widths: 44 56++ * - Variable+ - Effect+ * - ``OTEL_EXPORTER_OTLP_ENDPOINT``+ - Base URL, ``/v1/logs`` or ``/v1/metrics`` appended. Used when+ neither ``map_export.otel_endpoint``, ``--otel-endpoint`` nor the+ per-signal variable is set. Default ``http://localhost:4318``,+ except that ``status --otel`` sends nothing without a configured+ endpoint.+ * - ``OTEL_EXPORTER_OTLP_<SIGNAL>_ENDPOINT``+ - Full URL, used as given.+ * - ``OTEL_EXPORTER_OTLP_[<SIGNAL>_]PROTOCOL``+ - Must be ``http/json``.+ * - ``OTEL_EXPORTER_OTLP_[<SIGNAL>_]COMPRESSION``+ - ``none`` or ``gzip``.+ * - ``OTEL_EXPORTER_OTLP_[<SIGNAL>_]HEADERS``+ - Comma-separated ``name=value`` pairs, values percent-decoded.+ ``Content-Type``, ``Content-Encoding``, ``Content-Length``,+ ``Host`` and ``User-Agent`` are refused. An ``X-Tenant-ID`` pair+ yields to ``map_export.tenant_id`` and ``--tenant-id``.+ * - ``OTEL_EXPORTER_OTLP_[<SIGNAL>_]CERTIFICATE``+ - CA file for the collector's certificate.+ * - ``OTEL_EXPORTER_OTLP_[<SIGNAL>_]CLIENT_CERTIFICATE``,+ ``OTEL_EXPORTER_OTLP_[<SIGNAL>_]CLIENT_KEY``+ - Client certificate and key, both or neither.+ * - ``OTEL_EXPORTER_OTLP_[<SIGNAL>_]TIMEOUT``+ - Request timeout in milliseconds, 1 to 120000. Default 10000.+ * - ``AWS_REGION``, ``AWS_DEFAULT_REGION``+ - Region of ``map_export.s3_uri``, in this order. Default+ ``us-east-1``.+ * - ``AWS_ENDPOINT_URL_S3``+ - S3 endpoint in place of the region's.+ * - ``AWS_ACCESS_KEY_ID``, ``AWS_SECRET_ACCESS_KEY``+ - S3 credentials. Required for an S3 upload.+ * - ``AWS_SESSION_TOKEN``+ - S3 session token.+ * - ``AWS_CA_BUNDLE``+ - CA file for the S3 endpoint.++Libraries+---------++shirudo sets none of these and refuses none of them.++.. list-table::+ :header-rows: 1+ :widths: 26 16 58++ * - Variable+ - Library+ - Effect+ * - ``SSLKEYLOGFILE``+ - libcurl+ - libcurl appends the TLS session secrets of every registry, OTLP+ and S3 connection to this file. The static target's libcurl is+ built with this support. Anyone who reads the file can decrypt+ the captured traffic.+ * - ``http_proxy``, ``https_proxy``, ``HTTPS_PROXY``, ``all_proxy``,+ ``ALL_PROXY``, ``no_proxy``, ``NO_PROXY``+ - libcurl+ - Proxy for registry, OTLP and S3 connections. ``HTTP_PROXY`` in+ upper case is not read.+ * - ``TSS2_LOG``+ - tpm2-tss+ - Log levels of the TPM library. shirudo sets ``all+none`` when the+ variable is unset.+ * - ``TSS2_LOGFILE``+ - tpm2-tss+ - Destination of those logs: ``stderr`` (default), ``stdout`` or+ ``-``, or a file opened for appending.+ * - ``LIBBPF_LOG_LEVEL``+ - libbpf+ - ``warn``, ``info`` (default) or ``debug`` for libbpf's messages+ on standard error.+ * - ``LIBBPF_BPF_TOKEN_PATH``+ - libbpf+ - bpffs path from which libbpf creates a BPF token when ``init``+ loads its own BPF objects. Set to a non-empty value, a failure to+ create the token fails the load.+ * - ``OPENSSL_CONF``+ - OpenSSL+ - Not read. shirudo initializes OpenSSL without its configuration+ file.++Generator and installer scripts+-------------------------------++.. list-table::+ :header-rows: 1+ :widths: 26 30 44++ * - Variable+ - Read by+ - Effect+ * - ``SHIRUDO_KEYS_DIR``+ - ``shirudo-gen-verity``+ - Key directory when ``--keys-dir`` is not given. Default+ ``/var/lib/shirudo/keys``.+ * - ``SHIRUDO_REPO``+ - ``tools/gen-initrd/install.sh``+ - GitHub repository releases are fetched from. Default+ ``shirudo-dev/shirudo``.+ * - ``SHIRUDO_CERT``+ - ``tools/gen-initrd/install.sh``+ - Same as ``--cert``.+ * - ``SHIRUDO_VERSION``+ - ``tools/gen-initrd/install.sh``+ - Same as ``--version``.+ * - ``SHIRUDO_PACKAGE``+ - ``tools/gen-initrd/install.sh``+ - Same as ``--package``.+ * - ``DESTDIR``+ - ``install.sh`` of the target tarball+ - Installation root. Default ``/``.++Environment files+-----------------++The units read these files with ``EnvironmentFile=-<file>``. A missing+file is not an error. They are host files on the root file system,+outside the sealed state under ``/var/lib/shirudo`` and outside the+signed config. Root can change them, and the next run of the unit uses+what they hold. See :doc:`/operate/hardening`.++.. list-table::+ :header-rows: 1+ :widths: 32 34 34++ * - File+ - Units+ - Typical variables+ * - ``/etc/shirudo/init.env``+ - ``shirudo.service``, unless the runtime drop-in clears it+ - ``SHIRUDO_INIT_ARGS``+ * - ``/etc/shirudo/map-export.env``+ - ``shirudo-keepalive.service``, ``shirudo-map-export.service``+ - ``OTEL_EXPORTER_OTLP_*``, ``AWS_*``+ * - ``/etc/shirudo/bpm/environment``+ - ``shirudo-bpm-repo-update.service``,+ ``shirudo-bpm-tree-sync.service``+ - ``BPM_OCI_*``, ``REGISTRY_AUTH_FILE``, ``DOCKER_CONFIG``, proxy+ variables++A variable from the first table set in one of these files makes the+unit's command fail on a target.++Related+-------++- :doc:`/reference/systemd-units` for the units that read the+ environment files.+- :doc:`/reference/formats/configuration` for the settings these+ variables complement.+- :doc:`/operate/telemetry` and :doc:`/operate/deliver-packages` for+ setting up export and registry access.diff --git a/Documentation/reference/failure-categories.rst b/Documentation/reference/failure-categories.rstnew file mode 100644index 00000000..0b3ad0a3--- /dev/null+++ b/Documentation/reference/failure-categories.rst@@ -0,0 +1,577 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Failure categories and exit status+==================================++``shirudo upatch load`` and ``shirudo upatch unload`` classify every+refusal by a phase and a category. Both appear in the operation report+(``--report``) and in the ``upatch unload failed:`` journal line. Other+commands report failures as messages and exit status only.++Phases+------++The table lists the phases in the order a load reaches them. The+``--expect-version-id`` check of ``pre_flight`` runs before ``parse``.+An unload passes ``pre_flight`` and ``parse``, verifies the directive's+signature in ``signed_loader_load``, compares the payload in ``pin``,+measures in ``tpm_extend`` and removes the pins in ``pin``.++.. list-table::+ :header-rows: 1+ :widths: 22 78++ * - Phase+ - What runs+ * - ``pre_flight``+ - The ``--expect-version-id`` check, the signed-loader ABI check, the+ comparison of the ``.bpf`` keyring with the frozen record, the+ ``lsm_link`` pin, the ``--expect-chain`` comparison and the+ ``eventlog.max_bytes`` check. ``--no-precheck`` skips the ABI,+ ``lsm_link`` and ``--expect-chain`` checks, not the keyring+ comparison.+ * - ``parse``+ - Reading and staging the artifact, the header checks, the upatch+ name, the signed name, ``payload_sha256`` against the loader and+ data, and the signed attach metadata.+ * - ``target_verify``+ - Opening each ``uprobe.multi`` target binary and comparing its GNU+ build ID with the one the artifact records.+ * - ``signed_loader_load``+ - Creating, filling and freezing ``__loader.map`` and the+ ``BPF_PROG_LOAD`` of the signed loader, where the kernel verifies+ the signature against the ``.bpf`` keyring.+ * - ``payload_load``+ - ``BPF_PROG_TEST_RUN`` of the loader, which loads the payload+ programs and maps through the verifier.+ * - ``link_create``+ - Attaching each program, checking the link against the attach+ metadata and pinning it in the private bpffs.+ * - ``pin``+ - Unload only: comparing the payload recorded on the pin directory+ with the directive's, and removing the pins.+ * - ``persist``+ - Load only: copying the artifact to+ ``/var/lib/shirudo/upatches/<name>.upatch``.+ * - ``tpm_extend``+ - Extending the measurement register and appending the eventlog+ record.+ * - ``done``+ - The operation completed.++Categories+----------++.. list-table::+ :header-rows: 1+ :widths: 18 16 12 27 27++ * - Category+ - Phases+ - errno+ - Meaning+ - Action+ * - ``version_mismatch``+ - ``pre_flight``+ - ``EPERM``+ - ``--expect-version-id`` differs from the target's+ ``SHIRUDO_VERSION_ID``.+ - Compare ``shirudo version --version-id`` on both hosts and+ deploy matching builds. See :doc:`/operate/upgrade`.+ * - ``kernel_abi_unsupported``+ - ``pre_flight``, ``link_create``+ - ``EOPNOTSUPP``+ - In ``pre_flight``, the kernel lacks the signed-loader ABI; the+ message names the missing part. In ``link_create``, the kernel+ does not support the attach type.+ - Run a kernel that meets :doc:`/operate/system-requirements`.+ * - ``keyring_missing``+ - ``pre_flight``, ``signed_loader_load``+ - errno of the read, ``ENOKEY``+ - In ``pre_flight``, no trust anchor was frozen this boot (``ENOENT``+ when ``init`` has not run). In ``signed_loader_load``, the+ signer's certificate is not in the ``.bpf`` keyring.+ - Check ``shirudo status`` and the journal of ``init``. Compare the+ signer with ``shirudo keys``; enroll a signer through the signed+ config, see :doc:`/operate/keys`.+ * - ``tampered``+ - ``pre_flight``, ``tpm_extend``+ - none, ``EPERM``, ``EACCES``+ - The ``.bpf`` keyring is not the frozen anchor (no errno), the+ ``lsm_link`` pin cannot be opened, the register differs from+ ``--expect-chain`` or cannot be read (``EPERM``), or the register+ is not the one ``init`` bound (``EACCES``, the load is undone).+ - Do not retry. Keep the eventlog and the journal and handle the+ target as an incident: :doc:`/operate/incident-tampered`.+ * - ``eventlog_full``+ - ``pre_flight``+ - ``ENOSPC``+ - The eventlog would exceed ``eventlog.max_bytes``. Nothing was+ loaded or measured.+ - Raise ``eventlog.max_bytes`` in the signed config, see+ :doc:`/reference/formats/configuration`. The eventlog is sealed+ and cannot be rotated.+ * - ``parser_rejected``+ - ``parse``, ``target_verify``+ - errno of the read, or none; ``ERANGE``, ``EINVAL``, ``E2BIG``+ - The artifact cannot be read or is malformed: wrong kind (a+ directive given to ``load`` or the reverse), misaligned loader,+ unsafe or unsigned name, ``payload_sha256`` mismatch, unsigned or+ invalid attach metadata. In ``target_verify``, a uprobe offset+ lies beyond the target file.+ - Rebuild the artifact with ``shirudo build`` and check it with+ ``shirudo upatch info``.+ * - ``attach_target_missing``+ - ``target_verify``, ``link_create``+ - ``ENOENT``, ``ENOTDIR``+ - The uprobe binary, the kprobe symbol or its module is absent.+ ``upatch load`` exits 2. ``bpm tree sync`` records the operation as+ ``skipped: module not loaded`` and continues.+ - Load the module or install the binary, then load again.+ * - ``binary_mismatch``+ - ``target_verify``, ``link_create``+ - ``ESTALE``+ - The uprobe target is not a regular file, was replaced while it+ was opened, or its build ID differs from the recorded one.+ - Rebuild the upatch against the installed binary.+ * - ``signature_rejected``+ - ``signed_loader_load``+ - ``EKEYREJECTED``+ - The kernel rejected the loader's signature.+ - Fetch or rebuild the artifact. Check that the file was not+ modified after signing.+ * - ``signature_unsupported``+ - ``signed_loader_load``+ - ``ENOPKG``+ - The kernel cannot verify ML-DSA signatures.+ - Build the kernel with ``CONFIG_CRYPTO_MLDSA``, see+ :doc:`/operate/system-requirements`.+ * - ``lsm_denied``+ - ``target_verify``, ``signed_loader_load``, ``link_create``+ - ``EACCES``, ``EPERM``+ - The kernel refused an operation with ``EACCES`` or ``EPERM``,+ normally an LSM, shirudo's own or another one.+ - Check the tamper counters in ``shirudo status`` and the other+ LSMs' audit records.+ * - ``verifier_rejected``+ - ``signed_loader_load``, ``payload_load``+ - errno of the call, or the loader's return value+ - The verifier rejected the loader, ``BPF_PROG_TEST_RUN`` failed, or+ the loader returned an error for a payload program, often a CO-RE+ relocation against this kernel's BTF. ``verifier_log`` holds the+ kernel's log.+ - Read ``verifier_log`` and rebuild against the target kernel. See+ :doc:`/upatches/debugging`.+ * - ``attach_scope_mismatch``+ - ``link_create``+ - ``EXDEV``+ - The link the kernel reports is not at the site the attach+ metadata names: a cgroup link not at the root cgroup, a netfilter+ link outside the initial network namespace or at another hook or+ priority, a kprobe at another function or offset.+ - Run the load in the host's initial cgroup and network namespaces+ and with the host's sysfs.+ * - ``payload_mismatch``+ - ``pin``+ - ``EPERM``, errno of the read+ - The upatch loaded under the name carries another payload than the+ directive expects, or the recorded payload cannot be read.+ Nothing was detached.+ - Compare the ``Payload`` of ``shirudo upatch get <name>`` with the+ directive and build a directive for the loaded payload.+ * - ``detach_failed``+ - ``pin``+ - errno of the removal+ - The unload was measured, then removing the pins failed.+ - Repeat the unload. Each attempt records another unload event.+ * - ``tpm_error``+ - ``tpm_extend``+ - errno of the call+ - The register lock, the TPM or the extend failed. A load is undone+ when the register did not move. When the extend succeeded and the+ eventlog append failed, the message reads ``eventlog append failed+ after the extend``.+ - Check ``shirudo status``. A register ahead of the eventlog shows as+ ``tampered``; handle that as an incident.+ * - ``unknown``+ - ``parse``, ``target_verify``, ``signed_loader_load``,+ ``payload_load``, ``link_create``, ``persist``+ - errno of the call+ - Any other failure: out of memory, a failed hash of the loader, an+ unclassified attach error, or a failed archive copy (the load is+ undone).+ - Read ``message`` and the journal. For ``persist``, check the space+ on the file system that holds ``/var/lib/shirudo``.++A successful operation reports the category ``ok``. An unload of a+upatch that has no pins reports ``already_unloaded``, exits 0 and+records no event.++Refusals before a command runs+------------------------------++On an enforcing target every command except ``init``, ``genkey``,+``build``, ``help``, ``version``, ``image build`` and ``image verify``+passes a gate first. A refusal prints ``shirudo: image state:+<strerror>`` and exits 1.++.. list-table::+ :header-rows: 1+ :widths: 35 65++ * - Message+ - Cause+ * - ``shirudo: image state: Operation not permitted``+ - An argument starts with ``--keys-dir``, ``--cert`` or ``--tcti``,+ or a forbidden environment variable is set (see+ :doc:`/reference/environment`).+ * - ``shirudo: image state: Permission denied``+ - The binary is not the runtime binary, so the LSM refuses it access+ to the frozen record.+ * - ``shirudo: image state: Operation now in progress``+ - A config activation is pending. Only ``status`` and ``image`` run+ until the next boot.+ * - ``shirudo: image state: Structure needs cleaning``,+ ``Stale file handle`` or ``Key was rejected by service``+ - The config activation record or the mounted config cannot be+ verified. Only ``status`` and ``image`` run.+ * - ``shirudo: image state: Protocol error``+ - A frozen record exists but enforcement is not active.++Exit status+-----------++Monitoring must not rely on exit status: ``shirudo status`` exits 0 for+every verdict, ``tampered`` included. Parse ``.status`` of+``shirudo status --json`` instead, see :doc:`/reference/formats/status-json`.++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Command+ - Exit status+ * - ``shirudo`` without a command+ - 1, after the help text.+ * - ``shirudo help``, ``--help``, ``--list-cmds``+ - 0.+ * - Unknown or ambiguous command+ - 1.+ * - Any command+ - 1 when ``mlockall()`` fails (``hardening: cannot lock process+ memory``) or the gate refuses.+ * - ``genkey``+ - 0; 1 on failure or when keys exist without ``--force``; 2 for an+ unknown option.+ * - ``build``, ``keys vouch``, ``image build``, ``image verify``+ - The exit status of ``shirudo-build``: 0; 1 on failure; 2 for a+ usage error. 127 when the helper is missing, not executable or+ ``SHIRUDO_BUILD`` is empty.+ * - ``init``+ - 0; 1 on any failure, the pre-flight included; 2 for an unknown+ option. ``--check-only`` exits 0 when every check passes, else 1.+ * - ``status``+ - 0 for every verdict; 1 when memory runs out, the configuration+ cannot be loaded for ``--otel`` or the OTLP send fails; 2 for a+ usage error or an invalid ``map_export`` configuration with+ ``--otel``.+ * - ``upatch`` without a subcommand+ - 2.+ * - ``upatch load``+ - 0; 1 on refusal or failure; 2 for a usage error and for+ ``attach_target_missing``.+ * - ``upatch unload``+ - 0, ``already_unloaded`` included; 1 on refusal or failure; 2 for a+ usage error.+ * - ``upatch list``, ``upatch info``+ - 0; 1 on failure; 2 for a usage error.+ * - ``upatch get``+ - 0; 1 when the upatch is not found or cannot be read; 2 for a usage+ error or an invalid name.+ * - ``upatch map``+ - 0; 1 on a read or export failure; 2 for a usage error or an invalid+ ``map_export`` configuration.+ * - ``bpm`` without a subcommand+ - 2.+ * - ``bpm install``, ``uninstall``, ``upgrade``, ``list``, ``pull``,+ ``info``, ``key``, ``repo update``, ``config register``+ - 0, an already installed package included; 1 on failure; 2 for a+ usage error.+ * - ``bpm tree sync``+ - 0, also when no tree is configured; 1 on failure and for an+ unknown option.+ * - ``bpm build``, ``bpm config update``, ``bpm tree append``+ - 0; 1 on failure and for a usage error; 127 when the helper is+ missing.+ * - ``bpm push``+ - 0; 1 on failure; 2 for a usage error; 127 when the helper is+ missing.+ * - ``image`` without a subcommand+ - 2.+ * - ``image update``+ - 0; 1 on failure.+ * - ``image status``+ - 0 when the activation is consistent and not pending; 1 when it is+ pending or inconsistent (after the JSON) or no record exists.+ * - ``attest``+ - 0; 1 when no TPM answers, the register is not bound, the challenge+ is refused or the output cannot be written; 2 for a usage error or+ an unreadable challenge.+ * - ``attest verify``+ - 0 for ``verdict: ok``; 1 for ``verdict: FAIL``; 2 for a usage+ error, an unreadable evidence file or a file that is not an+ evidence document.+ * - ``attest predict``+ - 0; 1 when the write policy cannot be computed; 2 for a usage error+ or invalid input.+ * - ``attest challenge``+ - 0; 1 for ``verdict: FAIL`` or a write error; 2 for a usage error,+ an unreadable evidence file or evidence without an endorsement key.+ * - ``keys``+ - 0; 1 when no key material or no ``.bpf`` keyring is found; 2 for a+ usage error.+ * - ``keys add``+ - 0; 1 on failure, and always on a target with a config image; 2 for+ a usage error.+ * - ``keys revoke``+ - 1.+ * - ``config``+ - 0; 1 when the configuration cannot be loaded or ``map_export`` or+ ``tls.classical_hosts`` is invalid; 2 for an unknown option.+ * - ``version``+ - 0.++Operation report+----------------++``--report=<path>`` writes one JSON object after the operation, also+after a refusal. ``--report=-`` writes it to standard output. A usage+error writes no report. shirudo creates the file with mode ``0644`` and+refuses a sealed file, a path under a sealed directory and a symbolic+link.++.. list-table::+ :header-rows: 1+ :widths: 25 15 60++ * - Field+ - Type+ - Value+ * - ``schema``+ - integer+ - ``1``.+ * - ``result``+ - string+ - ``ok`` or ``failed``.+ * - ``op``+ - string+ - ``upatch_load`` or ``upatch_unload``.+ * - ``phase``+ - string+ - The phase that failed, or ``done``.+ * - ``errno``+ - integer or null+ - The positive errno, null when there is none.+ * - ``errno_name``+ - string or null+ - The errno's symbolic name, such as ``ENOKEY``.+ * - ``category``+ - string+ - One of the categories above, ``ok`` or ``already_unloaded``.+ * - ``message``+ - string+ - A short description, at most 255 bytes. Empty on success.+ * - ``verifier_log``+ - string+ - The kernel's log from ``signed_loader_load`` or ``payload_load``,+ up to 16 MiB. Empty otherwise.+ * - ``loader_return``+ - integer+ - The loader's return value from ``BPF_PROG_TEST_RUN``, 0 when it did+ not run.+ * - ``upatch.path``+ - string+ - The path given on the command line.+ * - ``upatch.name``+ - string+ - The upatch name from the header. Empty when the operation stopped+ before the artifact was read.+ * - ``upatch.payload_sha256``+ - string+ - For a load, the artifact's payload digest. For an unload, the+ payload the directive expects. Empty when the operation stopped+ before the artifact was read.+ * - ``kernel.release``+ - string+ - The running kernel's release, from ``uname``.+ * - ``tpm``+ - object or null+ - Present on success when the register moved, else null.+ * - ``tpm.nv_index``+ - string+ - The register's NV index, ``0x01818E00``.+ * - ``tpm.chain_after``+ - string+ - The register value after the extend, 64 hex characters.++A successful load:++.. code-block:: json++ {"schema":1,"result":"ok","op":"upatch_load","phase":"done",+ "errno":null,"errno_name":null,"category":"ok","message":"",+ "verifier_log":"","loader_return":0,+ "upatch":{"path":"/mnt/shirudo-bundle/fixtures/shirudo-test-basic.upatch",+ "name":"shirudo-test-basic",+ "payload_sha256":"8aee7072a1a15e4dddc93ad6b253a0e2e70ad6cdf767442aa8a1c1997bc3069f"},+ "kernel":{"release":"7.3.0-bpf-next+"},+ "tpm":{"nv_index":"0x01818E00",+ "chain_after":"c50b22ac27c5bb6a90ee5ff9b440fbbd5bb60b84a2aa7b395daec3f330886fcd"}}++A load refused because the register differs from ``--expect-chain``. The+journal line names the cause, ``chain_drift``:++.. code-block:: json++ {"schema":1,"result":"failed","op":"upatch_load","phase":"pre_flight",+ "errno":1,"errno_name":"EPERM","category":"tampered",+ "message":"pre-flight check failed","verifier_log":"","loader_return":0,+ "upatch":{"path":"/mnt/shirudo-bundle/fixtures/shirudo-test-lifecycle.upatch",+ "name":"shirudo-test-lifecycle",+ "payload_sha256":"2324dff6596d09695c57b45a234627a9e3efbd60c9a2818c5914e6c9e52f17b0"},+ "kernel":{"release":"7.3.0-bpf-next+"},"tpm":null}++A load refused by ``--expect-version-id``, before the artifact was read:++.. code-block:: json++ {"schema":1,"result":"failed","op":"upatch_load","phase":"pre_flight",+ "errno":1,"errno_name":"EPERM","category":"version_mismatch",+ "message":"SHIRUDO_VERSION_ID mismatch (operator vs target)",+ "verifier_log":"","loader_return":0,+ "upatch":{"path":"/mnt/shirudo-bundle/fixtures/shirudo-test-lifecycle.upatch",+ "name":"","payload_sha256":""},+ "kernel":{"release":"7.3.0-bpf-next+"},"tpm":null}++A load of an artifact signed by a key the target does not trust:++.. code-block:: json++ {"schema":1,"result":"failed","op":"upatch_load",+ "phase":"signed_loader_load","errno":126,"errno_name":"ENOKEY",+ "category":"keyring_missing",+ "message":"BPF_PROG_LOAD of signed loader failed",+ "verifier_log":"signature verification failed: -126\n","loader_return":0,+ "upatch":{"path":"/mnt/shirudo-bundle/fixtures/shirudo-test-foreign.upatch",+ "name":"shirudo-test-foreign",+ "payload_sha256":"d3e0d0a546f9aacc9e5828d479793dc4e848c4e835c8ac2bd55b2584374bc913"},+ "kernel":{"release":"7.3.0-bpf-next+"},"tpm":null}++An unload directive that expects another payload than the loaded one:++.. code-block:: json++ {"schema":1,"result":"failed","op":"upatch_unload","phase":"pin",+ "errno":1,"errno_name":"EPERM","category":"payload_mismatch",+ "message":"loaded payload does not match directive","verifier_log":"",+ "loader_return":0,+ "upatch":{"path":"/mnt/shirudo-bundle/fixtures/shirudo-test-basic-mismatch.unload.upatch",+ "name":"shirudo-test-basic",+ "payload_sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},+ "kernel":{"release":"7.3.0-bpf-next+"},"tpm":null}++shirudo prints each report on one line. The examples are wrapped.++Tree sync report+----------------++``shirudo bpm tree sync`` writes its own report to standard output, or+to ``--report=<path>`` with mode ``0600``.++.. list-table::+ :header-rows: 1+ :widths: 25 15 60++ * - Field+ - Type+ - Value+ * - ``schema``+ - integer+ - ``1``.+ * - ``dry_run``+ - boolean+ - Whether ``--dry-run`` was given.+ * - ``selected``+ - integer+ - Operations whose selector matches this target.+ * - ``skipped``+ - integer+ - Operations whose selector does not match.+ * - ``applied``+ - integer+ - Operations applied and measured in this run.+ * - ``module_skipped``+ - integer+ - ``add`` operations measured but not loaded because of+ ``attach_target_missing``.+ * - ``tpm_available``+ - boolean+ - Whether the register is bound this boot.+ * - ``last_seq``+ - integer+ - The last operation sequence number this target has processed.+ * - ``projection_root_tpm``+ - string or null+ - The tree's projection root, null without a bound register.++A failed sync logs ``bpm tree sync: phase=<phase> seq=<seq> id=<id>+rc=<rc> (<strerror>)`` and exits 1:++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Phase+ - Failure+ * - ``operation_validate``+ - An operation of the publication is malformed or its digest does+ not match.+ * - ``pending_recovery``+ - An interrupted operation cannot be reconciled with the tree+ eventlog.+ * - ``selector_evaluate``+ - The selector cannot be evaluated.+ * - ``operation_digest_parse``+ - The operation digest is malformed.+ * - ``expected_payload_digest``+ - The artifact's payload differs from the expected payload.+ * - ``pending_write``+ - ``pending.json`` cannot be written.+ * - ``artifact_fetch_or_verify``+ - The artifact cannot be fetched or does not match its digests.+ * - ``upatch_install``+ - The load or unload failed. ``rc`` is the exit status of+ ``upatch load`` or ``upatch unload``.+ * - ``projection_root_decode``+ - The recorded projection root is malformed.+ * - ``register_extend``+ - The register extend failed.+ * - ``tree_event_append``+ - The tree eventlog record cannot be appended.+ * - ``tree_state_commit``, ``tree_state_commit_final``+ - ``state.json`` cannot be written.+ * - ``tree_status_write``+ - The per-operation status file cannot be written.++Related+-------++- :doc:`/reference/cli/upatch-load` and :doc:`/reference/cli/upatch-unload`+- :doc:`/operate/troubleshooting`+- :doc:`/operate/incident-tampered`+- :doc:`/security/tamper-counters`diff --git a/Documentation/reference/files.rst b/Documentation/reference/files.rstnew file mode 100644index 00000000..e1f61198--- /dev/null+++ b/Documentation/reference/files.rst@@ -0,0 +1,495 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Files, paths and xattrs+=======================++The files, directories, pins and extended attributes shirudo reads and+writes. In the Protection columns, "seal" means the inode carries the+``security.bpf.shirudo`` label (see :doc:`/internals/seal`), "dm-verity"+means a read-only mount of a verified image and "bpffs" means the+guards of the private bpffs.++Operator host+-------------++.. list-table::+ :header-rows: 1+ :widths: 38 20 10 32++ * - Path+ - Written by+ - Mode+ - Purpose+ * - ``/var/lib/shirudo/keys/``+ - ``genkey``+ - ``0700``+ - Default keys directory. ``--keys-dir`` and ``SHIRUDO_KEYS_DIR``+ select another.+ * - ``<keys-dir>/signing_key.pem``+ - ``genkey``+ - ``0600``+ - ML-DSA-87 private key, PEM. ``shirudo-build`` refuses a key whose+ mode is not exactly ``0600``.+ * - ``<keys-dir>/cert.der``+ - ``genkey``+ - ``0600``+ - Self-signed X.509 certificate of the signing key, DER.+ * - ``<keys-dir>/signing_key.pem.new``, ``cert.der.new``,+ ``signing_key.pem.old``+ - ``genkey --force``+ - ``0600``+ - Transient during a key replacement.+ * - ``/var/lib/shirudo/upatches/<name>.upatch``+ - none+ - none+ - Read by ``shirudo build --unload <name>`` without+ ``--payload-sha256`` to take the expected payload from a local+ archive.+ * - ``./vmlinux.h``, ``./vendor/linux/vmlinux.h``,+ ``<sharedir>/shirudo/vmlinux.h``+ - none+ - none+ - Searched in this order when ``--vmlinux`` is not given.+ * - ``/usr/bin/clang``+ - none+ - none+ - The compiler ``shirudo-build`` executes for ``.bpf.c`` input.+ * - ``/tmp/shirudo-build-XXXXXX.bpf.o``+ - ``build``+ - none+ - Temporary object, removed after packaging.+ * - ``/etc/shirudo/shirudo.conf``+ - administrator+ - none+ - Operator settings, such as ``tls.classical_hosts``. See+ :doc:`/reference/formats/configuration`.++Output files the caller names: ``.upatch`` artifacts and ``.vouch``+files with mode ``0644``, ``.bee`` packages with mode ``0600``.++Target persistent state+-----------------------++Everything under ``/var/lib/shirudo`` on the state file system is+sealed. The first ``init`` labels every regular file and directory there.+From then on shirudo labels what it creates, and ignores an entry without+the label as foreign. In the initrd, ``init`` binds+``/sysroot/var/lib/shirudo`` writable over ``/var/lib/shirudo``.++.. list-table::+ :header-rows: 1+ :widths: 36 20 9 35++ * - Path+ - Written by+ - Mode+ - Purpose+ * - ``/var/lib/shirudo/``+ - ``init``+ - ``0700``+ - State root.+ * - ``keys/cert.der``+ - installer, ``bpm key add``+ - none+ - Checked by the ``cert_on_disk`` pre-flight outside the initrd, and+ the default certificate the dracut module copies into the initrd.+ On a running target the certificates come from the runtime and+ config images.+ * - ``keys/<fingerprint>.der``+ - ``bpm key add``+ - ``0644``+ - A certificate installed without a config image. ``bpm key add``+ is refused on a target with a config image.+ * - ``keys/trusted/``, ``keys/revoked/``+ - ``keys add`` (``trusted/``)+ - none+ - Trusted and revoked sets read when no config image is mounted.+ ``keys add`` is refused on a target with a config image.+ * - ``upatches/<name>.upatch``+ - ``upatch load``+ - ``0644``+ - Archive of every loaded upatch, restored by ``init`` at boot.+ ``upatch unload`` and a revocation purge remove it.+ * - ``incoming/load-<pid>.upatch``+ - ``upatch load``, ``upatch unload``+ - ``0600``+ - The one copy of the artifact an operation reads. Removed when it+ ends.+ * - ``eventlog``+ - measuring commands+ - ``0600``+ - Append-only eventlog, one JSON record per line. See+ :doc:`/reference/formats/eventlog`.+ * - ``eventlog.lock``+ - measuring commands+ - ``0600``+ - Lock held from each register extend to its eventlog append.+ * - ``locks/bpm.lock``+ - ``bpm``+ - ``0600``+ - Lock of ``repo update``, ``tree sync``, ``install``,+ ``uninstall`` and ``upgrade``.+ * - ``bpm/state.json``+ - ``bpm install``, ``uninstall``, ``upgrade``+ - ``0600``+ - Installed packages.+ * - ``bpm/repos/<source>/index.json``+ - ``bpm repo update``+ - ``0600``+ - Cached, verified package index of a repository.+ * - ``bpm/staging/<name>-<version>.bee``+ - ``bpm install``, ``upgrade``+ - ``0600``+ - Package download before it is verified and extracted.+ * - ``bpm/packages/<name>/<version>/``+ - ``bpm install``, ``upgrade``+ - none+ - Extracted package: ``cert.der``, ``upatches/*.upatch`` and the+ unload directives.+ * - ``bpm/packages/<name>/<name>-<version>.bee``+ - ``bpm install``, ``upgrade``+ - ``0600``+ - The installed package archive.+ * - ``bpm/upatch-tree/state.json``+ - ``bpm tree sync``+ - ``0600``+ - Tree cursor: tree id, generation, last sequence number,+ projection root, manifest digest.+ * - ``bpm/upatch-tree/tree-eventlog``+ - ``bpm tree sync``+ - ``0600``+ - Append-only record of applied tree operations.+ * - ``bpm/upatch-tree/pending.json``+ - ``bpm tree sync``+ - ``0600``+ - The operation in progress, removed when it completes.+ * - ``bpm/upatch-tree/artifacts/<layer-digest>.upatch``+ - ``bpm tree sync``+ - ``0600``+ - Fetched artifacts, named by their OCI layer digest.+ * - ``bpm/upatch-tree/status/<id>``+ - ``bpm tree sync``+ - ``0600``+ - ``skipped: module not loaded`` for an ``add`` operation whose+ target is absent.+ * - ``config-update/lock``, ``state``, ``events``+ - ``init``, ``image update``+ - ``0600``+ - Config activation record and its event history.+ * - ``images/<root-hash>.img``, ``.verity``, ``.roothash``, ``.p7s``+ - ``image update``+ - none+ - Fetched config images, named by their dm-verity root hash.+ * - ``images/incoming-XXXXXX/``+ - ``image update``+ - none+ - Staging directory of a fetch.++The paths in the table are relative to ``/var/lib/shirudo/``.++Target per-boot state+---------------------++``init`` creates ``/run/shirudo`` with mode ``0700``. When it lies on the+same file system as ``/run``, ``init`` mounts a private ``tmpfs`` there+(``nosuid``, ``nodev``, ``noexec``, 16 MiB) and labels it. systemd+carries ``/run`` from the initrd into the root file system.++.. list-table::+ :header-rows: 1+ :widths: 36 18 16 30++ * - Path+ - Written by+ - Protection+ - Purpose+ * - ``/run/shirudo/eventlog.pending``+ - ``init`` in the initrd+ - seal, ``0600``+ - The initrd's eventlog record. The next append on the root file+ system adopts it into ``/var/lib/shirudo/eventlog`` and removes+ it.+ * - ``/run/shirudo/bpffs/``+ - ``init``+ - bpffs+ - Private bpffs (``mode=0700``, ``nosuid``, ``nodev``,+ ``noexec``) holding every pin.+ * - ``/run/shirudo/runtime/``+ - ``init``+ - dm-verity+ - The runtime image, mounted read-only, ``nodev``, ``nosuid``. The+ dm-verity mapping is ``shirudo-runtime``.+ * - ``/run/shirudo/config/``+ - ``init``, ``image update``+ - dm-verity+ - The active config image, mounted read-only, ``nodev``,+ ``nosuid``, ``noexec``.+ * - ``/run/shirudo/config-candidate/``+ - ``image update``+ - dm-verity+ - A config image being activated. Its mapping is+ ``shirudo-config-<root-hash>``.++Runtime image+~~~~~~~~~~~~~++``shirudo-gen-runtime`` lays out the runtime image. Paths are relative+to ``/run/shirudo/runtime/``.++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Path+ - Content+ * - ``usr/bin/shirudo``+ - The runtime binary. ``shirudo.service`` runs it through the+ generated drop-in.+ * - ``usr/bin/<name>``+ - Binaries added with ``--extra-binary``.+ * - ``etc/shirudo/shirudo.conf``+ - Runtime settings.+ * - ``etc/shirudo/config-cert.der``+ - Certificate that verifies config image signatures, named by+ ``config.verification_key``.+ * - ``keys/cert.der``+ - The initial BPF signing certificate.+ * - Library paths+ - The interpreter and shared libraries of a dynamically linked+ binary.++Config image+~~~~~~~~~~~~++Paths are relative to ``/run/shirudo/config/``. On a target with a+config image, shirudo reads these instead of the host files of the same+name under ``/etc/shirudo``.++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Path+ - Content+ * - ``etc/shirudo/shirudo.conf``+ - Settings the config image may carry.+ * - ``etc/shirudo/bpm/registries.d/<source>.conf``+ - Package repositories.+ * - ``etc/shirudo/bpm/keys/``+ - Repository certificates.+ * - ``etc/shirudo/bpm/upatch-tree.conf``+ - upatch tree source.+ * - ``etc/shirudo/node.labels``+ - Labels that tree selectors match.+ * - ``keys/trusted/``+ - Vouched BPF signing certificates.+ * - ``keys/revoked/``+ - Revoked certificates.++See :doc:`/reference/formats/configuration` for the keys of each file.++Private bpffs pins+------------------++Every pin lives under ``/run/shirudo/bpffs/``. The ``lsm/inode_unlink``+guard refuses removing a pin (counter ``PinUnlink``) and the mount guards+refuse unmounting or covering the bpffs (``BpffsUmount``). A task without+runtime authority cannot open a pin that is not a directory, by path or+by ``BPF_OBJ_GET`` (``ObjGet``). Directories stay listable.++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Pin+ - Content+ * - ``lsm_link``+ - Link of ``lsm/bpf``, the ``bpf()`` admission hook. Its presence+ makes ``status`` report ``Mode: production``.+ * - ``bpf2_bpf_map_link``, ``bpf2_bpf_prog_load_link``,+ ``bpf2_inode_unlink_link``, ``bpf2_inode_setxattr_link``,+ ``bpf2_inode_removexattr_link``, ``bpf2_key_permission_link``,+ ``bpf2_tpm_command_link``+ - Links of the other admission and gate hooks.+ * - ``bpf2_sb_umount_link``, ``bpf2_move_mount_link``,+ ``bpf2_sb_mount_link``, ``bpf2_sb_remount_link``,+ ``bpf2_file_open_link``+ - Links of the mount and bpffs guards.+ * - ``bpf2_task_prctl_link``, ``bpf2_bprm_check_security_link``,+ ``inode_rmdir_link``, ``bpf2_inode_rename_link``,+ ``inode_mkdir_link``, ``inode_symlink_link``, ``inode_link_link``,+ ``kernel_load_data_link``, ``kernel_read_file_link``+ - Links of the observer hooks.+ * - ``file_ioctl_link``, ``file_ioctl_compat_link``,+ ``bdev_integrity_link``, ``bdev_free_link``+ - Links of the image observer hooks.+ * - ``seal_*_link``+ - Links of the seal hooks, one per hook, such as+ ``seal_file_open_link`` and ``seal_mmap_link``.+ * - ``identity``+ - Map ``shirudo_bpffs_sb``: the frozen record of this boot, such+ as the ``.bpf`` keyring serial, the runtime root hash and the NV+ index.+ * - ``tamper``+ - Map ``shirudo_tamper``: the tamper counters. See+ :doc:`/security/tamper-counters`.+ * - ``task_authority``, ``config_roots``+ - Task storage maps of runtime authority and expected config roots.+ * - ``devices``+ - Map of the dm-verity devices shirudo set up, with their root+ hashes.++Pins of a upatch+~~~~~~~~~~~~~~~~++Each loaded upatch has a directory ``upatches/<bpffs-name>/`` in the+private bpffs. ``<bpffs-name>`` is the upatch name with every ``.``+written as ``~d``.++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Pin+ - Content+ * - ``link``+ - The link of the only attached program.+ * - ``link_<n>``+ - The link of attached program ``<n>`` when there are several.+ * - ``test``+ - A program with the test-run role.+ * - ``serializers/<map>``+ - The serializer program of ``<map>``.+ * - ``maps/<map>``+ - The upatch's maps, less those whose name contains ``.`` or starts+ with ``obs_i_``.++Extended attributes+-------------------++.. list-table::+ :header-rows: 1+ :widths: 30 25 45++ * - Name+ - On+ - Value and rules+ * - ``security.bpf.shirudo``+ - Every regular file and directory of shirudo's writable state:+ ``/var/lib/shirudo``, ``/run/shirudo``.+ - 64 lowercase hex characters, the SHA-256 of the attribute name,+ the same on every build. The seal treats any value as the label.+ Only a task with runtime authority may set it (``SealLabel``).+ A file created in a labelled directory receives the label at+ creation.+ * - ``security.bpf.shirudo.payload``+ - Each ``upatches/<bpffs-name>/`` directory in the private bpffs.+ - 32 bytes, the ``payload_sha256`` of the loaded upatch. Set after+ attach and pin, read by ``upatch unload`` for the+ ``payload_mismatch`` check. The bpffs guards refuse setting or+ removing it to any other task (``PinXattr``).++Host configuration+------------------++.. list-table::+ :header-rows: 1+ :widths: 38 62++ * - Path+ - Use+ * - ``/etc/shirudo/shirudo.conf``+ - On the root file system: the source of the initrd's bootstrap+ file and the settings of a host without images. In the initrd:+ the bootstrap file. See :doc:`/reference/formats/configuration`.+ * - ``/etc/shirudo/keys/cert.der``, ``/etc/shirudo/keys/trusted/``+ - In the initrd only: the certificates the dracut module copies in.+ * - ``/etc/shirudo/bpm/registries.d/<source>.conf``+ - Repository of a host without a config image. Written by ``bpm+ config register add`` with mode ``0644``.+ * - ``/etc/shirudo/bpm/keys/<source>.der``+ - Repository certificate of a host without a config image, ``0644``.+ * - ``/etc/shirudo/bpm/upatch-tree.conf``+ - Tree source of a host without a config image.+ * - ``/etc/shirudo/node.labels``+ - Node labels of a host without a config image.+ * - ``/etc/shirudo/init.env``+ - ``EnvironmentFile`` of ``shirudo.service``. The runtime drop-in+ clears it.+ * - ``/etc/shirudo/map-export.env``+ - ``EnvironmentFile`` of ``shirudo-keepalive.service`` and+ ``shirudo-map-export.service``.+ * - ``/etc/shirudo/bpm/environment``+ - ``EnvironmentFile`` of ``shirudo-bpm-repo-update.service`` and+ ``shirudo-bpm-tree-sync.service``.++shirudo refuses a configuration file under ``/etc/shirudo`` or+``/var/lib/shirudo`` that is not a regular file, is owned by another+user than root or the caller, or is writable by group or others, and+the same for each directory above it unless that directory is root's+and sticky. A ``shirudo.conf`` that sets+``tpm.owner_auth`` must also not be readable by group or others. The+``EnvironmentFile`` paths are read by systemd, not by shirudo.++Kernel and system interfaces+----------------------------++.. list-table::+ :header-rows: 1+ :widths: 42 58++ * - Path+ - Read for+ * - ``/dev/tpmrm0``+ - The TPM, through the default TCTI ``device:/dev/tpmrm0``.+ * - ``/dev/mapper/control``, ``/dev/loop-control``, ``/dev/loop*``,+ ``/dev/dm-*``+ - Creating and checking the dm-verity mappings of the images.+ * - ``/sys/kernel/security/lsm``, ``/proc/filesystems``+ - Pre-flight: BPF LSM active, bpffs supported.+ * - ``/proc/self/mounts``+ - Whether the private bpffs is mounted.+ * - ``/proc/sys/kernel/random/boot_id``+ - The ``boot_id`` of eventlog records.+ * - ``/sys/kernel/security/tpm0/binary_bios_measurements``,+ ``/run/log/systemd/tpm2-measure.log``+ - The firmware and systemd event logs ``attest`` includes.+ * - ``/sys/bus/event_source/devices/kprobe/type``,+ ``/sys/bus/event_source/devices/kprobe/format/retprobe``+ - Attaching kprobe and kretprobe programs.+ * - ``/sys/fs/cgroup``+ - Attaching ``cgroup_skb`` programs at the root cgroup.+ * - ``/proc/modules``, ``/sys/module/``+ - ``status --include-modules``.+ * - ``/sys/kernel/notes``, ``/boot/config-<release>``,+ ``/proc/config.gz``+ - Kernel build ID and configuration, matched by tree selectors.+ * - ``/etc/os-release``, ``/etc/machine-id``, ``/proc/meminfo``,+ ``/proc/uptime``+ - ``status --include-system``.+ * - ``/dev/kmsg``+ - ``status --include-kernellog``.+ * - ``/etc/initrd-release``+ - Whether ``init`` runs in the initrd.++Temporary files+---------------++``bpm info`` and ``bpm key`` create ``/tmp/shirudo-bpm-*-XXXXXX``+files. ``upatch map --s3-uri`` writes a+snapshot to ``$TMPDIR/shirudo-map-snapshot.XXXXXX`` (``/tmp`` when+``TMPDIR`` is unset) with mode ``0600``.++Related+-------++- :doc:`/operate/backup-recovery`+- :doc:`/internals/seal`+- :doc:`/security/tamper-counters`+- :doc:`/reference/environment`+- :doc:`/reference/systemd-units`diff --git a/Documentation/reference/formats/bpm-formats.rst b/Documentation/reference/formats/bpm-formats.rstnew file mode 100644index 00000000..357c2f19--- /dev/null+++ b/Documentation/reference/formats/bpm-formats.rst@@ -0,0 +1,565 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: upatch authors++Package, index and tree formats+===============================++shirudo publishes three kinds of objects to an OCI registry: packages+(``.bee`` files), the signed repository index that lists them, and upatch+trees. The operator writes them with ``bpm build``, ``bpm push`` and+``bpm tree append`` (see :doc:`/reference/cli/bpm`). The target reads them+with ``bpm repo update``, ``bpm install``, ``bpm upgrade`` and+``bpm tree sync``. The ``.upatch`` files inside are specified in+:doc:`upatch-format`.++What is signed+--------------++.. list-table::+ :header-rows: 1+ :widths: 24 40 36++ * - Object+ - Protection+ - Checked by+ * - ``.upatch`` file+ - CMS signature, ML-DSA-87, over ``loader_insns || data``.+ - The kernel, at every load and unload.+ * - Repository index document+ - Detached CMS signature over the exact document bytes.+ - ``bpm repo update``, against the repository's key file from the+ configuration. ``bpm push`` also checks the published index against+ ``--index-cert`` before it adds an entry.+ * - Package manifest and ``.bee`` archive+ - Not signed. The signed index pins them by ``manifest_digest``,+ ``package_digest`` and ``package_size``.+ - ``bpm install`` and ``bpm upgrade`` from a repository.+ * - Package installed by ``oci://`` reference+ - Not signed and not pinned. The reference names a tag.+ - Only the per-``.upatch`` signatures and the ``cert.der`` check below.+ * - ``cert.der`` in a package+ - Its public key must equal the public key of the target's+ ``/var/lib/shirudo/keys/cert.der``.+ - ``bpm install`` and ``bpm upgrade``, before any upatch loads.+ * - ``Beefile``, ``README.md``, ``build-environment.json``, files+ - Not signed. Covered by the archive digest when the index pins it.+ - None beyond the archive digest.+ * - Tree publication document+ - Detached CMS signature over the exact document bytes.+ - ``bpm tree sync``, against the runtime image's initial certificate.+ * - Tree artifact manifest and ``.upatch`` layer+ - Not signed. Each signed operation pins them by+ ``manifest_digest``, ``layer_digest`` and ``payload_sha256``.+ - ``bpm tree sync``.+ * - Certificate referrer manifest+ - Not signed.+ - Not read by shirudo.++The detached signatures use the same CMS profile as the ``.upatch``+signature: DER ``SignedData``, no encapsulated content, no certificates,+ML-DSA-87, signer named by subject key identifier. The verifier checks it+against the one configured certificate without a validity-time check.++Names+-----++.. list-table::+ :header-rows: 1+ :widths: 24 30 46++ * - Name+ - Source+ - Rule+ * - Package name+ - Beefile ``[package] name``+ - Starts with a letter or digit, then ``[A-Za-z0-9._-]``, fewer than+ 128 characters.+ * - Package version+ - ``bpm build --version``+ - ``[A-Za-z0-9._+-]``, does not start with ``.``, fewer than 128+ characters. The newest version is chosen by SemVer 2.0.0+ precedence, build metadata ignored.+ * - upatch name+ - The source file's basename without ``.bpf.c``, ``.bpf.o`` or ``.o``+ - The Beefile cannot override it. 1 to 255 characters of+ ``[A-Za-z0-9._-]``, not starting with ``.``.+ * - Tree operation ``id``+ - Beefile ``[upatches.tree] id``+ - Must equal the upatch name of the artifact it publishes, so the+ source file's basename. ``bpm tree append`` and ``bpm tree sync``+ both refuse a mismatch.+ * - Tree ``tree_id``+ - ``--tree-id``, else the package name of the first append+ - Fixed for the life of the tree. Distinct from the operation ``id``.++Package archive+---------------++``bpm build`` writes ``<name>-<version>.bee``, a gzip-compressed ustar+archive with one top-level directory ``<name>-<version>/``. Members carry+uid and gid 0 and mtime 0.++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Member+ - Content+ * - ``<name>-<version>/``+ - The top-level directory, mode 0755.+ * - ``Beefile``+ - The Beefile the package was built from.+ * - ``<target>``+ - Each ``[[files]]`` entry at its ``target`` path.+ * - ``upatches/<base>.upatch``+ - Each ``[[upatches]]`` load artifact, at its ``load_target``. The+ default name is the source basename without its extension.+ * - ``upatches/<base>.unload.upatch``+ - The matching unload directive, at its ``unload_target``.+ * - ``README.md``+ - Present when the package directory has one.+ * - ``cert.der``+ - The signing certificate, DER.+ * - ``build-environment.json``+ - Build record, see below.++``Beefile``, ``README.md``, ``cert.der`` and ``build-environment.json`` are+reserved and cannot be ``[[files]]`` or upatch targets.+:doc:`/upatches/beefile` describes the Beefile.++On install the target loads every regular file in ``upatches/`` whose name+contains ``.upatch`` and not ``.unload.upatch``, in name order. Uninstall+and upgrade apply the package's ``*.unload.upatch`` files in reverse name+order.++Archive reader rules+~~~~~~~~~~~~~~~~~~~~++The target refuses an archive that breaks any of these:++- Each header is a 512-byte ustar header with a valid checksum, a name+ that is NUL-terminated within its 100 bytes, an empty prefix field and a+ size field of octal digits.+- Every member lies under the one top-level directory. No path is+ absolute or has an empty or ``..`` component.+- Every member is a regular file or a directory.+- At most 4096 members and 256 MiB of content.+- No regular file appears twice.++build-environment.json+~~~~~~~~~~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Key+ - Value+ * - ``format_version``+ - ``1``.+ * - ``builder``+ - ``"bpm build"``.+ * - ``created_at``+ - UTC time, ``YYYY-MM-DDTHH:MM:SSZ``.+ * - ``package.name``, ``package.version``+ - Package name and version. ``bpm push``, ``bpm tree append`` and+ ``bpm config update`` require both.+ * - ``os``, ``arch``+ - ``uname`` system name and machine of the build host.+ * - ``bpm_version``+ - shirudo version of the builder.+ * - ``shirudo.path``, ``shirudo.version``+ - Path and version of the building binary.+ * - ``shirudo.spki_sha256_fingerprint``+ - SHA-256 of the DER ``SubjectPublicKeyInfo`` of ``cert.der``, hex.+ When present, ``bpm push``, ``bpm tree append`` and+ ``bpm config update`` refuse the package if it differs from+ ``cert.der``.+ * - ``upatches[]``+ - Per upatch: ``source``, ``type``, ``load_target``, ``load_output``,+ ``unload_target``, ``unload_output``, ``upatch_name``,+ ``payload_sha256``.++Package in the registry+~~~~~~~~~~~~~~~~~~~~~~~++``bpm push <package> oci://<registry>/<repository>`` uploads:++.. list-table::+ :header-rows: 1+ :widths: 26 74++ * - Object+ - Content+ * - Package manifest+ - OCI image manifest, ``schemaVersion`` 2. Config blob+ ``{"mediaType":"application/vnd.shirudo.bpm.config.v1+json"}`` of+ that media type. One layer, the ``.bee`` file, media type+ ``application/vnd.shirudo.bpm.package.v1+gzip``, with an+ ``org.opencontainers.image.title`` annotation of the file name.+ Manifest annotations ``dev.shirudo.bpm.package.name``,+ ``dev.shirudo.bpm.package.version``,+ ``org.opencontainers.image.title`` and+ ``org.opencontainers.image.version``. Tagged with the package+ version after the index update.+ * - Certificate referrer+ - OCI image manifest with ``artifactType``+ ``application/vnd.shirudo.bpm.public-key.v1+der``, the empty config+ ``application/vnd.oci.empty.v1+json``, one ``application/pkix-cert``+ layer holding ``cert.der``, and ``subject`` set to the package+ manifest.+ * - Index entry+ - Added when signing material is given (``--keys-dir``, or+ ``--index-cert`` with ``--index-key``), see below.++The last path component of ``<repository>`` follows the package name rule.++Repository index+----------------++One index per registry, at ``<registry>/shirudo/bpm-index:stable``.++.. list-table::+ :header-rows: 1+ :widths: 26 74++ * - Object+ - Content+ * - Index manifest+ - OCI image manifest, ``schemaVersion`` 2, ``artifactType``+ ``application/vnd.shirudo.bpm.index.v1``, the empty config, and two+ layers.+ * - Document layer+ - The index document, media type+ ``application/vnd.shirudo.bpm.index.v1+json``.+ * - Signature layer+ - Detached CMS signature over the document layer's bytes, media type+ ``application/vnd.shirudo.bpm.index.signature.v1``.++The index document:++.. code-block:: text++ {"schema": 1,+ "generated_at": "<utc-time>",+ "packages": [+ {"name": "<package>", "version": "<version>",+ "repository": "<repository>",+ "manifest_digest": "sha256:<hex>",+ "package_digest": "sha256:<hex>",+ "package_size": <bytes>,+ "signer_fingerprint": "<hex>"}]}++.. list-table::+ :header-rows: 1+ :widths: 26 74++ * - Key+ - Value+ * - ``schema``+ - ``1``. Required.+ * - ``generated_at``+ - UTC time of the push. Not read by the target.+ * - ``packages``+ - Required. At most 512 entries. ``bpm push`` sorts them by name,+ then version.+ * - ``name``, ``version``+ - Package name and version.+ * - ``repository``+ - Repository path on the index's registry, without the host.+ * - ``manifest_digest``+ - Digest of the package manifest. The target fetches the manifest by+ this digest and refuses other bytes.+ * - ``package_digest``+ - Digest of the ``.bee`` layer. The target refuses a manifest whose+ package layer has another digest, and a download that hashes to+ another value.+ * - ``package_size``+ - Size of the ``.bee`` layer in bytes. When positive, the target+ refuses a layer of another size.+ * - ``signer_fingerprint``+ - ``shirudo.spki_sha256_fingerprint`` of the package. Not checked by+ the target.++A published version is immutable: ``bpm push`` refuses to list a name and+version again with a different ``manifest_digest`` or ``package_digest``.+The target keeps the verified document as+``/var/lib/shirudo/bpm/repos/<source>/index.json``.++upatch tree+-----------++A tree is an append-only sequence of ``add`` and ``delete`` operations in+one repository, ``oci://<registry>/<repository>``. ``bpm tree append``+publishes one operation per ``[upatches.tree]`` entry of a package.++Tree objects in the registry+~~~~~~~~~~~~~~~~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 26 74++ * - Object+ - Content+ * - Publication manifest+ - At ``<repository>:<reference>``, ``stable`` unless+ ``--reference`` names another tag. OCI image manifest,+ ``schemaVersion`` 2, ``artifactType``+ ``application/vnd.shirudo.upatch.tree.v2``, the empty config, and+ exactly one document layer and one signature layer.+ * - Document layer+ - The publication document, media type+ ``application/vnd.shirudo.upatch.tree.v2+json``.+ * - Signature layer+ - Detached CMS signature over the document layer's bytes, media type+ ``application/vnd.shirudo.upatch.tree.signature.v2``.+ * - Artifact manifest+ - One per operation, tagged ``upatch-<id>-<payload16>``, where+ ``<payload16>`` is the first 16 hex digits of the artifact's+ ``payload_sha256``. ``artifactType`` and layer media type+ ``application/vnd.shirudo.upatch.v1``, the empty config, one layer+ holding the ``.upatch`` file, annotation+ ``org.opencontainers.image.title`` ``<id>.upatch``. An ``add``+ publishes the load artifact, a ``delete`` the unload directive.++Publication document+~~~~~~~~~~~~~~~~~~~~++.. code-block:: text++ {"schema": 2,+ "tree_id": "<tree-id>",+ "generation": <n>,+ "parent_manifest_digest": "sha256:<hex>",+ "base": {"seq": 0},+ "operations": [<operation>, ...],+ "head": {"seq": <n>}}++.. list-table::+ :header-rows: 1+ :widths: 28 72++ * - Key+ - Value+ * - ``schema``+ - ``2``. Required.+ * - ``tree_id``+ - Non-empty. Required.+ * - ``generation``+ - Required. 1 for the first publication, one more for each append.+ From 0 to 2\ :sup:`63` - 2.+ * - ``parent_manifest_digest``+ - Digest of the publication manifest this one replaces. Absent in+ the first publication.+ * - ``base.seq``+ - Required. The target accepts only 0.+ * - ``operations``+ - Required. At most 512. Each ``seq`` is one more than the previous+ one, and the first is ``base.seq + 1``.+ * - ``head.seq``+ - Required. The ``seq`` of the last operation, or ``base.seq`` when+ there is none. Below 2\ :sup:`63` - 1.++Unknown keys are ignored.++Operation+~~~~~~~~~++.. code-block:: text++ {"seq": <n>, "op": "add", "id": "<upatch-name>",+ "selector": {...},+ "artifact": {"repository": "oci://<registry>/<repository>",+ "manifest_digest": "sha256:<hex>",+ "layer_digest": "sha256:<hex>",+ "payload_sha256": "sha256:<hex>"},+ "operation_digest": "sha256:<hex>"}++.. list-table::+ :header-rows: 1+ :widths: 28 72++ * - Key+ - Value+ * - ``seq``+ - Positive sequence number.+ * - ``op``+ - ``add`` or ``delete``.+ * - ``id``+ - The upatch name of the artifact. Must be a valid upatch name.+ * - ``selector``+ - Which nodes apply the operation, see `Selector`_. ``bpm tree+ append`` always writes it. Absent or ``{}``, it matches every node.+ * - ``artifact.repository``+ - ``oci://<registry>/<repository>`` the artifact manifest lives in.+ * - ``artifact.manifest_digest``+ - Digest of the artifact manifest.+ * - ``artifact.layer_digest``+ - Digest of the ``.upatch`` layer.+ * - ``artifact.payload_sha256``+ - ``sha256:`` and the artifact's header ``payload_sha256``.+ * - ``expected_payload_sha256``+ - Optional. When present, must equal ``artifact.payload_sha256``.+ ``bpm tree append`` does not write it, and ``operation_digest`` does+ not cover it.+ * - ``operation_digest``+ - ``sha256:`` and the SHA-256 of the canonical operation, see+ `Operation digest`_.++Selector+~~~~~~~~++Every key present must match. A list matches when one value matches.++.. list-table::+ :header-rows: 1+ :widths: 26 30 44++ * - Key+ - Type+ - Matches when+ * - ``architecture``+ - list of strings+ - One value equals ``uname`` machine, for example ``x86_64``.+ * - ``kernel_release_prefix``+ - list of strings+ - The kernel release starts with the value, followed by the end, a+ ``.`` or a ``-``.+ * - ``kernel_build_id``+ - list of strings+ - One value equals the kernel's GNU build ID from+ ``/sys/kernel/notes``, lowercase hex. A kernel without one never+ matches.+ * - ``kconfig``+ - object of lists+ - For each option, its value in ``/proc/config.gz``, else+ ``/boot/config-<release>``, is in the list. ``# CONFIG_<x> is not+ set`` reads as ``n``. ``kernel_config`` is accepted as an alias when+ parsing.+ * - ``labels``+ - object of lists+ - For each key, the node label's value is in the list. Node labels+ come from ``etc/shirudo/node.labels`` in the config image. A node+ without labels never matches.++Lists hold 1 to 16 strings of fewer than 256 bytes. ``kconfig`` and+``labels`` hold at most 64 keys each.++Operation digest+~~~~~~~~~~~~~~~~++``operation_digest`` is the SHA-256 of the compact JSON of the operation+without ``operation_digest``, in this form:++- Keys in the order ``seq``, ``op``, ``id``, ``selector``, ``artifact``.+- ``selector`` keys in byte order: ``architecture``, ``kconfig``,+ ``kernel_build_id``, ``kernel_release_prefix``, ``labels``. Empty lists+ are left out. ``kconfig`` and ``labels`` keys in byte order.+- List values in the published order. ``bpm tree append`` sorts them in+ byte order before it publishes.+- ``artifact`` keys in the order ``repository``, ``manifest_digest``,+ ``layer_digest``, ``payload_sha256``.++The target recomputes the digest from the parsed operation and refuses the+publication when one differs. The digest of each applied operation enters+the measurement register as a ``tree_op`` event, see+:doc:`eventlog`.++Target acceptance+~~~~~~~~~~~~~~~~~++``bpm tree sync`` applies a publication only when all of these hold:++#. The manifest has one document layer and one signature layer, each+ matching its descriptor's digest and size.+#. The signature verifies against the runtime image's initial+ certificate.+#. The document parses with the rules above, ``base.seq`` is 0, and every+ operation has a valid ``id``, ``op`` and digests and a correct+ ``operation_digest``.+#. ``tree_id`` equals the one the node recorded.+#. A publication other than the recorded one has a higher+ ``generation``. A direct successor that names a+ ``parent_manifest_digest`` names the recorded manifest.+#. ``head.seq`` is not below the node's last applied ``seq``.++For each new operation whose selector matches, the target then fetches the+artifact manifest by ``manifest_digest``, takes the layer with+``layer_digest`` and media type ``application/vnd.shirudo.upatch.v1``,+checks its digest and size, and refuses the ``.upatch`` unless its header+``payload_sha256`` equals ``artifact.payload_sha256``, its ``name`` equals+``id`` and it is an unload directive exactly when ``op`` is ``delete``.++Node records+~~~~~~~~~~~~++The target keeps these under ``/var/lib/shirudo/bpm/upatch-tree/``. They are+not published.++.. list-table::+ :header-rows: 1+ :widths: 22 78++ * - File+ - Content+ * - ``state.json``+ - JSON object with ``schema`` (1), ``tree_id``, ``generation`` and+ ``manifest_digest`` of the last applied publication, ``last_seq``,+ ``projection_root`` and ``projection_root_tpm``. ``last_seq`` also+ moves past operations whose selector does not match.+ * - ``tree-eventlog``+ - One JSON object per line and applied operation, with ``schema``+ (1), ``seq``, ``digest`` (the ``operation_digest``) and+ ``projection_root``. ``projection_root`` is the SHA-256 of the+ previous root followed by the raw operation digest, starting from+ 32 zero bytes.+ * - ``pending.json``+ - JSON object with ``schema`` (1), ``seq``, ``id`` and+ ``operation_digest`` while an operation is in progress.+ * - ``artifacts/<hex>.upatch``+ - Fetched artifacts, named by their layer digest.+ * - ``status/<id>``+ - ``skipped: module not loaded`` for an ``add`` whose attach target+ was missing.++:doc:`/reference/files` lists every file shirudo keeps.++Limits+------++.. list-table::+ :header-rows: 1+ :widths: 50 50++ * - Item+ - Limit+ * - Package file read by ``bpm push``+ - 256 MiB+ * - Archive members+ - 4096 members, 256 MiB of content+ * - Member name+ - fewer than 100 bytes, no ustar prefix+ * - ``build-environment.json`` and ``Beefile`` read by ``bpm push``+ and ``bpm tree append``+ - 4 MiB+ * - Index entries+ - 512+ * - Tree operations per publication+ - 512+ * - JSON document+ - 8 MiB+ * - Detached signature+ - 64 KiB (writer)++Related+-------++- :doc:`/upatches/publishing`+- :doc:`/operate/deliver-packages`+- :doc:`/reference/cli/bpm`+- :doc:`configuration` for repository and tree settingsdiff --git a/Documentation/reference/formats/configuration.rst b/Documentation/reference/formats/configuration.rstnew file mode 100644index 00000000..9be9e0fe--- /dev/null+++ b/Documentation/reference/formats/configuration.rst@@ -0,0 +1,506 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++Configuration+=============++Every file shirudo takes settings from, every key, and the rules each+reader applies. ``shirudo config`` prints the settings in effect, see+:doc:`/reference/cli/config`.++Files+-----++.. list-table::+ :header-rows: 1+ :widths: 26 34 40++ * - File+ - Location+ - Authenticated by+ * - Initrd bootstrap+ - ``/etc/shirudo/shirudo.conf`` inside the initrd+ - The signature of the UKI that carries the initrd, checked by the+ boot chain. shirudo does not verify it itself.+ * - Runtime bootstrap+ - ``etc/shirudo/shirudo.conf`` in the runtime image, read at+ ``/run/shirudo/runtime/etc/shirudo/shirudo.conf``+ - The runtime image's dm-verity root, pinned by+ ``runtime.root_hash`` in the initrd bootstrap+ * - Config settings+ - ``etc/shirudo/shirudo.conf`` in the config image, read through the+ image mounted at ``/run/shirudo/config``+ - The config image's signed dm-verity root+ * - Repository definitions, tree subscription, node labels, trusted+ and revoked keys+ - The config image, see `Config image`_+ - The config image's signed dm-verity root+ * - Host file+ - ``/etc/shirudo/shirudo.conf`` on the root file system+ - Nothing. Read on operator hosts. A target takes its settings from+ the bootstrap files and the config image.+ * - Unit environment files+ - ``/etc/shirudo/init.env``, ``/etc/shirudo/map-export.env``,+ ``/etc/shirudo/bpm/environment``+ - Nothing. See :doc:`/reference/environment`.++The two bootstrap files are different files with different required+keys. ``shirudo-gen-initrd --bootstrap-conf <file>`` embeds the initrd+bootstrap. ``shirudo-gen-runtime --bootstrap-conf <file>`` installs the+runtime bootstrap into the runtime image. See :doc:`/reference/cli/gen-tools`.++Bootstrap keys+--------------++.. list-table::+ :header-rows: 1+ :widths: 24 22 14 14 26++ * - Key+ - Value+ - Initrd bootstrap+ - Runtime bootstrap+ - Meaning+ * - ``runtime.image``+ - Absolute path prefix+ - Required+ - Refused+ - Prefix of the runtime image files, see `Image files`_+ * - ``runtime.root_hash``+ - 64 hexadecimal digits+ - Required+ - Refused+ - Expected dm-verity root hash of the runtime image+ * - ``config.image``+ - Absolute path prefix under ``/var/lib/shirudo/images/``+ - Allowed+ - Required+ - Config image selected at boot while+ ``/var/lib/shirudo/config-update`` holds no activation record.+ Once a record exists, its prefix is selected instead.+ * - ``config.verification_key``+ - Absolute path under ``/run/shirudo/runtime/``+ - Allowed+ - Required+ - DER certificate enrolled in the ``.dm-verity`` keyring to verify+ config signatures. ``shirudo-gen-runtime`` installs it as+ ``/run/shirudo/runtime/etc/shirudo/config-cert.der``.+ * - ``config.pcr``+ - Decimal integer, 0 to 15, not 9 or 11+ - Allowed+ - Required+ - PCR that config activation extends++The runtime bootstrap's ``config.*`` values are the ones in effect: the+root file system's run of ``init`` and every later command read only the+runtime bootstrap.++Bootstrap rules:++- A ``runtime.*`` key in the runtime bootstrap is refused with+ ``EINVAL``.+- A ``config.*`` or ``runtime.*`` key not in the table is refused with+ ``EINVAL``. A repeated ``runtime.image`` or ``runtime.root_hash`` is+ refused with ``EINVAL``.+- A ``config.verification_key`` outside ``/run/shirudo/runtime/`` is+ refused with ``EPERM``.+- A path is valid when it is absolute and contains no ``//``, ``/./`` or+ ``/../``, does not end in ``/..`` and is not ``/``.+- A non-blank line that is not a comment and has no ``=`` is refused+ with ``EINVAL``. A line longer than 4223 bytes is refused with+ ``E2BIG``.+- Every other key in a bootstrap file is a setting, read as in+ `Settings`_.++``init`` reports a refused bootstrap file with ``init: authenticated+image settings: <error>`` or, for the runtime bootstrap in the initrd,+``image: load runtime config: <error>``, and exits with status 1.+Every other command fails with ``shirudo: image state: <error>`` and exit+status 1.++Settings+--------++.. list-table::+ :header-rows: 1+ :widths: 26 26 14 34++ * - Key+ - Value+ - Default+ - Set in+ * - ``eventlog.max_bytes``+ - Decimal integer, ``0`` for no limit+ - ``0``+ - Config image+ * - ``tpm.owner_auth``+ - Literal password, or ``hex:<even number of hex digits>``, at most+ 256 bytes+ - Empty+ - Both bootstrap files+ * - ``tpm.tcti``+ - TCTI string, at most 255 bytes. ``device:<path>`` on a target+ - ``device:/dev/tpmrm0``+ - Both bootstrap files+ * - ``tls.classical_hosts``+ - Comma-separated exact DNS names, at most 1023 bytes+ - Empty+ - Runtime bootstrap on a target, host file on an operator host+ * - ``map_export.json_path``+ - Absolute path, or empty+ - Empty+ - Config image+ * - ``map_export.otel_endpoint``+ - ``http`` or ``https`` URL, at most 2047 bytes, or empty+ - Empty+ - Config image+ * - ``map_export.tenant_id``+ - 1 to 128 characters from ``A-Z``, ``a-z``, ``0-9``, ``.``,+ ``_``, ``-``, or empty+ - Empty+ - Config image+ * - ``map_export.otel_insecure``+ - ``true`` or ``false``+ - ``false``+ - Config image+ * - ``map_export.otel_retries``+ - Decimal integer, 0 to 10+ - ``3``+ - Config image+ * - ``map_export.s3_uri``+ - ``s3://<bucket>[/<prefix>]``, at most 2047 bytes, or empty+ - Empty+ - Config image+ * - ``map_export.log_record_max_bytes``+ - Decimal integer, 1 to 8388608+ - ``1048576``+ - Config image+ * - ``map_export.otlp_max_bytes``+ - Decimal integer, 1 to 8388608+ - ``4194304``+ - Config image++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Key+ - Effect+ * - ``eventlog.max_bytes``+ - ``upatch load``, ``upatch unload`` and the register binding of+ ``init`` refuse with ``eventlog_full`` when the eventlog's size+ plus 4096 bytes exceeds this value.+ * - ``tpm.owner_auth``+ - Owner hierarchy authorization for defining the NV index. Needed+ only when the TPM's owner password is set. The initrd copy is+ read while ``init`` creates the NV writer and the attestation key+ in the initrd, the runtime copy for every later TPM use.+ * - ``tpm.tcti``+ - TPM connection for tpm2-tss. With a config image active, a value+ that does not begin with ``device:`` is refused with ``EACCES``.+ Read from the same two files as ``tpm.owner_auth``.+ * - ``tls.classical_hosts``+ - HTTPS hosts that may negotiate ``X25519`` or ``secp256r1`` key+ exchange in addition to the hybrid ML-KEM groups. Every other+ host is held to ``X25519MLKEM768`` and ``SecP256r1MLKEM768``.+ Each host, redirect targets included, must be listed by its exact+ name, compared without case. IP addresses cannot be listed. A+ classical handshake is logged as a warning.+ * - ``map_export.json_path``+ - ``upatch map --all`` appends each decoded map as one JSON line to+ this file.+ * - ``map_export.otel_endpoint``+ - OTLP/HTTP base URL. ``/v1/logs`` or ``/v1/metrics`` is appended.+ ``status --otel`` and ``upatch map --all`` send to it. Without it+ and without ``--otel``, ``upatch map --all`` sends no OTLP. Plain+ ``http`` is accepted for ``localhost``, ``127.0.0.1`` and+ ``[::1]`` only, unless ``map_export.otel_insecure`` is ``true``.+ * - ``map_export.tenant_id``+ - Sent as the ``X-Tenant-ID`` header.+ * - ``map_export.otel_insecure``+ - ``true`` allows ``http`` to any host and turns off certificate and+ host name verification for ``https``.+ * - ``map_export.otel_retries``+ - Further attempts after a failed OTLP or S3 request.+ * - ``map_export.s3_uri``+ - Object store for a snapshot larger than+ ``map_export.otlp_max_bytes``. The OTLP endpoint receives a+ reference event instead. Requires ``map_export.otel_endpoint``.+ * - ``map_export.log_record_max_bytes``+ - Largest OTLP log record. Must not exceed+ ``map_export.otlp_max_bytes``.+ * - ``map_export.otlp_max_bytes``+ - Largest OTLP request body.++On a target, the effective settings combine the files as follows:++- ``tpm.owner_auth``, ``tpm.tcti`` and ``tls.classical_hosts`` come from+ the bootstrap. The config image cannot carry them.+- ``eventlog.max_bytes`` and ``map_export.*`` come from the config image.+ A value in a bootstrap file applies only while no config image is+ active, as for ``status`` during an activation it cannot verify.+- On a host without a config image, ``SHIRUDO_TPM_TCTI`` and+ ``SHIRUDO_TPM_OWNER_AUTH`` override the file. A target refuses both,+ see :doc:`/reference/environment`.++See :doc:`/reference/formats/otlp` for what the ``map_export.*``+destinations receive.++Syntax and validation+---------------------++All three files and the host file share one syntax:++- One ``key = value`` per line. Blanks around the key and the value are+ removed.+- A line whose first non-blank character is ``#`` is a comment.+- A later line sets a key again.+- A line without ``=`` is ignored, except in a bootstrap file and in the+ config image.++How each reader treats a bad value:++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Value+ - Result+ * - Unknown key+ - Warning ``config: unknown key '<key>' (ignored)``.+ * - Unknown ``map_export.*`` key, or a ``map_export.*`` value out of+ range+ - Warning. Map export is invalid: ``status --otel`` and+ ``upatch map --all`` exit with status 2, ``shirudo config`` with+ status 1.+ * - Unknown ``tls.*`` key, or an invalid ``tls.classical_hosts``+ - Warning. No host may use classical key exchange. ``shirudo+ config`` exits with status 1.+ * - Invalid ``eventlog.max_bytes``, ``tpm.owner_auth`` or+ ``tpm.tcti``+ - Warning. The value is ignored.+ * - Line longer than 4223 bytes in the host file+ - Warning. The line is ignored.+ * - Line containing a NUL byte+ - The file is refused with ``EINVAL``.++The config image's ``etc/shirudo/shirudo.conf`` is checked again when an+image is validated, before its root is extended into the config PCR. The+image is refused when:++- the file is missing;+- a line is longer than 1023 bytes or contains a NUL byte (``E2BIG``);+- a non-blank line that is not a comment has no ``=`` (``EINVAL``);+- a key is neither ``eventlog.max_bytes`` nor ``map_export.*``+ (``EPERM``);+- ``eventlog.max_bytes`` is not a decimal integer (``EINVAL``);+- the map export settings are invalid (``EINVAL``).++Ownership and mode+~~~~~~~~~~~~~~~~~~++A settings, repository or tree file read from a path under+``/etc/shirudo`` or ``/var/lib/shirudo`` is refused with ``EPERM`` unless:++- it is a regular file owned by root or by the effective user;+- it is not writable by group or others;+- every directory above it is owned by root or the effective user and is+ not writable by group or others, or is root's and sticky.++A file that sets ``tpm.owner_auth`` must also not be readable by group or+others, mode ``0600`` or stricter. This applies to the initrd bootstrap+and the host file. Files read from the runtime and config images are+checked by their dm-verity roots instead. ``shirudo-gen-runtime``+installs the runtime bootstrap with mode ``0644``.++Config image+------------++A config image is a directory tree of regular files and directories on+one file system, at most 65536 entries and 32 levels deep. Symbolic+links, devices, FIFOs and sockets are refused with ``EPERM``.++.. list-table::+ :header-rows: 1+ :widths: 38 62++ * - Path in the image+ - Content+ * - ``etc/shirudo/shirudo.conf``+ - Required. ``eventlog.max_bytes`` and ``map_export.*`` only.+ * - ``etc/shirudo/bpm/registries.d/<name>.conf``+ - One repository definition each, see `Repository definition`_.+ * - ``etc/shirudo/bpm/keys/<file>``+ - Repository certificates named by ``key_file``.+ * - ``etc/shirudo/bpm/upatch-tree.conf``+ - The upatch tree subscription, see `Tree subscription`_.+ * - ``etc/shirudo/node.labels``+ - The labels tree selectors match, see `Node labels`_.+ * - ``keys/trusted/<name>.der``+ - Further BPF signing certificates. Each needs a+ ``keys/trusted/<name>.vouch`` from an already trusted key.+ * - ``keys/revoked/<fingerprint>.der``+ - A revoked certificate. ``<fingerprint>`` is the lowercase hex+ SHA-256 of its DER ``SubjectPublicKeyInfo``.++See :doc:`/operate/keys` for the trusted and revoked sets and+:doc:`/internals/config-images` for activation.++Runtime image+-------------++.. list-table::+ :header-rows: 1+ :widths: 38 62++ * - Path in the image+ - Content+ * - ``usr/bin/shirudo``+ - The target binary (``--binary``).+ * - ``usr/bin/<name>``+ - Further executables (``--extra-binary``).+ * - ``etc/shirudo/shirudo.conf``+ - The runtime bootstrap (``--bootstrap-conf``).+ * - ``keys/cert.der``+ - The initial BPF signing certificate (``--cert``), always in the+ trusted set.+ * - ``etc/shirudo/config-cert.der``+ - The config verification certificate (``--config-cert``).+ * - The ELF interpreter and libraries+ - Copied at their own paths for a dynamic binary.++shirudo's part of the initrd+----------------------------++.. list-table::+ :header-rows: 1+ :widths: 38 62++ * - Path in the initrd+ - Content+ * - ``/etc/shirudo/shirudo.conf``+ - The initrd bootstrap. The dracut module's install step fails+ when it cannot read the file.+ * - ``/etc/shirudo/keys/cert.der``+ - The primary certificate. The pre-flight check and the+ ``ConditionPathExists=`` of ``shirudo-initrd.service`` use it.+ The keys enrolled at boot come from the runtime and config images.+ * - ``/etc/shirudo/keys/trusted/*.der``, ``*.vouch``+ - Copied from ``trusted/`` beside the primary certificate.+ * - The shirudo binary+ - At its path on the root file system.++Image files+-----------++``runtime.image`` and ``config.image`` name a path prefix. The files are+the prefix with a suffix:++.. list-table::+ :header-rows: 1+ :widths: 20 20 20 40++ * - Suffix+ - Runtime image+ - Config image+ - Content+ * - ``.img``+ - Required+ - Required+ - ext4 file system+ * - ``.verity``+ - Required+ - Required+ - dm-verity superblock and hash tree+ * - ``.roothash``+ - Required+ - Required+ - Root hash as exactly 64 lowercase hex digits, no newline+ * - ``.p7s``+ - Not read+ - Required+ - Detached CMS signature over the 64 root hash bytes++Repository definition+---------------------++``etc/shirudo/bpm/registries.d/<name>.conf`` in the config image, or the+same path under ``/`` on a host without one. ``<name>`` is the+repository name: 1 to 127 characters from ``A-Z``, ``a-z``, ``0-9``,+``.``, ``_``, ``-``, not starting with ``.``.++.. list-table::+ :header-rows: 1+ :widths: 18 82++ * - Key+ - Value+ * - ``endpoint``+ - Required. ``oci://<host>[:<port>]``, no path, ``?``, ``#`` or+ ``@``.+ * - ``key_file``+ - Required. DER certificate that verifies the repository's signed+ index. With a config image, ``/etc/shirudo/bpm/keys/<file>``+ names the image's ``etc/shirudo/bpm/keys/<file>``, a relative path+ names a file under the image root, and any other absolute path or+ a path containing ``..`` is refused with ``EINVAL``.++Lines without ``=`` and other keys are ignored. Leading blanks of a value+are removed, trailing blanks are kept.++Tree subscription+-----------------++``etc/shirudo/bpm/upatch-tree.conf`` in the config image, or+``/etc/shirudo/bpm/upatch-tree.conf`` on a host without one. Without the+file, ``bpm tree sync`` does nothing.++.. list-table::+ :header-rows: 1+ :widths: 18 82++ * - Key+ - Value+ * - ``endpoint``+ - Required. ``oci://<host>[:<port>]/<repository>``. The repository+ may not contain ``..``, ``//`` or ``:``.+ * - ``reference``+ - Required. Tag or digest of the tree publication, without ``/``,+ ``?``, ``#`` or ``..``.++Either value may be enclosed in double quotes. An opening quote without+a closing one is refused with ``EINVAL``. Lines without ``=`` and other+keys are ignored. See :doc:`/reference/formats/bpm-formats` for the+publication.++Node labels+-----------++``etc/shirudo/node.labels`` in the config image, or+``/etc/shirudo/node.labels`` on a host without one.++- One ``key=value`` per line. Lines starting with ``#`` and lines+ without ``=`` are ignored.+- A line longer than 511 bytes, more than 64 labels, or a key or value+ longer than 255 bytes is an error for the tree operation being+ matched.+- Blanks after the ``=`` and at the end of the line are removed. Blanks+ between the key and the ``=`` are kept as part of the key, so write+ ``env=prod``, not ``env = prod``.+- Without the file, a tree operation whose selector names a label does+ not match.++Related+-------++- :doc:`/reference/environment` for the variables that override or+ complement these settings.+- :doc:`/reference/files` for every path shirudo reads and writes.+- :doc:`/operate/boot-integration` for building the bootstrap files and+ images.+- :doc:`/operate/telemetry` for the export destinations.+- :doc:`/operate/deliver-packages` for repositories and the upatch tree.diff --git a/Documentation/reference/formats/eventlog.rst b/Documentation/reference/formats/eventlog.rstnew file mode 100644index 00000000..83c01615--- /dev/null+++ b/Documentation/reference/formats/eventlog.rst@@ -0,0 +1,365 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators, security reviewers++Eventlog events+===============++The eventlog records every extension of the measurement register, one+JSON object per line. A replay of this boot's records reproduces the+register value. :doc:`/internals/measurement-register` explains the+register. This page gives the files, the record format, the event kinds+and their digests, the replay rule and the limits.++Files+-----++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Path+ - Contents+ * - ``/var/lib/shirudo/eventlog``+ - The eventlog. Mode ``0600``. It inherits the seal label of+ ``/var/lib/shirudo``, so only tasks with shirudo's runtime+ authority may open it for writing, rename, unlink or change it.+ shirudo appends to it and never rotates or truncates it.+ * - ``/run/shirudo/eventlog.pending``+ - The ``init`` record that ``shirudo init`` writes while it runs+ from the initrd. Readers treat it as the end of the eventlog+ until it is adopted.+ * - ``/var/lib/shirudo/eventlog.lock``+ - Lock file. upatch loads and unloads, key revocations and tree+ operations hold it from the register extend to the matching+ append, so the register and the log advance in the same order.+ Adopting the pending record also takes it.++``SHIRUDO_EVENTLOG_PATH`` and ``SHIRUDO_EVENTLOG_PENDING_PATH`` override+the two paths for host tests. A target running from a runtime image+refuses both, see :doc:`/reference/environment`.++The upatch tree keeps its own projection log in+``/var/lib/shirudo/bpm/upatch-tree/tree-eventlog``, described in+:doc:`bpm-formats`. Config image activations extend the config PCR+instead of the register and keep their records under+``/var/lib/shirudo/config-update``, see :doc:`/internals/config-images`.+Neither is part of the eventlog.++Record format+-------------++- One compact JSON object per line, terminated by ``\n``.+- A command appends a record only after the register extend succeeded,+ then calls ``fsync``. An append that fails part-way is truncated back+ to the previous size.+- Digests are SHA-256, written as 64 lowercase hex digits.++Every record carries these fields:++.. list-table::+ :header-rows: 1+ :widths: 22 14 64++ * - Field+ - Type+ - Value+ * - ``schema``+ - integer+ - ``2``+ * - ``ts``+ - string+ - Time of the append, ISO 8601 UTC, for example+ ``2026-10-29T16:21:19Z``.+ * - ``nv_index``+ - string+ - The register's NV index, ``0x01818E00``.+ * - ``alg``+ - string+ - ``sha256``+ * - ``digest``+ - string+ - The event, 64 hex digits: the value extended into the register.+ * - ``type``+ - string+ - ``init``, ``upatch_load``, ``upatch_unload``, ``key_revoke`` or+ ``tree_op``.+ * - ``boot_id``+ - string+ - ``/proc/sys/kernel/random/boot_id`` at the append.++Event kinds+-----------++.. list-table::+ :header-rows: 1+ :widths: 18 40 42++ * - ``type``+ - Written by+ - Additional fields+ * - ``init``+ - ``shirudo init``, once per TPM reset, after boot restore. A+ re-run of ``init`` in the same boot writes nothing.+ - See `Fields of an init record`_.+ * - ``upatch_load``+ - ``shirudo upatch load``, after the load, before it reports+ success.+ - ``upatch``: object with ``name`` and ``payload_sha256``.+ * - ``upatch_unload``+ - ``shirudo upatch unload``, before the detach. A live config+ activation that revokes a key writes one per loaded upatch the+ key signed.+ - ``upatch``: object with ``name`` and ``payload_sha256``.+ ``reason``: ``key_revoke`` for an unload caused by a key+ revocation, absent otherwise.+ * - ``key_revoke``+ - ``shirudo image update``, when the activated config revokes a+ certificate that is in the ``.bpf`` keyring. A revocation+ applied at boot is covered by the ``init`` event instead.+ - ``key``: object with ``fingerprint`` (SHA-256 of the public key)+ and ``cert_sha256`` (SHA-256 of the certificate DER).+ * - ``tree_op``+ - ``shirudo bpm tree sync``, once per applied tree operation.+ - ``tree``: object with ``seq`` (integer), ``op`` (``add`` or+ ``delete``), ``id`` (the upatch name) and ``operation_digest``+ (``sha256:<hex>``). ``chain``: the register value after the+ event.++Fields of an init record+~~~~~~~~~~~~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 24 14 62++ * - Field+ - Type+ - Value+ * - ``tpm_reset_count``+ - integer+ - The TPM's reset count when the register was bound.+ * - ``cert_sha256``+ - string+ - Digest of the enrolled certificate set: the SHA-256 of the+ certificate DER when one certificate is enrolled, else the+ SHA-256 of the concatenated DER digests sorted bytewise.+ * - ``certs``+ - array of string+ - SHA-256 of each enrolled certificate's DER.+ * - ``set_digest``+ - string+ - SHA-256 of the restored set listing (see `Event digests`_).+ * - ``tree_root``+ - string+ - The upatch tree's ``projection_root`` at boot, or 64 zeros+ without tree state.+ * - ``set``+ - array of object+ - The upatches boot restore applied or found loaded, each with+ ``name`` and ``payload_sha256``.+ * - ``pcr``+ - integer+ - ``9``, the PCR that anchors the register.+ * - ``pcr_before``+ - string+ - PCR 9 before the binding.+ * - ``phase_pcr``+ - integer+ - ``11``, the boot phase PCR.+ * - ``phase_before``+ - string+ - PCR 11 at the binding.+ * - ``bound_in``+ - string+ - ``initrd`` when ``init`` ran from the initrd, ``root`` otherwise.+ * - ``nv_name``+ - string+ - The register's TPM name after its first write, 68 hex digits+ (``000b`` and a SHA-256).+ * - ``nv_writer_public``+ - string+ - The NV writer key's RSA modulus, 384 bytes big-endian, 768 hex+ digits. The exponent is 65537 and not stored.+ * - ``anchor``+ - string+ - ``nvpcr-init:shirudo:0x1818e00:<nv_name>``+ * - ``anchor_digest``+ - string+ - SHA-256 of the ``anchor`` string, extended into PCR 9.+ * - ``chain``+ - string+ - The register value after the event.++Event digests+-------------++Each digest is a SHA-256 over a tag, its terminating NUL byte and the+event's fields. Hex fields enter the hash as their 32 decoded bytes.+``attest verify`` recomputes every non-``init`` digest from the+record's own fields and fails a record whose digest does not derive+from them.++.. list-table::+ :header-rows: 1+ :widths: 18 82++ * - ``type``+ - ``digest``+ * - ``init``+ - ``SHA256("shirudo-init\0" || cert_sha256 || set_digest ||+ tree_root)``+ * - ``upatch_load``+ - ``SHA256("shirudo-upatch\0" || payload_sha256 || name)``+ * - ``upatch_unload``+ - ``SHA256("shirudo-unload\0" || payload_sha256 || name)``+ * - ``key_revoke``+ - ``SHA256("shirudo-key-revoke\0" || cert_sha256)``+ * - ``tree_op``+ - ``SHA256("shirudo-tree\0" || seq || operation_digest)``++- ``name`` is the upatch name's bytes without a terminating NUL, at most+ 256 bytes.+- ``seq`` is the tree sequence number as an 8-byte big-endian integer.+- ``set_digest`` is the SHA-256 of one line ``<payload_sha256> <name>\n``+ per member of ``set``, sorted by name, concatenated. An empty set+ gives the SHA-256 of the empty string,+ ``e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855``.+- The register starts at 32 zero bytes after every TPM reset. Each+ event sets it to ``SHA256(register || digest)``, the TPM's NV extend.++Replay+------++``shirudo status``, ``shirudo attest`` and the measuring commands select+this boot's records the same way:++- They read ``/var/lib/shirudo/eventlog`` followed by+ ``/run/shirudo/eventlog.pending``.+- They parse every line. One line that is not valid JSON fails the+ replay, whatever boot it belongs to.+- They skip lines without a ``boot_id`` or with another boot's+ ``boot_id``.+- They start at this boot's first ``init`` record. Every ``init``+ record restarts the fold at 32 zero bytes, so the replay covers the+ last ``init`` record and the records after it.+- A boot without an ``init`` record has no replay.++``status`` compares the replay with the live register (condition+``ChainIntact``, field ``tpm.chain_matches_eventlog`` in+:doc:`status-json`). It also reports a mismatch when the register's+name differs from the recorded ``nv_name``, when the recorded PCR values+and writer key do not give that name, and when two ``init`` records+name the same TPM reset count. ``shirudo attest`` puts the selected+records, verbatim, in the evidence's ``eventlog`` array, see+:doc:`/operate/attest`.++Pending record+--------------++``shirudo init`` run from the initrd writes its ``init`` record to+``/run/shirudo/eventlog.pending``. ``/run`` survives the switch to the+root file system. The ``init`` run of ``shirudo.service`` on the root+file system adopts it: it appends each pending line that this boot's+part of the eventlog does not already hold, then removes the pending+file. Any other append adopts a pending record first.++Size limits+-----------++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Limit+ - Behavior+ * - ``eventlog.max_bytes``+ - Signed config setting, default ``0`` (unlimited), see+ :doc:`configuration`. ``init``, ``upatch load`` and+ ``upatch unload`` refuse before they change anything when the+ eventlog size plus 4096 bytes exceeds it. ``upatch load`` and+ ``upatch unload`` report category ``eventlog_full`` (``ENOSPC``,+ phase ``pre_flight``). ``init`` fails without binding the+ register. ``tree_op``, ``key_revoke`` and revocation ``upatch_unload``+ records are appended without this check.+ * - Reader cap, 8 MiB+ - Readers load at most 8388608 bytes: the eventlog alone, and the+ eventlog and the pending record together. Above that the replay+ fails. ``status`` then reports ``ChainIntact`` ``ALERT`` and the+ verdict ``tampered``, ``upatch load`` and ``upatch unload`` fail+ with ``tpm_error``, and ``init`` refuses to bind the register.++The eventlog grows across boots and shirudo never shortens it. Keep+``eventlog.max_bytes`` at or below 8388608 so that a refusal with+``eventlog_full`` comes before the reader cap.++Example+-------++``shirudo status --include-eventlog`` on a test target after one boot,+one load and one unload prints the eventlog as a table (excerpt):++.. code-block:: text++ Eventlog (audit trail):+ TIME TYPE DIGEST DETAIL+ 2026-10-29T16:17:38Z init cb206abf8e51 set_digest=e3b0c44298fc..+ 2026-10-29T16:21:19Z upatch_load d979b373d4e5 shirudo-test-basic payload=8aee7072a1a1..+ 2026-10-29T16:21:20Z upatch_unload 26dae981e9bb shirudo-test-basic payload=8aee7072a1a1..++The ``upatch_load`` record of that eventlog, one line:++.. code-block:: json++ {"schema":2,"ts":"2026-10-29T16:21:19Z","nv_index":"0x01818E00","alg":"sha256","digest":"d979b373d4e5c59775c06c3bee5fd868d9d033db5403b290b61b512d4a293597","type":"upatch_load","boot_id":"743acb26-a7ee-405d-b45a-600484470644","upatch":{"name":"shirudo-test-basic","payload_sha256":"8aee7072a1a15e4dddc93ad6b253a0e2e70ad6cdf767442aa8a1c1997bc3069f"}}++Its ``init`` record, indented here, with the 768 hex digits of+``nv_writer_public`` shortened:++.. code-block:: json++ {+ "schema": 2,+ "ts": "2026-10-29T16:17:38Z",+ "nv_index": "0x01818E00",+ "alg": "sha256",+ "digest": "cb206abf8e514bc714fc69f372d464d2c7512f1489431aed2319551c5ed34b9a",+ "type": "init",+ "boot_id": "743acb26-a7ee-405d-b45a-600484470644",+ "tpm_reset_count": 1,+ "cert_sha256": "51a99fe89f5069a4d67131da3e1556dedbac7b2a1ec6702c51ca170c45d01d65",+ "certs": [+ "3702e8ffe817ade6151eea338194649cc3a5be1e0b940e462a1a75e52f7095d0",+ "d95db97ff4658b96b8b538afef41a25ca9f7a2c4d0abffdb26cbac7b0ba294b9"+ ],+ "set_digest": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",+ "tree_root": "0000000000000000000000000000000000000000000000000000000000000000",+ "set": [],+ "pcr": 9,+ "pcr_before": "0000000000000000000000000000000000000000000000000000000000000000",+ "phase_pcr": 11,+ "phase_before": "0000000000000000000000000000000000000000000000000000000000000000",+ "bound_in": "initrd",+ "nv_name": "000be3a552e2219550d2597ab96f3fffdeec0d01ce27cde858e0858ab0cdaba6c045",+ "nv_writer_public": "b4d7434fadbc7cb1a0d6...e07197",+ "anchor": "nvpcr-init:shirudo:0x1818e00:000be3a552e2219550d2597ab96f3fffdeec0d01ce27cde858e0858ab0cdaba6c045",+ "anchor_digest": "6912e5d20117d2eb4d2e55429bf666b1bb24ea2cd3882468411b1192f3940d50",+ "chain": "d1bdb80f7c0cfc1560f0a5a0b974d282bfd05fc95852b7649d59a054b450aa51"+ }++The test VM boots without a measured UKI, so PCR 9 and PCR 11 were zero+when ``init`` bound the register. Folding the three digests from 32+zero bytes gives+``e57e1428ab398e758b63f8eda52bac87b5d85c1368c2d8d786ed446448e46239``,+the register value ``status`` showed after the unload.++Related+-------++- :doc:`/internals/measurement-register`+- :doc:`/operate/attest`+- :doc:`status-json`+- :doc:`/reference/cli/status`diff --git a/Documentation/reference/formats/index.rst b/Documentation/reference/formats/index.rstnew file mode 100644index 00000000..f0893110--- /dev/null+++ b/Documentation/reference/formats/index.rst@@ -0,0 +1,21 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++Formats and settings+====================++The formats shirudo reads and writes: the signed ``.upatch`` container,+packages, signed indexes and upatch trees, the configuration files and+their keys, the eventlog, the ``shirudo status --json`` document and the+OTLP documents shirudo exports.++.. toctree::+ :titlesonly:++ upatch-format+ bpm-formats+ configuration+ eventlog+ status-json+ otlpdiff --git a/Documentation/reference/formats/otlp.rst b/Documentation/reference/formats/otlp.rstnew file mode 100644index 00000000..a24b1329--- /dev/null+++ b/Documentation/reference/formats/otlp.rst@@ -0,0 +1,496 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++OTLP documents+==============++shirudo sends OpenTelemetry data as OTLP/HTTP JSON. Each document is+one ``POST`` from a one-shot command:++.. list-table::+ :header-rows: 1+ :widths: 34 26 40++ * - Document+ - Sent by+ - Signal+ * - Status keepalive+ - ``shirudo status --otel``+ - One log record+ * - Map snapshot+ - ``shirudo upatch map --otel``, ``shirudo upatch map --all``+ - One log record or the decoder's metrics, per map+ * - Map snapshot reference+ - The same, when a snapshot goes to S3+ - One log record++The timers ``shirudo-keepalive.timer`` and ``shirudo-map-export.timer``+run these commands, see :doc:`/reference/systemd-units`. Setting up an+export is in :doc:`/operate/telemetry`. Decoders are in+:doc:`/upatches/decoders`.++Transport+---------++.. list-table::+ :header-rows: 1+ :widths: 28 72++ * - Property+ - Value+ * - Protocol+ - OTLP/HTTP with JSON bodies. ``OTEL_EXPORTER_OTLP_PROTOCOL`` may+ only be ``http/json``.+ * - Paths+ - ``v1/logs`` for logs, ``v1/metrics`` for metrics, appended to a+ base URL.+ * - Headers+ - ``Content-Type: application/json``,+ ``Content-Encoding: gzip`` when compression is on,+ ``User-Agent: Shirudo OTel-OTLP-Exporter-C/1``, the configured+ headers and ``X-Tenant-ID``.+ * - Compression+ - ``none`` (default) or ``gzip``.+ * - TLS+ - TLS 1.3 only, hybrid ML-KEM key exchange+ (``X25519MLKEM768``, ``SecP256r1MLKEM768``). A host listed in+ ``tls.classical_hosts`` may also use ``X25519`` and+ ``secp256r1``, see :doc:`configuration`.+ * - Cleartext+ - ``http://`` only to ``localhost``, ``127.0.0.1`` or ``[::1]``,+ unless insecure mode is on. Other schemes are refused.+ * - Insecure mode+ - ``--otel-insecure`` or ``map_export.otel_insecure = true``+ allows ``http://`` to any host and turns off certificate and+ host name verification for ``https://``. shirudo prints a+ warning for each export.+ * - Credentials in the URL+ - Refused.+ * - Timeout+ - Per attempt, ``OTEL_EXPORTER_OTLP_TIMEOUT`` in milliseconds, 1+ to 120000, default 10000.+ * - Success+ - HTTP ``200`` only, unless the response reports+ ``partialSuccess`` with ``rejectedLogRecords`` or+ ``rejectedDataPoints`` above zero.+ * - Retries+ - ``map_export.otel_retries`` or ``--otel-retries``, 0 to 10,+ default 3, after the first attempt. Retried: HTTP ``429``,+ ``502``, ``503``, ``504``, and failures to resolve, connect,+ send or receive, and timeouts. Any other response fails at+ once.+ * - Backoff+ - The response's ``Retry-After``, at most 30 seconds, else a+ random delay up to 250 ms doubled per retry, at most 4 s.+ * - Response size+ - A response body over 65535 bytes fails the export.+ * - Request size+ - ``map_export.otlp_max_bytes``, default 4194304, at most+ 8388608, before compression. A larger document fails with+ ``E2BIG``.++Endpoint+--------++shirudo picks the first that is set:++.. list-table::+ :header-rows: 1+ :widths: 46 54++ * - Source+ - URL used+ * - ``--otel-endpoint=<url>`` (``upatch map`` only)+ - ``<url>`` plus the signal path+ * - ``map_export.otel_endpoint`` (``status --otel`` and+ ``upatch map --all``)+ - The value plus the signal path+ * - ``OTEL_EXPORTER_OTLP_LOGS_ENDPOINT``,+ ``OTEL_EXPORTER_OTLP_METRICS_ENDPOINT``+ - The value as given+ * - ``OTEL_EXPORTER_OTLP_ENDPOINT``+ - The value plus the signal path+ * - None (``upatch map`` only)+ - ``http://localhost:4318`` plus the signal path++The signal path goes before any ``?`` or ``#`` and gets a ``/`` when+the base does not end in one. An empty variable counts as unset.+``status --otel`` sends no keepalive without one of the first four+sources. ``upatch map`` reads the ``map_export.*`` settings only with+``--all``. While a config activation is pending or cannot be verified,+the config image's ``map_export.*`` settings are not in effect and only+the environment can name the endpoint.++Environment+-----------++For each ``OTEL_EXPORTER_OTLP_<setting>`` below, the signal variable+``OTEL_EXPORTER_OTLP_LOGS_<setting>`` or+``OTEL_EXPORTER_OTLP_METRICS_<setting>`` takes precedence. The systemd+services read them from ``/etc/shirudo/map-export.env``.++.. list-table::+ :header-rows: 1+ :widths: 44 56++ * - Variable+ - Value+ * - ``OTEL_EXPORTER_OTLP_ENDPOINT``+ - Base URL, see `Endpoint`_.+ * - ``OTEL_EXPORTER_OTLP_PROTOCOL``+ - ``http/json``+ * - ``OTEL_EXPORTER_OTLP_COMPRESSION``+ - ``none`` or ``gzip``+ * - ``OTEL_EXPORTER_OTLP_HEADERS``+ - ``<name>=<value>[,<name>=<value>...]``, at most 16384 bytes.+ Values are percent-decoded. Refused: a name that is empty or+ contains ``:``, CR or LF, a value with CR or LF, and the names+ ``Content-Type``, ``Content-Encoding``, ``Content-Length``,+ ``Host`` and ``User-Agent``. One ``X-Tenant-ID`` is allowed and+ must be a valid tenant id. A tenant id from the command line or+ the config replaces it.+ * - ``OTEL_EXPORTER_OTLP_CERTIFICATE``+ - CA bundle for the collector's certificate.+ * - ``OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE``,+ ``OTEL_EXPORTER_OTLP_CLIENT_KEY``+ - Client certificate and key for mutual TLS. Both or neither.+ * - ``OTEL_EXPORTER_OTLP_TIMEOUT``+ - Milliseconds, 1 to 120000.++A tenant id, from ``--tenant-id=<id>`` or ``map_export.tenant_id``, is 1+to 128 characters from ``A-Z``, ``a-z``, ``0-9``, ``.``, ``_`` and+``-``. shirudo sends it as ``X-Tenant-ID``.++Resource and scope+------------------++Every document has one resource and one scope.++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Field+ - Value+ * - Resource attribute ``service.name``+ - ``shirudo``+ * - Resource attribute ``service.version``+ - The version string without the extra version and release name+ that ``shirudo version`` adds, for example ``58d3fa7`` where+ ``shirudo version`` prints ``shirudo (58d3fa7-rc0, ...)``.+ * - Resource attribute ``host.name``+ - The host name, or ``unknown``.+ * - Scope ``name``+ - ``shirudo.keepalive`` for the keepalive,+ ``shirudo.upatch.maps`` for map documents.+ * - Scope ``version``+ - Same as ``service.version``.++Attribute values follow the OTLP JSON encoding: ``stringValue``,+``intValue`` as a decimal string, ``boolValue``.++Status keepalive+----------------++One log record in ``resourceLogs[0].scopeLogs[0].logRecords``:++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Field+ - Value+ * - ``timeUnixNano``, ``observedTimeUnixNano``+ - Wall clock when shirudo builds the document, nanoseconds since+ the epoch, decimal string.+ * - ``severityNumber``, ``severityText``+ - ``9`` ``INFO`` for ``ok``. ``13`` ``WARN`` for ``degraded``,+ ``init-pending`` and ``reboot-pending``. ``17`` ``ERROR`` for+ every other verdict, ``tampered`` and ``lsm-off`` included.+ * - ``eventName``+ - ``shirudo.keepalive``+ * - ``body``+ - The :doc:`status-json` document as an OTLP value: objects as+ ``kvlistValue``, arrays as ``arrayValue``, strings as+ ``stringValue``, integers as ``intValue``, other numbers as+ ``doubleValue``, booleans as ``boolValue``, ``null`` as an empty+ value. The timer adds ``--include-system``.+ * - Attribute ``shirudo.status``+ - The verdict.+ * - Attribute ``shirudo.version_id``+ - ``SHIRUDO_VERSION_ID`` of the binary.+ * - Attribute ``shirudo.tamper_attempts``+ - ``tamper_attempts.total``. Absent when the counters cannot be+ read.++The keepalive uses ``map_export.otel_endpoint``,+``map_export.tenant_id``, ``map_export.otel_insecure``,+``map_export.otel_retries`` and ``map_export.otlp_max_bytes``.+``status --otel`` exits ``1`` when the export fails and ``2`` when the+``map_export.*`` settings are invalid.++Map snapshot log+----------------++One log record per map:++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Field+ - Value+ * - ``timeUnixNano``, ``observedTimeUnixNano``+ - Wall clock when shirudo builds the document, nanoseconds since+ the epoch, decimal string.+ * - ``severityNumber``, ``severityText``+ - ``9``, ``INFO``+ * - ``eventName``+ - ``shirudo.bpf.map.snapshot``+ * - ``body``+ - The value the map's decoder returns, as an OTLP value. Without a+ decoder, a ``kvlistValue`` of the map's contents, see+ `Undecoded body`_.+ * - Attribute ``shirudo.upatch.name``+ - The upatch name.+ * - Attribute ``shirudo.upatch.location``+ - The upatch's attach point.+ * - Attribute ``shirudo.map.name``+ - The map name.+ * - Attribute ``shirudo.map.type``+ - The map type name.+ * - Attribute ``shirudo.map.max_entries``+ - Integer.+ * - Attribute ``shirudo.map.n_entries``+ - Integer, entries read.+ * - Attribute ``shirudo.map.n_cpus``+ - Integer.+ * - Attribute ``shirudo.map.serialized``+ - Boolean, the map was read through its serializer.+ * - Attribute ``shirudo.map.truncated``+ - Boolean, the read stopped before the last entry.++A decoded body larger than ``map_export.log_record_max_bytes`` (default+1048576, at most ``map_export.otlp_max_bytes``) fails with ``E2BIG``.++Undecoded body+~~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Key+ - Value+ * - ``name``, ``type``, ``max_entries``, ``n_entries``+ - The map.+ * - ``n_cpus``+ - Per-CPU maps only.+ * - ``serialized``+ - Boolean.+ * - ``serialized_pages``, ``serialized_bytes``, ``pages``+ - Serializer-backed maps. Each page has ``page_index``,+ ``cursor``, ``next_cursor``, ``done``, ``flags``, ``chunks``,+ ``bytes`` and ``data_hex``.+ * - ``skipped``+ - The reason, for a map type shirudo cannot read generically.+ * - ``truncated``, ``n_truncated_at``+ - Other maps. ``n_truncated_at`` only when truncated.+ * - ``btf``+ - ``key_type``, ``value_type``, and ``key_type_def`` and+ ``value_type_def`` when known.+ * - ``entries``+ - Each with ``key`` and ``value``, or for per-CPU maps ``key``,+ ``values_per_cpu`` and ``sum``, formatted from BTF.++Map metrics+-----------++A decoder that declares the metric signal returns a list of OTLP+``Metric`` objects. shirudo sends them as+``resourceMetrics[0].scopeMetrics[0].metrics`` under the resource and+scope above and adds no attributes.++Signal selection+~~~~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Map+ - Export+ * - Has a decoder+ - The signal the decoder declares, log or metric.+ * - No decoder, unsigned per-CPU integer value+ - Classified as a metric. Metrics come only from decoders, so the+ export fails with ``ENODATA``.+ * - No decoder, any other map+ - Log record with the undecoded body.++For an undecoded map ``upatch map`` prints the choice on standard+error as ``otel: selected <signal> for <type> map <name>: <reason>``.++S3 snapshots+------------++When a decoded map's document fails with ``E2BIG`` and an S3 URI is+set (``--s3-uri=<uri>`` or ``map_export.s3_uri``), shirudo uploads the+snapshot to S3 and sends a reference log record instead. Undecoded,+skipped and truncated maps are not uploaded.+``map_export.s3_uri`` requires ``map_export.otel_endpoint``.++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Property+ - Value+ * - URI+ - ``s3://<bucket>[/<prefix>]``. Bucket: 3 to 63 characters from+ ``a-z``, ``0-9``, ``.`` and ``-``, starting and ending with a+ letter or digit. Prefix: at most 512 bytes, no control+ characters, ``?``, ``#``, ``.`` or ``..`` segments.+ * - Object+ - The decoder's JSON output, gzip-compressed, at most 64 MiB+ before compression.+ * - Key+ - ``[<prefix>/]<host>/<upatch>/<map>/<sha256>.json.gz``.+ ``<host>`` is the host name with every character other than+ ``A-Z``, ``a-z``, ``0-9``, ``-``, ``_`` and ``.`` replaced by+ ``_``. ``<sha256>`` is the digest of the compressed object.+ * - URL+ - With ``AWS_ENDPOINT_URL_S3``: ``<endpoint>/<bucket>/<key>``.+ Else ``https://<bucket>.s3.<region>.amazonaws.com/<key>``, or+ ``https://s3.<region>.amazonaws.com/<bucket>/<key>`` for a+ bucket name with a dot.+ * - Request+ - ``PUT`` signed with AWS SigV4, with ``If-None-Match: *``,+ ``Cache-Control: immutable``, ``x-amz-content-sha256``,+ ``x-amz-checksum-sha256``, ``x-amz-meta-shirudo-schema: 1``,+ ``x-amz-meta-shirudo-upatch`` and ``x-amz-meta-shirudo-map``.+ ``412`` counts as already uploaded.+ * - Timeout and retries+ - 10 seconds per attempt. Retries as for OTLP, also on ``408``,+ ``409`` and ``500``.+ * - Cleartext+ - As for OTLP, for ``AWS_ENDPOINT_URL_S3``. Insecure mode also+ turns off certificate verification for the AWS endpoints.++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Variable+ - Value+ * - ``AWS_ACCESS_KEY_ID``, ``AWS_SECRET_ACCESS_KEY``+ - Required. Missing credentials fail with ``EACCES``.+ * - ``AWS_SESSION_TOKEN``+ - Sent as ``x-amz-security-token``.+ * - ``AWS_REGION``, ``AWS_DEFAULT_REGION``+ - Region, in this order, default ``us-east-1``.+ * - ``AWS_ENDPOINT_URL_S3``+ - S3-compatible endpoint, path-style.+ * - ``AWS_CA_BUNDLE``+ - CA bundle for the S3 endpoint.++The reference log record goes to the logs endpoint, whatever signal+the decoder declares, and is not subject to+``map_export.otlp_max_bytes``:++.. list-table::+ :header-rows: 1+ :widths: 44 56++ * - Field+ - Value+ * - ``eventName``+ - ``shirudo.bpf.map.snapshot.reference``+ * - ``severityNumber``, ``severityText``+ - ``9``, ``INFO``+ * - ``body``+ - ``stringValue``: ``BPF map snapshot stored in S3: <uri>``+ * - Attributes+ - The map snapshot attributes above, and+ ``shirudo.map.snapshot.uri``,+ ``shirudo.map.snapshot.format`` (``shirudo.map.v1+json``),+ ``shirudo.map.snapshot.content_type`` (``application/json``),+ ``shirudo.map.snapshot.content_encoding`` (``gzip``),+ ``shirudo.map.snapshot.size_bytes``,+ ``shirudo.map.snapshot.uncompressed_size_bytes`` and+ ``shirudo.map.snapshot.sha256``.++JSON lines+----------++``map_export.json_path`` or ``upatch map --json=<path>`` appends one line+per map to a file, instead of OTLP or besides it. The line is the JSON+value the map's decoder returns, not an OTLP document. A map without a+decoder fails with ``ENODATA``. ``map_export.json_path`` must be an+absolute path. A file or directory that carries shirudo's seal label is+refused. A new file gets mode ``0644``.++Keepalive structure+-------------------++The keepalive of a target with verdict ``ok``, as the code builds it.+Angle brackets mark values that vary, and the ``body`` values are+shortened to the first entries:++.. code-block:: json++ {+ "resourceLogs": [+ {+ "resource": {+ "attributes": [+ {"key": "service.name", "value": {"stringValue": "shirudo"}},+ {"key": "service.version", "value": {"stringValue": "<version>"}},+ {"key": "host.name", "value": {"stringValue": "<host>"}}+ ]+ },+ "scopeLogs": [+ {+ "scope": {"name": "shirudo.keepalive", "version": "<version>"},+ "logRecords": [+ {+ "timeUnixNano": "<ns>",+ "observedTimeUnixNano": "<ns>",+ "severityNumber": 9,+ "severityText": "INFO",+ "eventName": "shirudo.keepalive",+ "body": {+ "kvlistValue": {+ "values": [+ {"key": "schema", "value": {"intValue": "1"}},+ {"key": "version_id", "value": {"stringValue": "<version-id>"}},+ {"key": "is_target", "value": {"boolValue": true}}+ ]+ }+ },+ "attributes": [+ {"key": "shirudo.status", "value": {"stringValue": "ok"}},+ {"key": "shirudo.version_id", "value": {"stringValue": "<version-id>"}},+ {"key": "shirudo.tamper_attempts", "value": {"intValue": "<total>"}}+ ]+ }+ ]+ }+ ]+ }+ ]+ }++Related+-------++- :doc:`/operate/telemetry`+- :doc:`/reference/cli/status`+- :doc:`/reference/cli/upatch-map`+- :doc:`/upatches/decoders`+- :doc:`status-json`+- :doc:`configuration`diff --git a/Documentation/reference/formats/status-json.rst b/Documentation/reference/formats/status-json.rstnew file mode 100644index 00000000..9e50c79e--- /dev/null+++ b/Documentation/reference/formats/status-json.rst@@ -0,0 +1,712 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++status JSON+===========++``shirudo status --json`` prints one JSON object on one line. The same+object is the body of the status keepalive that ``status --otel``+sends, see :doc:`otlp`. Options and exit status are in+:doc:`/reference/cli/status`. How to read a report is in+:doc:`/operate/read-status`.++.. code-block:: console++ target# shirudo status --json++``status`` exits ``0`` for every verdict, ``tampered`` included. A+monitor reads ``status`` and the fields in `Fields to alert on`_, never+the exit status alone.++Top-level fields+----------------++Fields appear in this order. ``null`` stands for a value that cannot be+determined, as noted.++.. list-table::+ :header-rows: 1+ :widths: 26 16 58++ * - Field+ - Type+ - Value+ * - ``schema``+ - integer+ - ``1``+ * - ``version_id``+ - string+ - The binary's ``SHIRUDO_VERSION_ID``, as+ ``shirudo version --version-id`` prints it.+ * - ``is_target``+ - boolean+ - ``true`` when the certificate is present, the LSM link is+ pinned or the ``.bpf`` keyring ``init`` recorded exists.+ * - ``is_operator``+ - boolean+ - ``true`` when ``/var/lib/shirudo/keys/signing_key.pem`` exists.+ * - ``status``+ - string+ - The verdict, see `Verdicts`_.+ * - ``conditions``+ - array of object+ - Five conditions, each with ``type``, ``status`` and ``detail``,+ see `Conditions`_.+ * - ``lsm_attached``+ - boolean+ - ``true`` when the pin ``/run/shirudo/bpffs/lsm_link`` opens.+ * - ``mode``+ - string+ - ``production`` when ``lsm_attached`` is ``true``, else+ ``inactive``.+ * - ``keyring_mode``+ - string+ - ``bpf`` when the ``.bpf`` keyring is present, else ``none``.+ * - ``keyring_present``+ - boolean+ - ``true`` when ``init`` recorded a keyring serial and the+ ``.bpf`` keyring exists.+ * - ``keyring_serial``+ - integer or ``null``+ - Serial of the live ``.bpf`` keyring. ``null`` when it is absent.+ * - ``keyring_serial_pinned``+ - integer or ``null``+ - Serial ``init`` froze in the identity pin. ``null`` before+ ``init``.+ * - ``keyring_serial_matches``+ - boolean or ``null``+ - ``keyring_serial`` equals ``keyring_serial_pinned``. ``null``+ unless both are known.+ * - ``cert_present``+ - boolean+ - The primary certificate exists: on an image target+ ``/run/shirudo/runtime/keys/cert.der``.+ * - ``certs``+ - array of object+ - The trusted certificate set, each with ``sha256`` (of the DER),+ ``fingerprint`` (SHA-256 of the public key) and ``primary``+ (boolean). Empty when the set cannot be loaded.+ * - ``certs_revoked``+ - integer+ - Certificates under ``keys/revoked``.+ * - ``certs_unvouched``+ - integer+ - Certificates under ``keys/trusted`` without a valid vouch.+ * - ``certs_enrolled``+ - integer or ``null``+ - Asymmetric keys in the ``.bpf`` keyring. ``null`` when the+ keyring is absent.+ * - ``signing_key_present``+ - boolean+ - Same value as ``is_operator``.+ * - ``upatches_loaded``+ - array of object+ - One object per upatch pinned under+ ``/run/shirudo/bpffs/upatches``, see `upatches_loaded`_.+ * - ``assets``+ - object+ - Persistent state, see `assets`_.+ * - ``tamper_attempts``+ - object or ``null``+ - Refusals counted this boot, see `tamper_attempts`_. ``null``+ until ``init`` has pinned the counters.+ * - ``config``+ - object or ``null``+ - Config image activation, see `config`_. ``null`` on a host+ without config activation state.+ * - ``system``+ - object+ - Only with ``--include-system``, see `Optional blocks`_.+ * - ``tpm``+ - object+ - The measurement register, see `tpm`_.+ * - ``upatch_tree``+ - object+ - The upatch tree, see `upatch_tree`_.+ * - ``kernel_log``+ - array of object+ - Only with ``--include-kernellog``, see `Optional blocks`_.+ * - ``boot_at``, ``modules``+ - string, array of object+ - Only with ``--include-modules``, see `Optional blocks`_.++Verdicts+--------++``status`` takes the first verdict in this order whose condition holds.++.. list-table::+ :header-rows: 1+ :widths: 18 82++ * - ``status``+ - Condition+ * - ``tampered``+ - The live register differs from the eventlog replay, the+ ``.bpf`` keyring's serial differs from the pinned serial, the+ keyring ``init`` pinned is gone, or the selected config cannot be+ verified against its activation records.+ * - ``lsm-off``+ - The LSM link is not pinned. Enforcement is off.+ * - ``init-pending``+ - No ``.bpf`` keyring is recorded: ``init`` has not completed.+ * - ``reboot-pending``+ - A config activation is pending until the next reboot.+ * - ``degraded``+ - No register is bound this boot: no TPM answered, or the NV index+ is not written.+ * - ``ok``+ - None of the above.++Conditions+----------++``conditions`` always holds these five types, in this order. ``status``+is ``OK``, ``WARN`` or ``ALERT``. ``<serial>`` and ``<root>`` stand for+a keyring serial and the first 12 hex digits of the config root hash.++.. list-table::+ :header-rows: 1+ :widths: 18 10 72++ * - ``type``+ - ``status``+ - ``detail``+ * - ``LsmAttached``+ - ``OK``+ - ``lsm/bpf link present and pinned``+ * -+ - ``ALERT``+ - ``lsm/bpf absent -- enforcement OFF``+ * - ``KeyringSealed``+ - ``OK``+ - ``serial=<serial> in the BPF keyring, pin matches``+ * -+ - ``WARN``+ - ``shirudo keyring absent (not init'd?)``+ * -+ - ``ALERT``+ - ``pin serial=<serial>, the BPF keyring is gone (removed?)``+ * -+ - ``ALERT``+ - ``pin serial=<serial> != live serial=<serial> (swapped?)``+ * - ``ChainIntact``+ - ``OK``+ - ``live register == eventlog replay``+ * -+ - ``WARN``+ - ``no register bound this boot (init incomplete)``+ * -+ - ``WARN``+ - ``no TPM answered, no register to replay``+ * -+ - ``ALERT``+ - ``live register != eventlog replay (tamper?)``+ * - ``TpmMeasured``+ - ``OK``+ - ``NV index 0x01818E00 readable``+ * -+ - ``WARN``+ - ``NV index 0x01818E00 not bound this boot``+ * -+ - ``WARN``+ - ``no TPM answered``+ * - ``ConfigActive``+ - ``OK``+ - ``config <root>.. is active``+ * -+ - ``WARN``+ - ``no config activation state (init not run?)``+ * -+ - ``WARN``+ - ``the activation of config <root>.. is pending until the next+ reboot``+ * -+ - ``ALERT``+ - ``the config activation record does not belong to this TPM boot+ (tamper?)``+ * -+ - ``ALERT``+ - ``the mounted config does not match the selected root (tamper?)``+ * -+ - ``ALERT``+ - ``the config PCR, activation records and mounted config disagree+ (tamper?)``++upatches_loaded+---------------++.. list-table::+ :header-rows: 1+ :widths: 22 18 60++ * - Field+ - Type+ - Value+ * - ``name``+ - string+ - The upatch name.+ * - ``location``+ - string+ - The attach point, for example ``fentry/do_nanosleep``.+ * - ``status``+ - string+ - ``success``+ * - ``n_maps``+ - integer+ - Maps pinned for the upatch.+ * - ``loaded_at``+ - string+ - Change time of the upatch's pin directory, ISO 8601 UTC.+ * - ``age_sec``+ - integer or ``null``+ - Seconds since ``loaded_at``.+ * - ``payload_sha256``+ - string or ``null``+ - The loaded payload's digest, as in the eventlog.++assets+------++.. list-table::+ :header-rows: 1+ :widths: 22 18 60++ * - Field+ - Type+ - Value+ * - ``root``+ - string+ - ``/var/lib/shirudo``+ * - ``cert``+ - boolean+ - Same test as ``cert_present``.+ * - ``signing_key``+ - boolean+ - Same test as ``is_operator``.+ * - ``eventlog``+ - boolean+ - ``/var/lib/shirudo/eventlog`` exists.+ * - ``eventlog_bytes``+ - integer+ - Its size, all boots.+ * - ``upatches``+ - integer or ``null``+ - ``.upatch`` files in ``/var/lib/shirudo/upatches``. ``null``+ when the directory is absent.+ * - ``incoming``+ - integer or ``null``+ - Entries in ``/var/lib/shirudo/incoming``. ``null`` when the+ directory is absent.+ * - ``bpffs_mounted``+ - boolean+ - ``/run/shirudo/bpffs`` is a mount point.++tamper_attempts+---------------++.. list-table::+ :header-rows: 1+ :widths: 22 18 60++ * - Field+ - Type+ - Value+ * - ``total``+ - integer+ - Sum of all counters.+ * - ``counters``+ - object+ - Every counter by name, zero or not, so the keys are the same in+ every report. :doc:`/security/tamper-counters` lists them.++The counters live in a pinned BPF map under ``/run/shirudo/bpffs`` and+start at zero at every boot.++config+------++.. list-table::+ :header-rows: 1+ :widths: 22 18 60++ * - Field+ - Type+ - Value+ * - ``root_hash``+ - string+ - Root hash of the selected config image, 64 hex digits.+ * - ``activation_pending``+ - boolean+ - ``true`` while an activation waits for the next reboot.+ * - ``error``+ - string or ``null``+ - Why the selected config cannot be verified, as an ``strerror``+ text. ``null`` when it is active or pending.++tpm+---++.. list-table::+ :header-rows: 1+ :widths: 26 18 56++ * - Field+ - Type+ - Value+ * - ``reachable``+ - boolean+ - A TPM answered.+ * - ``nv_index``+ - string+ - ``0x01818E00``+ * - ``chain``+ - string or ``null``+ - The live register value. ``null`` when no register is bound.+ * - ``nv_name``+ - string or ``null``+ - The register's TPM name. ``null`` when no register is bound.+ * - ``register_bound``+ - boolean+ - The NV index is defined and written.+ * - ``register_anchored``+ - boolean+ - The register's name equals the name this boot's ``init``+ record gives, for the TPM's current reset count.+ * - ``init_records``+ - integer+ - ``init`` records this boot.+ * - ``register_rebound``+ - boolean+ - Two ``init`` records this boot name the same TPM reset count.+ * - ``pcr``+ - integer+ - ``9``+ * - ``phase_pcr``+ - integer+ - ``11``+ * - ``pcr_before``+ - string or ``null``+ - PCR 9 before the binding, from the ``init`` record. ``null``+ without one.+ * - ``phase_before``+ - string or ``null``+ - PCR 11 at the binding, from the ``init`` record. ``null``+ without one.+ * - ``bound_in``+ - string or ``null``+ - ``initrd`` or ``root``, from the ``init`` record. ``null``+ without one.+ * - ``chain_matches_eventlog``+ - boolean or ``null``+ - The register is anchored, not rebound, and equals this boot's+ eventlog replay. ``null`` when no register is bound.+ * - ``eventlog``+ - object+ - ``present`` (boolean), ``entries`` (lines in+ ``/var/lib/shirudo/eventlog``, all boots), ``bytes``, and+ ``events`` with ``--include-eventlog``.++:doc:`eventlog` defines the records and the replay.++upatch_tree+-----------++.. list-table::+ :header-rows: 1+ :widths: 28 18 54++ * - Field+ - Type+ - Value+ * - ``configured``+ - boolean+ - A tree configuration exists, in the config image on an image+ target.+ * - ``pending``+ - boolean+ - ``/var/lib/shirudo/bpm/upatch-tree/pending.json`` exists.+ * - ``tree_id``, ``generation``, ``last_seq``, ``projection_root``,+ ``manifest_digest``+ - string, integer, integer, string, string+ - The tree state, present when it can be read.+ * - ``state``+ - ``null``+ - Present instead of the five fields above when there is no tree+ state.+ * - ``eventlog_projection_root``+ - string or ``null``+ - Replay of the tree's projection log. ``null`` when it cannot be+ replayed.+ * - ``eventlog_matches_state``+ - boolean or ``null``+ - The replay equals ``projection_root``.++:doc:`bpm-formats` defines the tree state.++Optional blocks+---------------++``--show-full`` turns on every block below.++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Option+ - Adds+ * - ``--include-system``+ - ``system``: ``hostname``, ``os`` (``PRETTY_NAME`` from+ ``/etc/os-release``), ``kernel_release``, ``kernel_version``,+ ``kernel_build_id`` (from ``/sys/kernel/notes``),+ ``kernel_config`` (every ``CONFIG_*`` in+ ``/boot/config-<release>``, ``n`` for one not set, empty without+ the file), ``architecture``, ``machine_id``, ``boot_id``,+ ``nproc``, ``mem_total_kb``, ``mem_avail_kb``, ``disk_total_kb``+ and ``disk_used_kb`` (of ``/``), ``uptime_seconds``. A number+ that cannot be read is ``-1``.+ * - ``--include-eventlog``+ - ``tpm.eventlog.events``: one object per line of+ ``/var/lib/shirudo/eventlog``, all boots, with ``ts``, ``type``+ and ``digest``, plus ``set_digest`` for ``init`` and ``upatch``+ (``name``, ``payload_sha256``) for upatch events. A line that+ does not parse gives ``{"type": "unparseable"}``.+ * - ``--include-kernellog[=<n>]``+ - ``kernel_log``: the last ``<n>`` kernel log records, 1 to 100,+ default 10, each with ``ts`` (ISO 8601 UTC) and ``msg``.+ * - ``--include-modules``+ - ``boot_at`` (boot time, ISO 8601 UTC) and ``modules``: each+ loaded module with ``name``, ``size``, ``refcount``,+ ``loaded_at``, ``since_boot_sec`` (or ``null``) and ``deps``.++``status`` sizes its output buffer from the options, the eventlog size+and the number of loaded upatches, at most 8 MiB. A document that does+not fit is not printed: ``status`` writes ``status: json encode failed:+<reason>`` to standard error, nothing to standard output, sends no+keepalive and exits 1.++Fields to alert on+------------------++.. list-table::+ :header-rows: 1+ :widths: 34 22 44++ * - Field+ - Alert when+ - Next step+ * - ``status``+ - ``tampered``+ - Handle as an incident: :doc:`/operate/incident-tampered`.+ * - ``status``+ - any value but ``ok``+ - :doc:`/operate/read-status`+ * - ``conditions[].status``+ - ``ALERT``+ - The ``detail`` names the cause.+ * - ``tamper_attempts.total``+ - rises+ - The counter that moved names the refused action,+ :doc:`/security/tamper-counters`.+ * - ``tamper_attempts``+ - ``null`` on a target+ - ``init`` has not pinned the counters this boot.+ * - ``lsm_attached``+ - ``false``+ - Enforcement is off.+ * - ``keyring_serial_matches``+ - ``false``+ - The ``.bpf`` keyring was replaced.+ * - ``tpm.chain_matches_eventlog``+ - ``false``+ - The register and the eventlog disagree.+ * - ``tpm.register_rebound``+ - ``true``+ - The register was bound twice in one TPM reset period.+ * - ``tpm.bound_in``+ - ``root``+ - The register was bound after the initrd.+ * - ``config.error``+ - not ``null``+ - The selected config cannot be verified.+ * - ``config.activation_pending``+ - ``true``+ - Every command but ``status`` is refused until a reboot.+ * - ``upatch_tree.eventlog_matches_state``+ - ``false``+ - The tree state and its projection log disagree.+ * - ``version_id``+ - differs from the expected build+ - A different shirudo build runs on the target.++A collector that stops receiving the keepalive from a target has lost+the target or its export, see :doc:`otlp`.++Example+-------++``shirudo status --json`` on a test target with one upatch loaded,+indented here:++.. code-block:: json++ {+ "schema": 1,+ "version_id": "58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0",+ "is_target": true,+ "is_operator": false,+ "status": "ok",+ "conditions": [+ {+ "type": "LsmAttached",+ "status": "OK",+ "detail": "lsm/bpf link present and pinned"+ },+ {+ "type": "KeyringSealed",+ "status": "OK",+ "detail": "serial=420195959 in the BPF keyring, pin matches"+ },+ {+ "type": "ChainIntact",+ "status": "OK",+ "detail": "live register == eventlog replay"+ },+ {+ "type": "TpmMeasured",+ "status": "OK",+ "detail": "NV index 0x01818E00 readable"+ },+ {+ "type": "ConfigActive",+ "status": "OK",+ "detail": "config 12dbf3c75083.. is active"+ }+ ],+ "lsm_attached": true,+ "mode": "production",+ "keyring_mode": "bpf",+ "keyring_present": true,+ "keyring_serial": 420195959,+ "keyring_serial_pinned": 420195959,+ "keyring_serial_matches": true,+ "cert_present": true,+ "certs": [+ {+ "sha256": "3702e8ffe817ade6151eea338194649cc3a5be1e0b940e462a1a75e52f7095d0",+ "fingerprint": "2edb279c05efee6b489a65ae07fd6d402a54b6e495be68f6d364544e9b5a37e2",+ "primary": false+ },+ {+ "sha256": "d95db97ff4658b96b8b538afef41a25ca9f7a2c4d0abffdb26cbac7b0ba294b9",+ "fingerprint": "d1dc6624ee6bd0c277864fab0a8a15f8509308aa2338768cb772117c157f8d61",+ "primary": true+ }+ ],+ "certs_revoked": 0,+ "certs_unvouched": 0,+ "certs_enrolled": 2,+ "signing_key_present": false,+ "upatches_loaded": [+ {+ "name": "shirudo-test-basic",+ "location": "fentry/do_nanosleep",+ "status": "success",+ "n_maps": 0,+ "loaded_at": "2026-10-29T16:21:18Z",+ "age_sec": 1,+ "payload_sha256": "8aee7072a1a15e4dddc93ad6b253a0e2e70ad6cdf767442aa8a1c1997bc3069f"+ }+ ],+ "assets": {+ "root": "/var/lib/shirudo",+ "cert": true,+ "signing_key": false,+ "eventlog": true,+ "eventlog_bytes": 2324,+ "upatches": 1,+ "incoming": 0,+ "bpffs_mounted": true+ },+ "tamper_attempts": {+ "total": 47,+ "counters": {+ "LoadNotLoader": 27, "LoadUnsigned": 0, "LoadUnverified": 0, "LoadKeyringKind": 0,+ "LoadKeyring": 0, "MapCreate": 1, "MapWrite": 0, "MapFdWrite": 0,+ "ProgRun": 0, "ProgAttach": 0, "ObjPin": 0, "BpfCommand": 12,+ "ExeIdentity": 0, "KeyringWrite": 0, "PinUnlink": 0, "PinRename": 0,+ "PinXattr": 0, "BpffsUmount": 0, "BpffsUmountAbove": 0, "BpffsMount": 0,+ "SealWrite": 0, "SealUnlink": 0, "SealRename": 0, "SealSetattr": 0,+ "SealXattr": 0, "SealLabel": 0, "SealPtrace": 7, "SealPerf": 0,+ "ExecTraced": 0, "SealEntry": 0, "PerfAttach": 0, "PinEntry": 0,+ "SealCopyUp": 0, "Kexec": 0, "TpmExtend": 0, "ObjGet": 0+ }+ },+ "config": {+ "root_hash": "12dbf3c750834908c0f6510481e35fbb0cc76cf6b1896de524304535e63aff0f",+ "activation_pending": false,+ "error": null+ },+ "tpm": {+ "reachable": true,+ "nv_index": "0x01818E00",+ "chain": "c50b22ac27c5bb6a90ee5ff9b440fbbd5bb60b84a2aa7b395daec3f330886fcd",+ "nv_name": "000be3a552e2219550d2597ab96f3fffdeec0d01ce27cde858e0858ab0cdaba6c045",+ "register_bound": true,+ "register_anchored": true,+ "init_records": 1,+ "register_rebound": false,+ "pcr": 9,+ "phase_pcr": 11,+ "pcr_before": "0000000000000000000000000000000000000000000000000000000000000000",+ "phase_before": "0000000000000000000000000000000000000000000000000000000000000000",+ "bound_in": "initrd",+ "chain_matches_eventlog": true,+ "eventlog": {+ "present": true,+ "entries": 2,+ "bytes": 2324+ }+ },+ "upatch_tree": {+ "configured": false,+ "pending": false,+ "state": null,+ "eventlog_projection_root": null,+ "eventlog_matches_state": null+ }+ }++After refused tamper attempts as root (reading and removing a pin,+unmounting the private bpffs, appending to the eventlog), the counters+of the same target read:++.. code-block:: json++ {+ "total": 73,+ "counters": {+ "LoadNotLoader": 39, "LoadUnsigned": 0, "LoadUnverified": 0, "LoadKeyringKind": 0,+ "LoadKeyring": 0, "MapCreate": 1, "MapWrite": 0, "MapFdWrite": 0,+ "ProgRun": 0, "ProgAttach": 0, "ObjPin": 0, "BpfCommand": 16,+ "ExeIdentity": 0, "KeyringWrite": 0, "PinUnlink": 1, "PinRename": 0,+ "PinXattr": 0, "BpffsUmount": 1, "BpffsUmountAbove": 0, "BpffsMount": 0,+ "SealWrite": 1, "SealUnlink": 0, "SealRename": 0, "SealSetattr": 0,+ "SealXattr": 0, "SealLabel": 0, "SealPtrace": 12, "SealPerf": 0,+ "ExecTraced": 0, "SealEntry": 0, "PerfAttach": 0, "PinEntry": 0,+ "SealCopyUp": 0, "Kexec": 0, "TpmExtend": 0, "ObjGet": 2+ }+ }++Related+-------++- :doc:`/reference/cli/status`+- :doc:`/operate/read-status`+- :doc:`/security/tamper-counters`+- :doc:`eventlog`+- :doc:`otlp`diff --git a/Documentation/reference/formats/upatch-format.rst b/Documentation/reference/formats/upatch-format.rstnew file mode 100644index 00000000..e7c52ecf--- /dev/null+++ b/Documentation/reference/formats/upatch-format.rst@@ -0,0 +1,769 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: upatch authors, Kernel developers, security reviewers++.upatch format+==============++A ``.upatch`` file is the signed container that :doc:`/reference/cli/build`+writes and that :doc:`/reference/cli/upatch-load` and+:doc:`/reference/cli/upatch-unload` consume. One layout serves both a load+artifact and an unload directive. The structures are defined in+``include/shirudo/upatch.h``. The writer is ``tools/shirudo-build/package.c``+and the reader is ``util/upatch.c``.++Conventions+-----------++- Every multi-byte integer is little-endian on every architecture.+- Header offsets count from the start of the file. Offsets inside+ ``data`` count from the start of ``data``.+- Fixed-size string fields are NUL-padded and must contain a NUL.+- A file is at most 16 MiB (``SHIRUDO_UPATCH_FILE_MAX``).++Layout+------++The writer emits the regions in the order below. A reader locates each+region through the header only.++.. list-table::+ :header-rows: 1+ :widths: 18 32 50++ * - Region+ - Located by+ - Content+ * - header+ - offset 0, 360 bytes+ - ``struct shirudo_upatch_header``.+ * - ``loader_insns``+ - ``loader_insns_off``, ``loader_insns_len``+ - The ``BPF_PROG_TYPE_SYSCALL`` loader program that libbpf's+ ``bpf_object__gen_loader()`` generates, as 8-byte+ ``struct bpf_insn`` records. The writer places it at offset 360.+ * - ``signature``+ - ``signature_off``, ``signature_len``+ - Detached CMS signature over ``loader_insns || data``.+ * - ``data``+ - ``data_off``, ``data_len``+ - The loader's data blob (``gen_loader_opts.data``), then the signed+ sections, their directory and the trailer.+ * - ``metadata``+ - ``metadata_off``, ``metadata_len``+ - Absent. ``shirudo build`` sets both fields to 0. The target never+ reads this region.++Header+------++``struct shirudo_upatch_header``, 360 bytes, no padding.++.. list-table::+ :header-rows: 1+ :widths: 8 6 20 66++ * - Offset+ - Size+ - Field+ - Value+ * - 0+ - 8+ - ``magic``+ - ``0x53485244554e4150``. The file starts with the bytes+ ``PANUDRHS``.+ * - 8+ - 4+ - ``version``+ - ``1``.+ * - 12+ - 4+ - ``flags``+ - Bit 0, ``SHIRUDO_DIRECTIVE_UNLOAD``: 0 for a load artifact, 1 for an+ unload directive. Writers set bits 1 to 31 to 0. The reader does not+ check them.+ * - 16+ - 256+ - ``name``+ - The upatch name, NUL-padded. Writers accept 1 to 255 characters of+ ``[A-Za-z0-9._-]`` that do not start with ``.``. For an unload+ directive, the name of the upatch to unload.+ * - 272+ - 32+ - ``payload_sha256``+ - SHA-256 of ``loader_insns || data``, the bytes the signature covers.+ * - 304+ - 4+ - ``loader_insns_off``+ - At least 360 and a multiple of 8.+ * - 308+ - 4+ - ``loader_insns_len``+ - Non-zero multiple of 8.+ * - 312+ - 4+ - ``signature_off``+ - File offset of the signature.+ * - 316+ - 4+ - ``signature_len``+ - Non-zero.+ * - 320+ - 4+ - ``metadata_off``+ - 0.+ * - 324+ - 4+ - ``metadata_len``+ - 0.+ * - 328+ - 4+ - ``data_off``+ - File offset of ``data``.+ * - 332+ - 4+ - ``data_len``+ - Length of ``data``, signed sections included.+ * - 336+ - 4+ - ``log_buf_sz``+ - Writers set 1048576. The target ignores the field and sizes its+ verifier log at 16 MiB.+ * - 340+ - 4+ - ``nr_maps``+ - Number of maps in the BPF object, the count of map descriptors the+ loader writes behind its context.+ * - 344+ - 4+ - ``nr_progs``+ - Number of programs in the BPF object, the count of program+ descriptors behind the map descriptors.+ * - 348+ - 4+ - ``rodata_data_off``+ - Offset in ``data`` of the initial ``.rodata`` value, or 0 when the+ object has no ``.rodata``. At most ``data_len``.+ * - 352+ - 4+ - ``type``+ - ``1`` (``SHIRUDO_UPATCH_TYPE_BPF``).+ * - 356+ - 4+ - ``reserved1``+ - 0.++Signature+---------++.. list-table::+ :header-rows: 1+ :widths: 24 76++ * - Property+ - Value+ * - Signed bytes+ - ``loader_insns`` followed by ``data``, exactly as stored. The header+ and ``metadata`` are outside the signature.+ * - Encoding+ - DER CMS ``SignedData``, detached (no encapsulated content), no+ certificates. The signer is identified by its subject key+ identifier.+ * - Algorithm+ - ML-DSA-87. The writer refuses any other key.+ * - Signed attributes+ - Built against OpenSSL 3.x: signed attributes with a SHA-512 message+ digest and no signing time. Built against OpenSSL 4: no signed+ attributes, the signature covers the content directly.+ * - Size+ - At most 16 KiB from the writer. The kernel accepts at most 64 KiB.+ * - Verifier+ - The kernel, during ``BPF_PROG_LOAD`` of the loader, with+ ``attr.keyring_id`` set to ``KEY_SPEC_BPF_KEYRING`` (the ``.bpf``+ keyring). The target passes ``data`` as the frozen value of a+ one-element array map, ``__loader.map``, made exclusive to the+ loader by ``excl_prog_hash`` (SHA-256 of ``loader_insns``), as+ ``fd_array[0]`` with ``fd_array_cnt`` set to 1. The kernel verifies+ the signature over the instructions followed by that map value.++:doc:`/internals/signed-loader` describes the load sequence around this+check.++Signed sections+---------------++What the target needs beyond the loader rides inside ``data``, behind the+loader's own bytes, so the signature covers it. The loader addresses only+its own prefix of ``data``.++.. code-block:: text++ data: loader data | pad | section | pad | section ... | pad | directory | trailer++The writer aligns each section and the directory to 8 bytes from the start+of ``data`` and fills the padding with zeros. The trailer is the last 16+bytes of ``data``.++Trailer+~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 8 6 20 66++ * - Offset+ - Size+ - Field+ - Value+ * - +0+ - 4+ - ``magic``+ - ``0x52544753``, the bytes ``SGTR``.+ * - +4+ - 4+ - ``version``+ - ``1``.+ * - +8+ - 4+ - ``dir_off``+ - Offset of the directory in ``data``.+ * - +12+ - 4+ - ``nr_sections``+ - Number of directory entries, 1 to 8.++Directory entry+~~~~~~~~~~~~~~~++``nr_sections`` entries of 16 bytes each.++.. list-table::+ :header-rows: 1+ :widths: 8 6 20 66++ * - Offset+ - Size+ - Field+ - Value+ * - +0+ - 4+ - ``tag``+ - Section tag, one of the table below.+ * - +4+ - 4+ - ``reserved``+ - 0.+ * - +8+ - 4+ - ``off``+ - Offset of the section in ``data``.+ * - +12+ - 4+ - ``len``+ - Length of the section in bytes.++Section tags+~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 10 14 12 64++ * - Tag+ - Value+ - Length+ - Content and presence+ * - ``NAME``+ - ``0x454d414e``+ - 256+ - The upatch name, NUL-padded, byte-for-byte equal to the header+ ``name``. Required in a load artifact and in an unload directive.+ * - ``UPGM``+ - ``0x4d475055``+ - variable, non-zero+ - Attach metadata, see `UPGM section`_. Required in a load artifact.+ * - ``UNLD``+ - ``0x444c4e55``+ - 32+ - The ``payload_sha256`` the loaded upatch must carry. Required in an+ unload directive.+ * - ``DCDB``+ - ``0x42444344``+ - variable+ - Signed decoders, see `DCDB section`_. Present in a load artifact+ when its programs declare decoders.++The writer emits ``NAME``, then ``UNLD`` for an unload directive, or+``UPGM`` and an optional ``DCDB`` for a load artifact.++UPGM section+~~~~~~~~~~~~++A 16-byte header followed by ``nr_progs`` program entries, in libbpf's+program iteration order, which is the order of the loader's program+descriptors.++.. list-table::+ :header-rows: 1+ :widths: 8 6 20 66++ * - Offset+ - Size+ - Field+ - Value+ * - +0+ - 4+ - ``magic``+ - ``0x4d475055``, the bytes ``UPGM``.+ * - +4+ - 4+ - ``version``+ - ``1``.+ * - +8+ - 4+ - ``nr_progs``+ - Number of program entries. Equal to the header ``nr_progs``.+ * - +12+ - 4+ - ``reserved``+ - 0.++Each program entry is 160 bytes:++.. list-table::+ :header-rows: 1+ :widths: 8 6 20 66++ * - Offset+ - Size+ - Field+ - Value+ * - +0+ - 4+ - ``role``+ - Program role, see the table below.+ * - +4+ - 4+ - ``kind``+ - Attach kind, see the table below. 0 for the serializer and test-run+ roles.+ * - +8+ - 8+ - ``offset``+ - Byte offset into the function for ``kprobe``. 0 for every other+ kind and role.+ * - +16+ - 128+ - ``target``+ - NUL-terminated. The kernel symbol for ``kprobe`` and+ ``kretprobe``, the function glob for ``uprobe.multi`` (no ``,`` or+ ``|``). Empty for every other kind and role.+ * - +144+ - 16+ - ``map``+ - NUL-terminated name of the map a serializer reads. Empty for every+ other role.++.. list-table::+ :header-rows: 1+ :widths: 10 20 70++ * - ``role``+ - Name+ - Program+ * - 0+ - attach+ - A program the target attaches and pins as a link.+ * - 1+ - serializer+ - A ``SEC("syscall")`` program named ``shirudo_serialize__<map>``.+ * - 2+ - test-run+ - The one ``SEC("syscall")`` program named ``shirudo_test__<id>``.++.. list-table::+ :header-rows: 1+ :widths: 10 34 56++ * - ``kind``+ - Name+ - Sections that produce it+ * - 0+ - raw tracepoint (BTF target)+ - ``fentry/``, ``fentry.s/``, ``fexit/``, ``fexit.s/``, ``lsm/``,+ ``lsm.s/``, ``tp_btf/``+ * - 1+ - kprobe+ - ``kprobe/<symbol>[+<offset>]``+ * - 2+ - kretprobe+ - ``kretprobe/<symbol>``+ * - 3+ - cgroup_skb ingress+ - ``cgroup_skb/ingress``+ * - 4+ - cgroup_skb egress+ - ``cgroup_skb/egress``+ * - 5+ - fmod_ret+ - ``fmod_ret/<symbol>``, ``fmod_ret.s/<symbol>``+ * - 6+ - netfilter IPv6 pre-routing+ - ``netfilter``+ * - 7+ - uprobe.multi entry probe+ - ``uprobe.multi/<absolute-path>:<function-glob>``++:doc:`/upatches/attach-kinds` describes how the target attaches each kind.++When any entry has kind 7, one ``UPUT`` block follows the program entries+and ends the section. Without a kind 7 entry the section ends after the+program entries.++.. list-table::+ :header-rows: 1+ :widths: 8 6 20 66++ * - Offset+ - Size+ - Field+ - Value+ * - +0+ - 4+ - ``magic``+ - ``0x54555055``, the bytes ``UPUT``.+ * - +4+ - 4+ - ``version``+ - ``1``.+ * - +8+ - 4+ - ``nr_targets``+ - Number of target records, equal to the number of kind 7 entries.+ * - +12+ - 4+ - ``reserved``+ - 0.++Each target record is a 16-byte head followed, without padding, by its+variable parts:++.. list-table::+ :header-rows: 1+ :widths: 14 20 66++ * - Offset+ - Field+ - Value+ * - +0+ - ``prog_idx``+ - Index of a kind 7 program entry. Each such entry has exactly one+ record.+ * - +4+ - ``path_len``+ - Length of the path, 1 to 4095.+ * - +8+ - ``build_id_len``+ - Length of the GNU build ID, 1 to 64.+ * - +12+ - ``nr_offsets``+ - Number of offsets, 1 to 1048576.+ * - +16+ - path+ - ``path_len`` bytes, an absolute path without a NUL.+ * - then+ - build ID+ - ``build_id_len`` bytes of the ELF's GNU build ID.+ * - then+ - offsets+ - ``nr_offsets`` little-endian ``u64`` ELF file offsets, strictly+ increasing.++DCDB section+~~~~~~~~~~~~++A 16-byte header, ``nr_decoders`` entries of 200 bytes, then the decoder+sources, concatenated without terminators.++.. list-table::+ :header-rows: 1+ :widths: 8 6 20 66++ * - Offset+ - Size+ - Field+ - Value+ * - +0+ - 4+ - ``magic``+ - ``0x42444344``, the bytes ``DCDB``.+ * - +4+ - 4+ - ``version``+ - ``1``.+ * - +8+ - 4+ - ``nr_decoders``+ - At least 1.+ * - +12+ - 4+ - ``reserved``+ - 0.++Each decoder entry:++.. list-table::+ :header-rows: 1+ :widths: 8 6 20 66++ * - Offset+ - Size+ - Field+ - Value+ * - +0+ - 4+ - ``language``+ - ``1``, Lua.+ * - +4+ - 4+ - ``api_version``+ - ``1``.+ * - +8+ - 4+ - ``input_format``+ - ``1``, ``shirudo.map.v1``.+ * - +12+ - 4+ - ``export_signal``+ - ``1`` log, ``2`` metric.+ * - +16+ - 64+ - ``upatch``+ - NUL-terminated upatch name. The writer requires the artifact's name.+ * - +80+ - 16+ - ``map``+ - NUL-terminated name of a map in the object.+ * - +96+ - 64+ - ``source``+ - NUL-terminated relative path of the decoder source, resolved+ against the directory of the ``.bpf.c`` file. No ``..`` component.+ * - +160+ - 32+ - ``entrypoint``+ - NUL-terminated name of the Lua function.+ * - +192+ - 4+ - ``source_off``+ - Offset of the source in the section, behind the entries.+ * - +196+ - 4+ - ``source_len``+ - Length of the source, non-zero.++The writer takes each entry from a ``struct shirudo_decoder_manifest`` that+the BPF program declares in ``.rodata`` (``bpf/lib/shirudo_decoder.h``,+192 bytes, magic ``0x44434544``, the bytes ``DECD``, ``u16`` fields+``version``, ``language``, ``api_version``, ``input_format``,+``export_signal`` and ``reserved``, then the same four strings). It scans+``.rodata`` at 4-byte steps, accepts one decoder per upatch and map, and+reads each source file, at most 16 MiB. A decoder whose ``language``,+``api_version``, ``input_format`` or ``export_signal`` differs from the+values above fails the build. :doc:`/upatches/decoders` covers the decoder+API.++Header fields outside the signature+-----------------------------------++The header is not signed. The target checks some fields against the+signed bytes and trusts others as they are.++.. list-table::+ :header-rows: 1+ :widths: 22 78++ * - Field+ - Treatment+ * - ``name``+ - Must equal the signed ``NAME`` section, all 256 bytes, for a load+ and for an unload.+ * - ``payload_sha256``+ - Recomputed as SHA-256 of ``loader_insns || data`` and must match.+ The target records it in the ``security.bpf.shirudo.payload`` xattr+ of the upatch's pin directory, measures it in the load event and+ matches it against an unload directive's ``UNLD`` value.+ * - ``flags``+ - Bit 0 selects the load or the unload path. Each path refuses an+ artifact without the signed section it requires (``UPGM`` or+ ``UNLD``).+ * - ``nr_progs``+ - Must equal the ``nr_progs`` of the signed ``UPGM`` section.+ * - ``nr_maps``+ - Not checked against signed content. The target uses it to find the+ program descriptors behind the map descriptors in the loader+ context, and to pin and close the map descriptors.+ * - ``rodata_data_off``+ - Bounds-checked only: the ``.rodata`` size from the signed BTF must+ fit between it and the end of ``data``. ``bpm info data`` reads+ ``.rodata`` at this offset, and the operator's ``.rodata`` rewrites+ (``bpm build`` and ``bpm config update`` rodata entries) patch at it+ and re-sign.+ * - ``log_buf_sz``+ - Ignored.+ * - ``metadata_off``, ``metadata_len``+ - Bounds-checked. Not read on the target.+ * - ``magic``, ``version``, ``type``, ``reserved1``, section offsets and+ lengths+ - Checked by the reader, see `Reader validation`_.++Reader validation+-----------------++``util/upatch.c`` applies these checks in order. Any failure rejects the+file.++#. The file is a regular file, not empty and at most 16 MiB.+#. The file is at least 360 bytes long.+#. ``magic`` equals ``0x53485244554e4150``.+#. ``version`` equals 1.+#. ``name`` contains a NUL.+#. ``reserved1`` is 0.+#. ``type`` equals 1.+#. ``loader_insns_off`` is at least 360 and a multiple of 8,+ ``loader_insns_len`` is a multiple of 8, and the region lies inside the+ file.+#. ``signature``, ``metadata`` and ``data`` each lie inside the file, and+ each non-empty one starts at or after offset 360.+#. ``rodata_data_off`` is at most ``data_len``.+#. ``loader_insns_len`` and ``signature_len`` are not 0.++The reader then parses the signed sections. A failure here does not reject+the file. The reader treats the whole directory as absent, so a load or an+unload later refuses for the section it lacks, and+:doc:`/reference/cli/upatch-info` shows no signed sections.++#. ``data`` is at least 16 bytes long and its last 16 bytes are a trailer+ with magic ``SGTR`` and version 1.+#. ``nr_sections`` is 1 to 8, and the directory lies between ``dir_off``+ and the trailer.+#. Each entry has ``reserved`` 0 and a section that ends at or before+ ``dir_off``.+#. Each tag is ``NAME``, ``UPGM``, ``UNLD`` or ``DCDB``, and appears at most+ once.+#. ``NAME`` is 256 bytes and contains a NUL. ``UPGM`` is not empty.+ ``UNLD`` is 32 bytes.+#. ``DCDB`` has magic ``DCDB``, version 1, at least one entry, all entries+ inside the section, NUL-terminated strings, non-zero ``language``,+ ``api_version``, ``input_format`` and ``export_signal``, and each source+ inside the section behind the entries.++Target admission+----------------++A load artifact passes the reader, then these checks in order. A failure+of checks 1 to 6 is reported as ``parser_rejected``, see+:doc:`/reference/failure-categories`.++#. ``flags`` bit 0 is clear.+#. ``loader_insns_len`` is a multiple of 8.+#. The header ``name`` is not empty, does not start with ``.`` and+ contains only ``[A-Za-z0-9._-]``.+#. A ``NAME`` section is present and equals the header ``name``.+#. ``payload_sha256`` equals SHA-256 of ``loader_insns || data``.+#. A ``UPGM`` section is present and parses: version 1 (any other version+ is ``EOPNOTSUPP``), ``reserved`` 0, ``nr_progs`` equal to the header's,+ every entry valid for its role and kind, and a ``UPUT`` block that is+ present exactly when a kind 7 entry exists and ends the section.+#. Each ``uprobe.multi`` target file is a regular file whose GNU build ID+ equals the recorded one.+#. The kernel verifies the signature in ``BPF_PROG_LOAD``.++An unload directive passes the reader, then these checks:++#. ``flags`` bit 0 is set.+#. ``NAME`` and ``UNLD`` sections are present and ``NAME`` equals the+ header ``name``.+#. Load checks 2 to 5 above, then the kernel verifies the signature in+ ``BPF_PROG_LOAD``. The target never runs the directive's loader.+#. The ``UNLD`` value equals the ``security.bpf.shirudo.payload`` xattr of+ the loaded upatch, or no upatch of that name is pinned.++Versioning+----------++.. list-table::+ :header-rows: 1+ :widths: 30 14 56++ * - Structure+ - Version+ - Reader on another value+ * - Container header+ - 1+ - Rejects the file.+ * - Trailer+ - 1+ - Treats the directory as absent.+ * - ``UPGM``+ - 1+ - Load refused (``EOPNOTSUPP``).+ * - ``UPUT``+ - 1+ - Load refused.+ * - ``DCDB``+ - 1+ - Treats the directory as absent.+ * - Decoder manifest in ``.rodata``+ - 1+ - The writer skips the candidate.++A section tag the reader does not know makes it treat the directory as+absent. A new section therefore needs readers that know its tag before+writers emit it. Reserved fields are 0 in every file a writer emits. The+reader checks ``reserved1``, the directory entries' ``reserved`` and the+``UPGM`` and ``UPUT`` ``reserved`` fields. It does not check ``flags``+bits 1 to 31 or the ``DCDB`` ``reserved`` field.++Limits+------++.. list-table::+ :header-rows: 1+ :widths: 50 50++ * - Item+ - Limit+ * - File size+ - 16 MiB+ * - Signature+ - 16 KiB (writer), 64 KiB (kernel)+ * - Signed sections+ - 1 to 8+ * - Name of an upatch+ - 255 characters of ``[A-Za-z0-9._-]``, not starting with ``.``+ * - ``kprobe``, ``kretprobe`` or ``uprobe.multi`` target+ - 127 bytes+ * - Serializer map name+ - 15 bytes+ * - ``uprobe.multi`` path+ - 4095 bytes+ * - GNU build ID+ - 1 to 64 bytes+ * - ``uprobe.multi`` offsets per program+ - 1 to 1048576+ * - Decoder source+ - 16 MiB per file+ * - Target verifier log+ - 16 MiB++Related+-------++- :doc:`/reference/cli/build` and :doc:`/reference/cli/upatch-info`+- :doc:`/internals/signed-loader`+- :doc:`/upatches/attach-kinds`+- :doc:`bpm-formats` for the packages that carry ``.upatch`` filesdiff --git a/Documentation/reference/index.rst b/Documentation/reference/index.rstnew file mode 100644index 00000000..e028b4e8--- /dev/null+++ b/Documentation/reference/index.rst@@ -0,0 +1,24 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++Reference+=========++Facts to look up: every command and its options, the formats shirudo+reads and writes, its settings, the failure categories and exit status,+the files and extended attributes it keeps, its systemd units and the+environment variables it reads. Each fact has one home here, and the+other sections link to it.++.. toctree::+ :titlesonly:++ cheat-sheet+ cli/index+ formats/index+ failure-categories+ files+ systemd-units+ environment+ versionsdiff --git a/Documentation/reference/systemd-units.rst b/Documentation/reference/systemd-units.rstnew file mode 100644index 00000000..5d3b7dbd--- /dev/null+++ b/Documentation/reference/systemd-units.rst@@ -0,0 +1,339 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators++systemd units and timers+========================++The units the target package installs, from ``systemd/*.in`` and+``systemd/*.timer``. Every service is ``Type=oneshot``: shirudo runs no+daemon.++Units+-----++.. list-table::+ :header-rows: 1+ :widths: 30 38 32++ * - Unit+ - Runs+ - Started by+ * - ``shirudo-initrd.service``+ - ``@bindir@/shirudo init`` in the initrd+ - ``initrd.target``, once per boot+ * - ``shirudo.service``+ - ``@bindir@/shirudo init $SHIRUDO_INIT_ARGS``, replaced by the+ runtime drop-in+ - ``sysinit.target``, once per boot+ * - ``shirudo-keepalive.service``+ - ``@bindir@/shirudo status --otel --include-system``+ - ``shirudo-keepalive.timer``+ * - ``shirudo-map-export.service``+ - ``@bindir@/shirudo upatch map --all``+ - ``shirudo-map-export.timer``+ * - ``shirudo-bpm-repo-update.service``+ - ``@bindir@/shirudo bpm repo update``, then+ ``@bindir@/shirudo bpm upgrade``+ - ``shirudo-bpm-repo-update.timer``+ * - ``shirudo-bpm-tree-sync.service``+ - ``@bindir@/shirudo bpm tree sync``+ - ``shirudo-bpm-tree-sync.timer``++``@bindir@`` is replaced at build time. It is ``/usr/bin`` in the+packages that ``make -C packaging`` builds and ``$(prefix)/bin``+otherwise, ``/usr/local/bin`` with the default prefix.++shirudo-initrd.service+----------------------++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Setting+ - Value+ * - ``ExecStartPre``+ - ``-mount -o remount,rw /sysroot`` (a failure is ignored)+ * - ``ExecStart``+ - ``@bindir@/shirudo init``: the binary the dracut module copies+ into the initrd at its path on the root file system+ * - ``Type``+ - ``oneshot``, ``RemainAfterExit=yes``+ * - ``ConditionPathExists``+ - ``/etc/initrd-release`` and ``/etc/shirudo/keys/cert.der``. The+ unit is skipped, not failed, when either is missing.+ * - ``After``+ - ``initrd-root-fs.target``, ``tpm2.target``,+ ``systemd-pcrphase-initrd.service``,+ ``systemd-tpm2-setup-early.service``+ * - ``Before``+ - ``initrd.target``, ``initrd-switch-root.target``,+ ``shutdown.target``+ * - ``Conflicts``+ - ``shutdown.target``+ * - ``RequiresMountsFor``+ - ``/sysroot/var/lib/shirudo``+ * - ``DefaultDependencies``+ - ``no``+ * - ``KeyringMode``+ - ``inherit``+ * - ``LimitMEMLOCK``+ - ``infinity``+ * - ``WantedBy``+ - ``initrd.target``++The dracut module ``90shirudo`` installs this unit into the initrd and+enables it there. It never runs in the root file system. No+``OnFailure=`` or failure action is set: when the unit fails, the boot+continues.++shirudo.service+---------------++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Setting+ - Value+ * - ``ExecStart``+ - ``@bindir@/shirudo init $SHIRUDO_INIT_ARGS``+ * - ``EnvironmentFile``+ - ``-/etc/shirudo/init.env`` (optional)+ * - ``Type``+ - ``oneshot``, ``RemainAfterExit=yes``+ * - ``ConditionPathIsMountPoint``+ - ``/run/shirudo/runtime``: the unit is skipped when the initrd did+ not mount the runtime image+ * - ``After``+ - ``local-fs.target``, ``systemd-tpm2-setup-early.service``,+ ``systemd-pcrnvdone.service``+ * - ``Before``+ - ``sysinit.target``, ``shutdown.target``+ * - ``Conflicts``+ - ``shutdown.target``+ * - ``RequiresMountsFor``+ - ``/var/lib/shirudo``+ * - ``DefaultDependencies``+ - ``no``+ * - ``KeyringMode``+ - ``inherit``+ * - ``LimitMEMLOCK``+ - ``infinity``+ * - ``WantedBy``+ - ``sysinit.target``++Runtime drop-in+~~~~~~~~~~~~~~~++``shirudo-gen-runtime --unit-output <file>`` writes a drop-in for+``shirudo.service`` to ``<file>`` when it builds the runtime image. It+clears ``EnvironmentFile=`` and ``ExecStart=`` and runs ``init`` from the+runtime image. For a static target binary:++.. code-block:: ini++ [Service]+ EnvironmentFile=+ ExecStart=+ ExecStart=/run/shirudo/runtime/usr/bin/shirudo init++For a dynamic binary the drop-in starts the image's own ELF interpreter:++.. code-block:: ini++ [Service]+ EnvironmentFile=+ ExecStart=+ ExecStart=/run/shirudo/runtime<interpreter> --inhibit-cache --library-path <library-path> /run/shirudo/runtime/usr/bin/shirudo init++``<interpreter>`` is the binary's ELF interpreter path and+``<library-path>`` the colon-separated library directories under+``/run/shirudo/runtime`` that the generator copied. With the drop-in+installed, ``/etc/shirudo/init.env`` and ``SHIRUDO_INIT_ARGS`` have no+effect.++The generator writes this drop-in for ``shirudo.service`` only. The+keepalive, map-export, repository-update and tree-sync services run+``@bindir@/shirudo``. On a target that enforces, a shirudo binary outside+the runtime image is refused with ``shirudo: image state: Permission+denied`` and exit status 1, so each of these services needs its own+drop-in whose ``ExecStart=`` runs the runtime image's binary. See+:doc:`/operate/boot-integration`.++shirudo-keepalive.service+-------------------------++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Setting+ - Value+ * - ``ExecStart``+ - ``@bindir@/shirudo status --otel --include-system``+ * - ``EnvironmentFile``+ - ``-/etc/shirudo/map-export.env`` (optional)+ * - ``After``+ - ``shirudo.service``+ * - ``TimeoutStartSec``+ - ``2min``+ * - ``LimitMEMLOCK``+ - ``infinity``++The keepalive is sent only when ``map_export.otel_endpoint``,+``OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`` or ``OTEL_EXPORTER_OTLP_ENDPOINT``+names an endpoint. See :doc:`/reference/formats/otlp`.++shirudo-map-export.service+--------------------------++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Setting+ - Value+ * - ``ExecStart``+ - ``@bindir@/shirudo upatch map --all``+ * - ``EnvironmentFile``+ - ``-/etc/shirudo/map-export.env`` (optional)+ * - ``ConditionPathExists``+ - ``/run/shirudo/bpffs/lsm_link``+ * - ``After``+ - ``shirudo.service``+ * - ``TimeoutStartSec``+ - ``5min``+ * - ``LimitMEMLOCK``+ - ``infinity``++The destinations come from the ``map_export.*`` settings, see+:doc:`/reference/formats/configuration`.++shirudo-bpm-repo-update.service+-------------------------------++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Setting+ - Value+ * - ``ExecStart``+ - ``-@bindir@/shirudo bpm repo update`` (a failure is ignored), then+ ``@bindir@/shirudo bpm upgrade``+ * - ``EnvironmentFile``+ - ``-/etc/shirudo/bpm/environment`` (optional)+ * - ``Wants``+ - ``network-online.target``+ * - ``After``+ - ``network-online.target``, ``shirudo.service``+ * - ``RequiresMountsFor``+ - ``/etc/shirudo/bpm``, ``/var/lib/shirudo``+ * - ``TimeoutStartSec``+ - ``30min``+ * - ``LimitMEMLOCK``+ - ``infinity``++``bpm repo update`` refreshes the index of every repository in+``registries.d``. ``bpm upgrade`` then installs, for every package+installed from a repository, the highest version in its cached index+when that version is newer than the installed one. A package pulled+directly is left alone. See+:doc:`/operate/deliver-packages`.++shirudo-bpm-tree-sync.service+-----------------------------++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Setting+ - Value+ * - ``ExecStart``+ - ``@bindir@/shirudo bpm tree sync``+ * - ``EnvironmentFile``+ - ``-/etc/shirudo/bpm/environment`` (optional)+ * - ``Wants``+ - ``network-online.target``+ * - ``After``+ - ``network-online.target``, ``shirudo.service``+ * - ``RequiresMountsFor``+ - ``/etc/shirudo/bpm``, ``/var/lib/shirudo``+ * - ``TimeoutStartSec``+ - ``30min``+ * - ``LimitMEMLOCK``+ - ``infinity``++``bpm tree sync`` exits 0 without contacting a registry when no+``upatch-tree.conf`` is configured.++Timers+------++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Timer+ - Schedule+ * - ``shirudo-keepalive.timer``+ - ``OnBootSec=5s``, ``OnUnitInactiveSec=5s``, ``AccuracySec=1s``+ * - ``shirudo-map-export.timer``+ - ``OnBootSec=5s``, ``OnUnitInactiveSec=5s``, ``AccuracySec=1s``+ * - ``shirudo-bpm-repo-update.timer``+ - ``OnBootSec=0s``, ``OnUnitInactiveSec=60s``, ``AccuracySec=1s``+ * - ``shirudo-bpm-tree-sync.timer``+ - ``OnBootSec=60s``, ``OnUnitActiveSec=60s``, ``Persistent=true``,+ ``AccuracySec=1s``++Each timer starts the service of the same name and is+``WantedBy=timers.target``. ``OnUnitInactiveSec=`` counts from the end of+the previous run, ``OnUnitActiveSec=`` from its start.++Memory lock+-----------++Every ``shirudo`` and ``shirudo-build`` process calls ``mlockall()``+before it dispatches a command and exits with status 1 when that fails+(``hardening: cannot lock process memory``). Every service sets+``LimitMEMLOCK=infinity`` for that reason.++Enablement+----------++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Installer+ - What it enables+ * - Target ``.deb`` and ``.rpm``+ - On install: ``systemctl enable`` of ``shirudo.service`` and the+ four timers, for the next boot. Nothing is started. On removal:+ ``disable --now`` of the four timers and ``disable`` of+ ``shirudo.service``.+ * - Target tarball (``install.sh``)+ - ``systemctl daemon-reload`` only.+ * - dracut module ``90shirudo``+ - ``shirudo-initrd.service``, inside the initrd it builds.++The operator package installs no units.++Related+-------++- :doc:`/reference/environment` for the variables the+ ``EnvironmentFile=`` files set.+- :doc:`/reference/formats/configuration` for the settings the services+ read.+- :doc:`/reference/cli/init`, :doc:`/reference/cli/status`,+ :doc:`/reference/cli/upatch-map` and :doc:`/reference/cli/bpm` for the+ commands the services run.+- :doc:`/operate/boot-integration` for installing the units with the+ runtime image.diff --git a/Documentation/reference/versions.rst b/Documentation/reference/versions.rstnew file mode 100644index 00000000..b3693652--- /dev/null+++ b/Documentation/reference/versions.rst@@ -0,0 +1,270 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: All readers++Versions and compatibility+==========================++What identifies a build of shirudo, which format and schema numbers its+files and documents carry, what each reader does with them, and which+mixes of builds work together.++Releases+--------++There is no shirudo release. ``main`` is the development branch, and no+stable branches are maintained. Every push to ``main`` builds the+packages in the ``Build packages`` workflow, where they are available as+run artifacts. Until a release, no format below carries a compatibility+promise.++Version string+--------------++``shirudo version`` prints the version string and the version ID+(:doc:`/reference/cli/version`)::++ shirudo (<describe><extraversion>, "<release-name>")+ version-id: <version-id>++.. list-table::+ :header-rows: 1+ :widths: 26 74++ * - Part+ - Source+ * - ``<describe>``+ - ``git describe --tags --always --dirty`` of the build tree, or+ the content of the ``VERSION`` file, ``0.0.0-dev``, outside a git+ checkout. Without tags, describe prints the abbreviated commit,+ with ``-dirty`` for uncommitted changes.+ * - ``<extraversion>``+ - ``EXTRAVERSION`` in the top-level ``Makefile``, ``-rc0``.+ * - ``<release-name>``+ - ``NAME`` in the top-level ``Makefile``.++The package versions in ``packaging/Makefile`` derive from the same+describe string. ``<describe>`` alone, without ``<extraversion>``,+appears as ``service.version`` and the scope version in OTLP documents+(:doc:`/reference/formats/otlp`) and as ``bpm_version`` and+``shirudo.version`` in a package's ``build-environment.json``.++Version ID+----------++``SHIRUDO_VERSION_ID`` is the SHA-256 that the build writes into the+generated ``util/version_id.c`` (``Makefile.shirudo``). Its input:++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Input+ - Value+ * - Revision+ - ``git rev-parse HEAD``, or the content of ``VERSION`` outside a+ git checkout.+ * - Dirty mark+ - ``-dirty`` when ``git diff-index HEAD`` reports a change to a+ tracked file. Untracked files do not count.+ * - Build configuration+ - The first 16 hexadecimal digits of a SHA-256 over the checksums of+ ``config.mk`` and ``Makefile.shirudo``.++``config.mk`` is the operator profile's configuration, which the+feature probes in ``Makefile.config`` write. It records the compiler and+linker flags of the libraries on the build host, with their paths. The+target profile writes its configuration to ``config-target.mk``, which+the ID does not cover: a target binary's ID takes the ``config.mk`` of+the tree it was built in, or ``Makefile.shirudo`` alone in a tree+without one, as after ``make clean`` and ``make target``.++Two builds of one commit therefore get different IDs when their trees+hold different ``config.mk`` files, for example an operator package+built on its distribution and a target package built on another host.+``make`` and ``make target`` in one tree give both binaries the same ID.+Outside a git checkout, every build of the same ``VERSION`` with the+same ``config.mk`` gets the same ID.++The ID does not cover the compiler and its version, the contents of the+libraries, the generated ``vendor/linux/vmlinux.h`` that the BPF objects+compile against, untracked files, ``EXTRAVERSION`` or the release name.++Where it appears and what checks it:++.. list-table::+ :header-rows: 1+ :widths: 42 58++ * - Place+ - Use+ * - ``shirudo version``, ``shirudo version --version-id``+ - Printed.+ * - ``shirudo status``, ``version_id`` in ``status --json``+ - Printed.+ * - ``version_id`` in an evidence document+ - Written by ``attest``. ``attest verify`` does not compare it.+ * - ``upatch load`` and ``upatch unload`` with+ ``--expect-version-id=<hex>``+ - Compared with the target binary's ID. A difference refuses the+ command in phase ``pre_flight`` with ``version_mismatch``+ (``EPERM``). Without the option, or with+ ``--no-version-check``, nothing is compared.++The ID keeps an operator and a target of different builds apart when the+operator asks for it. It authenticates nothing (R5 in+:doc:`/security/threat-model`). :doc:`/operate/upgrade` says where to+take the expected ID from.++Format and schema numbers+-------------------------++A number names the layout its writer used. No reader converts one+layout into another, and readers ignore JSON keys they do not know.++Artifacts and published documents, which the operator writes and the+target reads:++.. list-table::+ :header-rows: 1+ :widths: 30 12 58++ * - Structure+ - Number+ - Reader on another value+ * - ``.upatch`` container header ``version``+ - 1+ - The target rejects the file. The section versions are in+ :doc:`/reference/formats/upatch-format`.+ * - Repository index ``schema``+ - 1+ - The target refuses the index (``EINVAL``).+ * - Tree publication ``schema``+ - 2+ - The target refuses the publication (``EINVAL``).+ * - ``build-environment.json`` ``format_version``+ - 1+ - Not checked.++:doc:`/reference/formats/bpm-formats` describes the package, index and+tree documents.++Documents the target writes for operators, collectors and scripts:++.. list-table::+ :header-rows: 1+ :widths: 30 12 58++ * - Document+ - Number+ - Reader on another value+ * - Eventlog record ``schema``+ - 2+ - Not checked by ``status``, ``init``, ``attest`` or ``attest+ verify``. See :doc:`/reference/formats/eventlog`.+ * - Evidence document ``schema``, with ``kind``+ ``shirudo-attestation``+ - 1+ - Neither is checked by ``attest verify``.+ * - ``config`` block of an evidence document, ``schema``+ - 1+ - ``attest verify`` refuses the document (``EINVAL``).+ * - Credential from ``attest challenge``, ``schema``, with ``kind``+ ``shirudo-credential``+ - 1+ - ``attest --challenge`` requires the ``kind`` and does not check+ ``schema``.+ * - ``status --json``+ - 1+ - For consumers. See :doc:`/reference/formats/status-json`.+ * - Operation report of ``upatch load`` and ``upatch unload``, report+ of ``bpm tree sync``+ - 1+ - For consumers. See :doc:`/reference/failure-categories`.+ * - ``--json`` output of ``upatch info``, ``upatch list``, ``upatch+ get`` and ``upatch map``+ - 1+ - For consumers.++State the target keeps for itself:++.. list-table::+ :header-rows: 1+ :widths: 30 12 58++ * - File+ - Number+ - Reader on another value+ * - Config activation records under ``/var/lib/shirudo/config-update``+ - 1+ - Refused as malformed (``EBADMSG``). The active config can then+ not be verified, and commands stop with ``shirudo: image state:``+ and the error.+ * - ``state.json`` and ``pending.json`` of the upatch tree+ - 1+ - Refused by ``bpm tree sync``.++Configuration and bootstrap files carry no version. Unknown keys in the+two bootstrap files and the host file draw a warning, and a config image+whose ``shirudo.conf`` holds a key other than ``eventlog.max_bytes`` or+``map_export.*`` is refused (:doc:`/reference/formats/configuration`).+The config image's hash tree must carry the standard ``veritysetup``+superblock, version 1, with hash type 1, SHA-256, 4096-byte blocks and a+32-byte salt.++Kernel ABI+----------++shirudo needs the signed-loader ABI of the bpf-next tree it targets and+the ``tpm_command`` LSM hook that it carries as a kernel patch. A+release number does not identify such a kernel. The pre-flight check+``signed_loader_kernel_abi`` reads the running kernel's BTF, and a load+on a kernel without the ABI fails with ``kernel_abi_unsupported``.+:doc:`/operate/system-requirements` lists the kernel requirements and how+to identify a kernel, :doc:`/internals/kernel-interfaces` every interface+shirudo uses, and :doc:`/internals/kernel-patches` the carried patches.++Mixing builds+-------------++No command negotiates a version with another build, and only+``--expect-version-id`` compares two builds. Keep the operator and every+target on builds of the same commit.++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Combination+ - Behavior+ * - Initrd binary and runtime image binary+ - Must be the same build (:doc:`/operate/boot-integration`).+ Nothing compares their IDs. The runtime binary reads the identity+ map and the tamper counters that the initrd's ``init`` pinned and+ refuses maps whose layout differs from its own: a different+ identity layout stops every command with ``shirudo: image state:+ Protocol error``.+ * - Operator artifacts on a target of another build+ - Load when a key the target trusts signed them, the container and+ section versions match, and the target kernel accepts the signed+ loader. The target does not check which build produced an+ artifact or a package.+ * - ``attest predict`` and ``attest verify`` against evidence from+ another build+ - Work as long as both builds compute event digests and the+ register the same way. Nothing checks that.+ * - ``shirudo`` and the ``shirudo-build`` helper+ - ``shirudo`` runs the helper that ``SHIRUDO_BUILD`` names, else+ ``/usr/libexec/shirudo/shirudo-build`` (the compiled-in libexec+ path), else the first on ``PATH``, and does not compare versions.++Related+-------++- :doc:`/operate/upgrade`+- :doc:`/reference/cli/version`+- :doc:`/reference/formats/index`+- :doc:`/operate/system-requirements`diff --git a/Documentation/requirements.in b/Documentation/requirements.innew file mode 100644index 00000000..7d157898--- /dev/null+++ b/Documentation/requirements.in@@ -0,0 +1,7 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# The documentation toolchain. requirements.txt is generated from this+# file with pip-compile --generate-hashes --strip-extras --allow-unsafe.+sphinx==9.1.1+myst-parser==5.1.0diff --git a/Documentation/requirements.rst b/Documentation/requirements.rstdeleted file mode 100644index f73f2ae0..00000000--- a/Documentation/requirements.rst+++ /dev/null@@ -1,471 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--System requirements-===================--This is the single list of what a host needs before shirudo is built,-installed or initialised on it. The operator and target roles have-different needs; a development host that plays both needs the union.-shirudo requires the signed-loader ABI and BPF LSM interfaces in the-validated upstream development kernel, plus a current toolchain. Missing-features fail at build or pre-flight time; there is no compatibility mode.--1) Target kernel-------------------The signed-loader ABI is present at upstream bpf-next commit-``0867b7bfa9de65674c6e599fa21b762b71011b14``, which reports a-``7.3.0-rc5``-based release string in the initial validation build. Image mode-also requires the upstream keyring-ID API described below. A released-version-minimum has not been established by this validation, so a release number-alone is not an admission check.--``shirudo init`` checks the running kernel's signed-loader support through-``signed_loader_kernel_abi`` and refuses an incompatible ABI. Such a load-reports ``kernel_abi_unsupported``. Build against the target kernel's BTF-and keep the configuration below; passing this ABI check alone does not-establish that every optional upatch attach point is available.--The table below is what shirudo itself needs; without any of it,-``shirudo init`` does not complete. The test VM kernel uses the slim-configuration embedded in ``testing/vm/build-kernel.sh``. It also-builds the networking modules used by the VM test setup: veth, bridge,-802.1Q, and the netfilter flow table. It also enables IPv6 for the kernel-obs-fixture.--.. list-table::- :header-rows: 1- :widths: 34 66-- * - Option- - Why shirudo needs it- * - ``CONFIG_BPF``, ``CONFIG_BPF_SYSCALL``, ``CONFIG_BPF_JIT``- - The ``bpf()`` syscall, the JIT and bpffs, for the loaders, the- enforcement programs and the private pin mount.- * - ``CONFIG_BPF_LSM``, ``CONFIG_BPF_EVENTS``, ``CONFIG_SECURITY``,- ``bpf`` in ``CONFIG_LSM`` (or ``lsm=`` on the kernel command line)- - The ``lsm/bpf`` and ``lsm/bpf_prog_load`` gates, the bpffs and- mount guards, and the filesystem seal are all BPF LSM programs.- ``CONFIG_BPF_EVENTS`` is listed because ``CONFIG_BPF_LSM``- depends on it, not for tracing.- * - ``CONFIG_FUNCTION_TRACER``,- ``CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS``- - Base, not an attach-point option: shirudo's own enforcement- programs attach through BPF trampolines, and a trampoline is- installed at the function entry that function tracing- reserves, through an ftrace direct call. Without function- tracing there is no entry to patch; with tracing but without- direct calls the kernel refuses every trampoline attach with- ``ENOTSUPP``. Either way ``shirudo init`` cannot attach its- enforcement. The same trampolines later carry ``fentry``,- ``fexit``, ``fmod_ret`` and ``lsm`` upatches at no extra cost.- * - ``CONFIG_SECURITYFS``- - ``/sys/kernel/security/lsm``, which the pre-flight reads to- confirm the BPF LSM is active (``bpf_lsm_active``).- * - ``CONFIG_DEBUG_INFO_BTF``- - CO-RE relocation of every shipped and user-built BPF program,- ``vmlinux.h`` generation, and the ABI check above.- * - ``CONFIG_KEYS``, ``CONFIG_ASYMMETRIC_KEY_TYPE``,- ``CONFIG_ASYMMETRIC_PUBLIC_KEY_SUBTYPE``- - The kernel's bpf keyring (``KEY_SPEC_BPF_KEYRING``), which- holds the operator certificate once ``init`` has enrolled it- and sealed it. The kernel is booted with- ``bpf.keyring_unsealed=1`` so that the keyring takes the- certificate from the initrd; booted without, it is sealed- empty. Shirudo refuses initialization until reboot with the- enrollment parameter; it has no user-keyring fallback.-- * - ``CONFIG_X509_CERTIFICATE_PARSER``,- ``CONFIG_PKCS7_MESSAGE_PARSER``,- ``CONFIG_SYSTEM_DATA_VERIFICATION``- - Parsing ``cert.der`` at ``add_key(2)`` and verifying the- detached CMS signature at ``BPF_PROG_LOAD``. The last one is- usually pulled in by module signing or IMA; set it explicitly- on a kernel that has neither.- * - ``CONFIG_CRYPTO_MLDSA``- - Verification of ML-DSA-87 (FIPS 204) signatures and- certificates, the only kind shirudo produces. Without it the- kernel rejects the certificate at ``add_key(2)``; ``shirudo- init`` reports the ``cert_kernel_support`` pre-flight failure- and a load reports ``signature_unsupported``.- * - ``CONFIG_CRYPTO_SHA512``- - The signed-attributes digest OpenSSL 3.x emits next to an- ML-DSA signature; ``CONFIG_CRYPTO_MLDSA`` does not select it.- * - ``CONFIG_CRYPTO_SHA256``- - ``excl_prog_hash``, ``payload_sha256``, the measurement register- and the eventlog digests.- * - Kernel ``tpm_command`` LSM hook- - The hook passes a copied command and its declared length before- submission through either TPM device node. Shirudo refuses an- untrusted ``TPM2_NV_Extend`` to its frozen NV index, including- through an inherited descriptor. It allows other TPM signing- and PCR extension. The TPM must create and use RSA-3072- RSASSA/SHA-256 primary keys; there is no RSA-2048 fallback.- * - ``CONFIG_TCG_TPM`` plus a TPM driver (``CONFIG_TCG_TIS``,- ``CONFIG_TCG_CRB``, or the platform's virtual TPM)- - The measurement register and the attestation key. A TPM 2.0 is- mandatory; there is no unmeasured mode. ``testing/swtpm.sh``- provides a software TPM for machines without one.- * - ``CONFIG_EXT4_FS_SECURITY`` (when ``/var/lib/shirudo`` is on ext4)- - Allows ``init`` to store the ``security.bpf.shirudo`` label used by- the filesystem seal, and the seal to write it on a new inode- inside the transaction that creates it. Other filesystems hosting- this state must support security xattrs, at creation included.- * - ``CONFIG_TMPFS_XATTR``- - The label on ``/run/shirudo`` and on the init record an initrd- run leaves there for the root file system's run.--``CONFIG_PKCS7_WAIVE_AUTHATTRS_REJECTION_FOR_MLDSA`` is not required: it-only relaxes module-signature checks, and BPF signature verification-accepts the signed-attributes form.--``CONFIG_KEXEC`` and ``CONFIG_KEXEC_FILE`` may stay enabled: the LSM-refuses every kexec load (``Kexec``, threat T6 of the threat model),-since a kexec would carry this boot's TPM state under a kernel of-root's choosing.--``CONFIG_MODULE_SIG_FORCE``, or ``CONFIG_SECURITY_LOCKDOWN_LSM`` in-integrity mode, on a kernel with ``CONFIG_MODULES``: an unsigned module-root loads replaces the kernel under shirudo, and nothing in shirudo-refuses or measures it. The test kernel does without, as its own-modules are unsigned.--Image-mode requirements-~~~~~~~~~~~~~~~~~~~~~~~--Image mode supports 64-bit userspace only. Disable 32-bit compatibility-(``CONFIG_COMPAT=n``); on x86-64, disable ``CONFIG_IA32_EMULATION`` and-``CONFIG_X86_X32_ABI``. The device-mapper and perf event restrictions-hook both ``file_ioctl`` and ``file_ioctl_compat``, but 32-bit callers are-not otherwise considered.--Every target also requires ``CONFIG_BLK_DEV_DM``,-``CONFIG_DM_VERITY``, ``CONFIG_BLK_DEV_LOOP`` and ``CONFIG_EXT4_FS``. Runtime-and config mappings use verity format 1, SHA-256, 4096-byte blocks and a-standard verity superblock. ``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG`` is-required for the config root signature. The kernel must provide the-``.dm-verity`` keyring enrollment and sealing API, including-``KEY_SPEC_DM_VERITY_KEYRING``, merged for Linux 7.4 as commit-1041fca2ee8a (``keys: add KEY_SPEC_DM_VERITY_KEYRING``).-Image boot uses-``dm_verity.keyring_unsealed=1`` so the trusted initrd can enroll its config-certificate and seal that keyring. Built-in trusted certificates remain-part of the kernel's dm-verity trust path. The runtime must match the exact-UKI-authenticated root; config-signing trust does not authorize executables.--Image enforcement uses existing upstream LSM hooks. Existing hooks do not establish every desired protection against-hostile device-mapper controls or mount-tree changes; see the limitations in-`config-images <config-images.rst>`__. BPF signing keys are enrolled at boot-before reject-all keyring sealing. Missing image settings stop initialization.--Production image mode requires authenticated measured UKI boot, the-runtime root hash in authenticated bootstrap settings, a reserved static-SHA-256 PCR outside the existing PCR 9/11 binding, and writable Shirudo state-mounted in the initrd. All executable loader and library dependencies must-be inside the runtime image. The operator image generators additionally-need ``mkfs.ext4`` from ``e2fsprogs`` and ``veritysetup`` from-``cryptsetup-bin`` (Debian/Ubuntu) or ``cryptsetup`` (Fedora/RHEL).-Offline ``shirudo image verify`` also requires the operator build helper-and ``veritysetup``. Targets need none of these external tools: they-validate authenticated metadata and read the entire strict dm-verity-mapping through kernel APIs before accepting image contents.--Attach points for upatches-~~~~~~~~~~~~~~~~~~~~~~~~~~--Everything from here on is optional. shirudo itself runs without any-of it; these options only decide where the upatches an operator ships-can attach. ``fentry``, ``fexit``, ``lsm`` and ``tp_btf`` upatches-attach through the trampolines and BTF the base table already-requires for shirudo itself, and-``fmod_ret`` works on the ``security_*`` hooks without anything more.-Enable the rest for the kinds of upatch a fleet will run. An upatch-that needs a missing one fails at load with the kernel's error in the-report; it never attaches somewhere else.--.. list-table::- :header-rows: 1- :widths: 34 66-- * - Option- - What it enables- * - ``CONFIG_KPROBES``, ``CONFIG_KPROBE_EVENTS``- - ``kprobe`` and ``kretprobe`` upatches on arbitrary kernel- functions.- * - ``CONFIG_FUNCTION_ERROR_INJECTION``,- ``CONFIG_BPF_KPROBE_OVERRIDE``- - ``fmod_ret`` on functions outside the ``security_*`` hooks- (those marked ``ALLOW_ERROR_INJECTION``) and- ``bpf_override_return()`` from a kprobe: the two ways a shield- rejects a call before the function body runs.- * - ``CONFIG_UPROBE_EVENTS`` (selects ``CONFIG_UPROBES``)- - ``uprobe.multi`` upatches against userspace binaries.- * - ``CONFIG_CGROUP_BPF``- - ``cgroup_skb`` upatches on the cgroup v2 root.- * - ``CONFIG_NETFILTER``, ``CONFIG_NETFILTER_BPF_LINK``- - ``netfilter`` upatches at IPv6 pre-routing.--2) Operator kernel---------------------The operator kernel needs nothing from the tables above. Building and-signing never touch ``bpf()``: ``shirudo build`` compiles with clang,-runs libbpf's gen_loader, which records map creation, program loads,-CO-RE relocations and attach targets for the signed loader to perform-on the target kernel, and signs the result with libcrypto. No BPF-program is loaded on the operator, the operator kernel's BTF is not-consulted, and no capability is needed. ``shirudo bpm build``, ``push``-and ``tree append`` wrap that path and talk to a registry. Any Linux-kernel that a current clang and OpenSSL 3.5 run on will do.--.. list-table::- :header-rows: 1- :widths: 34 66-- * - Operator activity- - Kernel requirement- * - Build and sign upatches; build and publish packages and trees- (``shirudo build``, ``shirudo bpm build``, ``push``,- ``tree append``)- - None. No BPF is loaded and no kernel BTF is read; the target- kernel's ``vmlinux.h`` is the only kernel-derived input, see- below.- * - Inspect artifacts and packages offline (``shirudo upatch info``,- ``shirudo bpm info``)- - None.- * - Build or verify signed images offline (``shirudo image build``,- ``shirudo image verify``)- - No loaded DM target or root privilege. The operator helper uses- ``veritysetup format`` and ``veritysetup verify`` on regular files.- * - Craft and test mitigations: reproduce the bug, load the shield,- run the reproducer against it- - A kernel that mimics the target: the fleet's release,- configuration and BTF, meeting the base and attach-point tables- of the target kernel, preferably in a VM.- * - Operator and target on one node (local development)- - The full target table; the node is a target.--``vmlinux.h`` is the one input the build takes from a kernel. By-default the tree generates it from the build host's own BTF-(``/sys/kernel/btf/vmlinux``) with ``tools/gen-vmlinux-h``. When the-fleet runs another kernel, generate it from that kernel's BTF-(``tools/gen-vmlinux-h <vmlinux or BTF file> > vmlinux.h``) and either-build the tree with ``BPF_VMLINUX_H=<path>`` or pass ``--vmlinux-<path>`` to ``shirudo build``. CO-RE makes the artifact portable-across builds of the same kernel generation, not across kernels that-renamed a field.--Mimic the target to craft mitigations. Building is where the operator-kernel's requirements end; crafting a mitigation is not. The agentic-loop the architecture describes (ingest the fix, reproduce it, derive a-shield, load it, run the reproducer against it) needs a kernel that-behaves like the fleet's: the same release and configuration, the same-BTF, the attach points the shield will use. Run that loop in a VM-booting the target kernel rather than on the operator host. ``make -C testing-kernel KERNEL_TAG=<tag> KERNEL_CONFIG=<the fleet's .config>`` builds-such a kernel with its BTF, ``make -C testing vm KERNEL=<version>`` boots a-release of v7.4 or newer with a software TPM and a prepared shirudo, and-``make tests`` runs the tests in it; any VM of the operator's-own serves the same purpose. A mitigation that loads and passes its-reproducer on a kernel unlike the fleet's proves nothing about the-fleet.--The test VM runs under KVM and so has the architecture of its host,-x86-64 or arm64; the kernel image is ``bzImage`` or ``Image`` to match.-On a Fedora or RHEL host the scripts print RPM package names for a-missing tool and build the kernel as an RPM. Where ``cloud-localds`` is-not packaged, ``xorriso`` or ``genisoimage`` builds the cloud-init seed-instead, and ``TEST_VM_QEMU`` names the emulator on a host that has no-``qemu-system-<arch>`` binary, such as ``/usr/libexec/qemu-kvm``. The-runtime image installs its packages through the caller's ``http_proxy``-or ``TEST_VM_APT_PROXY``; a proxy that only the host's ``/etc/hosts``-names must be given by address, as in ``http://[2001:db8::1]:8080``,-since the libguestfs appliance resolves names through DNS alone.--3) Cryptography------------------.. list-table::- :header-rows: 1- :widths: 30 70-- * - Use- - Algorithm- * - Signing key and certificate- - ML-DSA-87 (FIPS 204, NIST category 5) and nothing else:- ``shirudo genkey`` has no algorithm option, the builder refuses- a classical key, the target pre-flight refuses a classical- certificate. The smaller ML-DSA parameter sets are not offered:- a fleet-wide trust anchor gets the largest margin for about- 2 KiB more per signature. The certificate is self-signed with- the same key.- * - ``.upatch`` loader signature- - Detached CMS over ``loader_insns || data``. With OpenSSL 3.x the- SignerInfo carries signed attributes and a SHA-512 message- digest; OpenSSL 4 signs the content directly. The kernel- verifies both forms; see `upatch-spec <upatch-spec.rst>`__.- * - BPM index and upatch-tree signatures- - Detached CMS in the same form, produced by ``shirudo-build`` on- behalf of ``shirudo bpm push`` and ``shirudo bpm tree append``,- verified on the target with libcrypto against the registered- certificate.- * - Payload, program and register digests- - SHA-256: ``payload_sha256``, ``excl_prog_hash``, the measurement- register, its policy and the eventlog.- * - TPM attestation- - ECDSA P-256 (the attestation key); TPMs sign with nothing- post-quantum today, so the evidence is classical.- * - NV write authorization- - RSA-3072 RSASSA-PKCS1-v1_5 with SHA-256 through- ``PolicySigned``. The TPM holds the private key. Shirudo freezes- the public modulus and the input used to recreate the same- primary key during this boot.- * - TLS (registries, OTLP and S3 export)- - TLS 1.3 on every libcurl client in both profiles. Hybrid ML-KEM- groups (X25519MLKEM768, SecP256r1MLKEM768) are required unless- an exact host is opted in through ``tls.classical_hosts`` in the- root-managed operator config or immutable target runtime config.- The exception does not change certificate verification. Server- certificates are whatever the registry or collector presents.--4) Operator host-------------------* A C toolchain (``cc``, ``make``, ``pkg-config``). A compiler warning- fails the build; ``make WERROR=0`` lets a compiler newer than the tree- finish it.-* Current upstream ``clang`` and ``llvm`` with the BPF target, for- ``shirudo build`` and the embedded enforcement programs.-* OpenSSL 3.5 or newer: ``libcrypto`` and ``libssl`` development files- and the ``openssl`` command. 3.5 is the first release with ML-DSA;- the build probe refuses older versions.-* ``libelf``, ``zlib``, ``libcurl`` 7.75 or newer, ``libluajit-5.1``- and tpm2-tss (``tss2-esys`` 4.0 or newer, ``tss2-tctildr``)- development files.-* No kernel tree: libbpf, its BPF-side headers and the BPF UAPI headers- are vendored under ``vendor/libbpf``, and ``vmlinux.h`` is generated- by the in-tree ``tools/gen-vmlinux-h`` into ``vendor/linux/`` (never- committed), so neither a submodule nor bpftool is needed. ``make- bpf-deps`` refreshes the vendored copy from a kernel tree on- demand.-* Bash and GNU coreutils for operator image generation.-* ``veritysetup`` for image formatting and offline verification, provided- by ``cryptsetup-bin`` on Debian/Ubuntu or ``cryptsetup`` on Fedora/RHEL.- Directory-to-image generators additionally require ``mkfs.ext4`` from- ``e2fsprogs``. The operator package depends on the verity tool; target- packages and initrds do not.-* Packages, indexes and trees are built and published through the same- ``shirudo-build`` helper.--The operator never needs a TPM, the kernel keyring or ``CAP_BPF``; only-the private key under ``/var/lib/shirudo/keys/``.--Both ``shirudo`` and ``shirudo-build`` lock all current and future-process mappings before command dispatch. Manual invocations and host-tests need ``CAP_IPC_LOCK`` or a memory-lock limit large enough for the-process, its libraries, mapped artifacts and subsequent allocations.-Startup refuses to run if locking fails. The shipped systemd services-set ``LimitMEMLOCK=infinity``. Locks remain for the process lifetime;-an exec clears them and the operator helper applies its own hardening.--5) Target host-----------------* The kernel configuration above, booted with the BPF LSM enabled.-* Root (``CAP_SYS_ADMIN``, ``CAP_BPF``) for ``shirudo init`` and every- state-changing command.-* The target binary from ``make target`` links OpenSSL, libcurl,- tpm2-tss with its device TCTI, libbpf, libelf, zlib, zstd and- LuaJIT, glibc, libm and the compiler runtime statically as a PIE, so it- runs on a distribution whose own OpenSSL predates ML-DSA and reaches- the TPM from an initrd that holds no tpm2-tss shared objects.-* A TPM 2.0 exposed through the kernel device TCTI (discrete,- firmware or cloud vTPM). Authenticated-image targets use that path so- the LSM can check NV extension commands. Host tests may use a software- TPM through another TCTI. TPM 1.2 is refused; there is no opt-out.-* ``systemd`` 256 or newer for the boot units and the timers:- ``shirudo-initrd.service`` orders itself after ``tpm2.target``, which- an older systemd does not have, and ``init`` could then run before- the TPM is there. The test suite runs systemd 259. A systemd-based- initrd (dracut) for the production configuration, with- ``systemd-pcrphase-initrd.service``, which measures ``enter-initrd``- and ``leave-initrd`` into PCR 11: the register's binding closes when- the second one lands, so without the phase measurements an initrd- binding is no stronger than a late one. The ``initrd`` document- lists what the initrd must contain.-* x86-64, arm64 or riscv64.--Operator and target may be on different architectures; the artifact-format is little-endian and the signature is architecture-neutral.--6) Build host for the target binary--------------------------------------``make target`` runs ``make target-deps`` first, which builds OpenSSL,-an OpenSSL-backed libcurl and tpm2-tss from source and stages them as-static archives. The build host then needs static ``libelf``,-``zlib``, ``zstd`` and ``libluajit-5.1`` archives;-``SHIRUDO_TARGET_STATIC_LIBDIR`` names their directory when it is not-the system one. The configured C compiler must also provide matching-static glibc, libm, startup objects and compiler runtime archives with-static PIE support (``libc6-dev`` on Debian-family hosts,-``glibc-static`` on Fedora). These come from that compiler's sysroot,-not ``SHIRUDO_TARGET_STATIC_LIBDIR``. Missing or incompatible archives-fail configuration; the target never falls back to shared libraries.-The operator package, by contrast, links the host's-shared libraries and must be built on the distribution it is installed-on.--The target ELF has no interpreter, shared-library dependencies or-library search paths. Its static PIE startup relocates it without-``ld-linux``, retaining address randomisation, and ignores-``LD_PRELOAD``. This describes the ELF linkage, not a prohibition on-runtime module loading: glibc's NSS and explicit ``dlopen`` paths may-still load shared objects. The build's glibc linker warnings for those-interfaces must not be mistaken for an ELF dependency.--Both installer tarball names remain available and carry the same target-executable, without bundled shared libraries. The package SBOMs include-the embedded glibc and compiler runtime versions as well as the other-static dependencies. glibc retains its LGPL licence and notices; the-GCC runtime retains its runtime exception. The project's source licence-does not replace those dependency licences. To rebuild or relink the-target, use the source revision and dependency versions recorded with-the release, supply the replacement runtime through ``CC`` and its-sysroot, and run ``make target``. Retain that source, the build rules-and the dependency sources/notices with the distribution's relinking-materials. Rebuild the initrd and reboot after replacing the target-binary, as described in `operations <operations.rst>`__.--7) Development kernel baseline----------------------------------Use the upstream development-tree ABI and options described above. Image-mode uses existing LSM hooks. A kernel predating-``KEY_SPEC_DM_VERITY_KEYRING`` needs commit 1041fca2ee8a above. The-`config-images <config-images.rst>`__ guide describes the two policy modes,-test commands and remaining protection gaps. Run both complete policy-mode-suites when validating a deployment.--8) Documentation and tests-----------------------------* ``make -C Documentation html-docs`` renders the documents with- docutils' ``rst2html`` (``python3-docutils``).-* The operator tests, ``make tests VM=0``, run their Python- helpers on the standard library alone. With the ``cryptography``- module installed, ``testing/functional/tpm/t4001-tpm-wire.sh`` also- cross-checks the TPM credential blob it builds against an independent- implementation; without it that one check is skipped.-* ``make -C testing functional/tpm`` additionally needs libtpms- development headers on the build host (``libtpms-dev`` on Debian and- Ubuntu). The prepared guest installs libtpms and the command TCTI- runtime. The guest uses the TPM-held NV writer and the kernel TPM- device, not a software signing replacement.-* ``make -C testing end2end`` runs an OCI registry and an OpenTelemetry- Collector in Docker containers beside the VM, and needs ``curl``.-* ``make -C testing fuzz`` builds the parsers' libFuzzer targets with- ``clang`` and needs its fuzzer and sanitizer runtime- (``libclang-rt-<version>-dev`` on Debian and Ubuntu).diff --git a/Documentation/requirements.txt b/Documentation/requirements.txtnew file mode 100644index 00000000..052e8853--- /dev/null+++ b/Documentation/requirements.txt@@ -0,0 +1,510 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# Generated from requirements.in by pip-compile --generate-hashes; do not edit.+alabaster==1.0.0 \+ --hash=sha256:c00dca57bca26fa62a6d7d0a9fcce65f3e026e9bfe33e9c538fd3fbb2144fd9e \+ --hash=sha256:fc6786402dc3fcb2de3cabd5fe455a2db534b371124f1f21de8731783dec828b+ # via sphinx+babel==2.18.0 \+ --hash=sha256:b80b99a14bd085fcacfa15c9165f651fbb3406e66cc603abf11c5750937c992d \+ --hash=sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35+ # via sphinx+certifi==2026.10.23 \+ --hash=sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd \+ --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1+ # via requests+charset-normalizer==3.5.2 \+ --hash=sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e \+ --hash=sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf \+ --hash=sha256:04851f73ae72b8413dddadb16a49dfee95263553741fd42d546f7d66907e6be5 \+ --hash=sha256:0521c5665880b33d603717defa76c094048900010897909952397feb3039da56 \+ --hash=sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26 \+ --hash=sha256:0891b9d3903c5571c03771ca669a4b0ec5618ca722a5c957d3d29cd4e5062848 \+ --hash=sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718 \+ --hash=sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93 \+ --hash=sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640 \+ --hash=sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3 \+ --hash=sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875 \+ --hash=sha256:124fbf1a8ff966d87ae05bb8bd45a71f966055ed8bba320d0c7cf450bc5f4d0e \+ --hash=sha256:1461ac396c4fdb983a675f20aa555624f0ee18ac83d832b9244ffff3d8055275 \+ --hash=sha256:1503bccbeb36d5527790c3930327704c39af22de3112f1b1666a9f3ce15ee204 \+ --hash=sha256:15bb4005af6320d259dc7593ca84a38d7fe06a421dbcf7b910ae23979101e787 \+ --hash=sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234 \+ --hash=sha256:16fa0eccf81304b79c5cd87f9271c3b85dd9dd99245e4422ae9c0dd45e0f99d3 \+ --hash=sha256:183b88127acdb4fabe59d951ab424faf1af7b63cdbb5f776186c1ea2ffcaed98 \+ --hash=sha256:195c26fb65950f8fce54e26349852b7bdd7c5f120aeefbcc440b8a20faaed4a3 \+ --hash=sha256:1afb975bd5d68d5ce9f6b6d44fdf2f7e34b895a35e95708a7a91b20a3b51d187 \+ --hash=sha256:1b4cbc7c3491ccb4aa17fcd8165649d01cf39f76de1696da8631b5f71b85401d \+ --hash=sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f \+ --hash=sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7 \+ --hash=sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011 \+ --hash=sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f \+ --hash=sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869 \+ --hash=sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1 \+ --hash=sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d \+ --hash=sha256:281cb91036248400f4cc957495cccd44c275c2e0c5854f7e45ac5cf7dc193847 \+ --hash=sha256:28a15fdad492a99b6eccfaaed66ef3f74050680545ea61ec8b2f4c538f1f1320 \+ --hash=sha256:28b4f0d66fb834ff90f28209ac7bce77868c45d8c93e26f906709d9b7c2e1af9 \+ --hash=sha256:2a925889534b3748302dae5dead07cc13480de1dac3aea80a941b729b471ef93 \+ --hash=sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd \+ --hash=sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00 \+ --hash=sha256:2cc961b171b3f3440f410489ab3573e86aea8736134ebbb40ea1338b7f0831bc \+ --hash=sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0 \+ --hash=sha256:2e06a3a98f916dd41d27f3105e02e7a40181c98c94b9158733d03a6f80506c09 \+ --hash=sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac \+ --hash=sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621 \+ --hash=sha256:30fcd120b732aa79317f08dee04d7de0847822e4cf7ee0e9f445bb958832252c \+ --hash=sha256:31f3930700408d211f13378ccbe1c40845d8da54bd0681fac3a9b5aae81c7aa8 \+ --hash=sha256:34276fd796040bf0993ab33a369aa572e6979c7aab225a88893667ad8eac8f7a \+ --hash=sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51 \+ --hash=sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0 \+ --hash=sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef \+ --hash=sha256:3d14b50de6bf4d0edf857a9386836846f982b8f524e188e2e68b96d702bcf4aa \+ --hash=sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6 \+ --hash=sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649 \+ --hash=sha256:3ddacd27458c45bdacd6bd6db644bfb730efbf9e830310186e3045c9c5be8fb2 \+ --hash=sha256:3df041de8887954562c9b261cba85ca0e9ded74048daf125f45edcfaa4832229 \+ --hash=sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e \+ --hash=sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd \+ --hash=sha256:443eae2bf318abeaf6f15d785138f71fd6de770e99a92158b8b814265e079115 \+ --hash=sha256:447441e76ec720b15e64418d32e092297340387053047c7c694f579efb0ee1d9 \+ --hash=sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c \+ --hash=sha256:44bd4fbb29dfbeba60e7d2bd000c59e4b21ddb3cc53912b14048d37092706d7c \+ --hash=sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab \+ --hash=sha256:498dc3188ca05a68231ac3fdbfc7f57eb67e1343c30e0fea17f8218c1599b253 \+ --hash=sha256:4c2b5031f63e331e3839b40aed2dd6f191e9c07edbde303e7876846ea1946995 \+ --hash=sha256:4d48f2d08b9de5864e2c8744d4461b862fb149a18274abc8b698c45975573438 \+ --hash=sha256:4f87960d57feabfb618e4e0af6e7371645fa26a277860739d6e5d6e0012c92f0 \+ --hash=sha256:50e3adfb96fc189eb27b1cf62d3b598b89b4bb0420d93a3d3e42e137409011be \+ --hash=sha256:51cf45226a9b588d0d2b4880c62d686934b63ab0bd79ca23ab0e9762eb27441b \+ --hash=sha256:52aa6992700996af31f375de0c6bacd402b0097fe40b53c426b9f51a90ebabc7 \+ --hash=sha256:55ea99acb17b9325618de155a0cd6a2e8f5d10be008113e1d433bbb58db543b2 \+ --hash=sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a \+ --hash=sha256:588461c2e8384d309bd63e5826019b6977bc66d629b99ac8737bb795d7b2cb5a \+ --hash=sha256:58ca3755ee7ff7f59b57789ec9833c9de9ea275405cdd240eda1f193112e398a \+ --hash=sha256:58f361dcbab699cf8f42db3f47c8e7fd1036f138c23a5d08de9fde5f425a730c \+ --hash=sha256:598a11a2c7ebaa5334bf698bf29568c9c390abac6a154d8170fedecd1cea38c5 \+ --hash=sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37 \+ --hash=sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e \+ --hash=sha256:5e2b6b57e9733d39f0c9fd3185efa6b8e29652c4cd8fe94180272cf6ed9a78c4 \+ --hash=sha256:5fb29fb8cd1a46c27a1bf9613ad5ec2599310d46b4025d9556404a6b6a292800 \+ --hash=sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055 \+ --hash=sha256:619799369eeef6366ed3e8755a5670f4f2f0fb6b30a0fd7264dc0fdc2357058e \+ --hash=sha256:62588a277bfb59def052abd940703fa35107152bf479781a878617d60faf8fb5 \+ --hash=sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c \+ --hash=sha256:65cd72beeeca9d3aaea1201e5923859f308f952f9c71de93f06063c79f0f7a3b \+ --hash=sha256:68eb192d85ab8e5f6ec69c2bc6ac0179fbf04a5ac1569d12fbef74883fe102d0 \+ --hash=sha256:6bd128f206a7752ae1f2ab6c61bf8a24ba28913a10df8b14c2637b973ff97a80 \+ --hash=sha256:6be488a102b8cf28d0391d8c4ba7748938ae28b78ad901f8585520fca33ead1a \+ --hash=sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4 \+ --hash=sha256:7441d755b7ab94f8d4eb3e43ec05482d760842fd263d003a99102d742cd835e2 \+ --hash=sha256:749e97e1b32313717a565abbe321bc2190bc8b35f1a67e4cdbc7c56c8d8ffe58 \+ --hash=sha256:75a3ceed0724d625d64b86ca20aba182e4df462e04c2414fc941c0f523f06aac \+ --hash=sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc \+ --hash=sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639 \+ --hash=sha256:7967d08cf06dee78443b874f98c98036f624f3a4e73e11f9f64f5be4d25393cf \+ --hash=sha256:7a881931aa470808df94a8c380eed2bbbc76cd9dc622310f99665658c821eb6d \+ --hash=sha256:7dcd882da75ef9adf94903b1e3b9419e8aa8fb4c7396822b834b9ef7fb96954f \+ --hash=sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c \+ --hash=sha256:7fdde2c9fd9e3eca40631e024664cf2584272cc8f96308cbe5fdfc930f51d8bc \+ --hash=sha256:8024d00c3faf3fc0c16e07a69f4405e8eac7cc0ab15f65fe6cf43827c4cf72b4 \+ --hash=sha256:80d02b6f04e92601a081dd97b23d3128033098bff5d35d392ddcc0476ea11253 \+ --hash=sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade \+ --hash=sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858 \+ --hash=sha256:87475fabc8d9996fd9c27debb395e642e8c838d78a00b6e932227a0e06b81e26 \+ --hash=sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96 \+ --hash=sha256:89b53f3cda69831909888e0494f4fa0bcd3537e3e138dabeb620bd6ad946bae8 \+ --hash=sha256:8a893cc101149f80a653f82062ebc95b34525a2614382e1da5458fe7c6997249 \+ --hash=sha256:8b2bfab86aa71ae13aa41a6a26aab338e0db2b8bc75434b05aea89e011ff35a4 \+ --hash=sha256:8d86d6fc60743dc916eb79e2eb1ec4818e21e427731543af40a3021851174a13 \+ --hash=sha256:915563965d418f986e7e145accc592eae9e1a1be3566ff98a05d7a9ec42a76e1 \+ --hash=sha256:92888bb3187c5ba50500b00b3b310c9f2c651709d28036077680cb5255450a03 \+ --hash=sha256:93223adc95033dd47133a46ccfc316a0139176fd79085762e27202ec56018f03 \+ --hash=sha256:9373ad13ef0d2c0fb761e04e55bfdee5a08b52cef2c882c8fbe9935b1517152e \+ --hash=sha256:9409a8bf35cf78353942504b24a57de3d75b708997a1e4bd8db71ac8633ce364 \+ --hash=sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4 \+ --hash=sha256:9bde855991b7e362c146535e3136a50bfaffc0487d38b33ca7e5edefc6e23849 \+ --hash=sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0 \+ --hash=sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a \+ --hash=sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036 \+ --hash=sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3 \+ --hash=sha256:a192e2c40070d92c3ccf777e3a5c4ff515573cd2bb7ed0c537fdadbbec5bbf21 \+ --hash=sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3 \+ --hash=sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e \+ --hash=sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413 \+ --hash=sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21 \+ --hash=sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346 \+ --hash=sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429 \+ --hash=sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685 \+ --hash=sha256:b736353c0a625bbd5fcec108576e2385db3496f4f771f785ff32e108d3c3bc45 \+ --hash=sha256:b7fd005a73d9e657273b7a10dc71a9e03c8fb9ee6999798d6918ce095b81ac7f \+ --hash=sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c \+ --hash=sha256:ba0b1d2620edf869789c3879223f52bf2afc5d31b3cb47cc57b3a12c05e2aa9d \+ --hash=sha256:bbbfc8e28816f19d7c0f1816664980c0a9875d01b27cdf8eedddb639d9e108ad \+ --hash=sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400 \+ --hash=sha256:c0afc6800ba57ccc350374c5bd6150419915d95ce93cdbab2d783d75eaf30ecb \+ --hash=sha256:c6708715abcf3c73b99508253e961a9967f02fe536532834149574eda6de0d1c \+ --hash=sha256:c7c9ab723cde841fefb34efbad91e87f00a674b1fe1cd0784fde742bf2c154dc \+ --hash=sha256:c8f3d67aeaf55f017982b73683f0e7342ba2f6635a78f69ce89ebb26aa411e5c \+ --hash=sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74 \+ --hash=sha256:ca403d7e4798f525fdfc78e258820419cbbd0f0ecbab9de7840e3c017cf6b8cf \+ --hash=sha256:d008d90a7f2471519aef0c90dfbe73b3e6e4d5e66ac48e19154c17e89e98b604 \+ --hash=sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f \+ --hash=sha256:d1befeed746d247c81127bb14de9dc3d30edb6e5976d34f83f86ed262b1d9105 \+ --hash=sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a \+ --hash=sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d \+ --hash=sha256:d4a7319f304a774bed22115bc891618e45f85065ab44ea6acd07d274e750519a \+ --hash=sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1 \+ --hash=sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5 \+ --hash=sha256:d913de495d90407cd859d263bee2e5d1a4ed3eb6573c04e70d9ec619a7cbed7f \+ --hash=sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e \+ --hash=sha256:dca9ab98072a5a54ebacebdc45f53e645336b320c667410b061be1ca588ae709 \+ --hash=sha256:ddc7dacc8ece3a182e7f15cb862d1fd616b46d076cb1ae9dd232b2c38b655874 \+ --hash=sha256:ddf19c062bea7a0cc80f519243d2c01dd091be0cf952a0750d4ad576709559f5 \+ --hash=sha256:def79fa35ef0cef8d2accec024f4fdc7ead3012ff02f5215c783f39f03ef8cfc \+ --hash=sha256:df29a0a7107f7011e77f4eebdddec4c7331e24d787a0b21a46d63bdf7445da95 \+ --hash=sha256:e09a3942ecbdee5cce73ea9d42da82b81b72ac1bf031ce069b93b5adf4eac8cd \+ --hash=sha256:e242bb1c5e76e97dfa9e7f209a71e93a01d7f19ffdd5cfbb2e2d55b4f08f8ab0 \+ --hash=sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d \+ --hash=sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3 \+ --hash=sha256:e4e81e09c1578b8df602e3db08b0b3ea0a6947ad612f52bf8dc5ea8d47691f0c \+ --hash=sha256:e54da4baf05720032d527874d40b65fa4d7e5c6c6a43d0c3adbeffcaf275a2b3 \+ --hash=sha256:e80e6c2f55656b4824d72065abb4ddd6a525c74bd78a0aab5d9fc2cf4fb5af50 \+ --hash=sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491 \+ --hash=sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5 \+ --hash=sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5 \+ --hash=sha256:ee43c17b173d46a3212baa6ead3ae258eeabdae48c263a01ccf0218c366dd655 \+ --hash=sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288 \+ --hash=sha256:eff0ac9dbe711a4aee69bf04a83896aa9b85f19641264053a9f6d48573abb7dd \+ --hash=sha256:f0aa869112ef88429ae17820d99c3dd9504c9e9c671d3c246f3d7442cb051084 \+ --hash=sha256:f3c96f633825733f735c5a9cf21d21a257d8e1edf0b1cee0a064b9c424ca0f7d \+ --hash=sha256:f5833ad231be5eb6553de524a70f48d71b2c8563101750531e0b80184e175cd4 \+ --hash=sha256:f5ec61164adcec446f8969a3358ec3f9b26bbda3b9213e5586d219afa8df2915 \+ --hash=sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1 \+ --hash=sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd \+ --hash=sha256:fc14a032f813bf5fe624d991960ea83e9715adc27e4c1830a2361eb1d02ac341 \+ --hash=sha256:fcff63213e8e6e47770541a4607175404f47cbb3ebea7b6058cc82d524a0e424 \+ --hash=sha256:fd1fbe0f116b6e55da77aca2c6ddcddcfac2186cbf78bdebf40fc156efca389d \+ --hash=sha256:fe9753dfee015c570d73df76f899f18444d41388bffcde097deba51c4fadbb9f+ # via requests+docutils==0.22.4 \+ --hash=sha256:4db53b1fde9abecbb74d91230d32ab626d94f6badfc575d6db9194a49df29968 \+ --hash=sha256:d0013f540772d1420576855455d050a2180186c91c15779301ac2ccb3eeb68de+ # via+ # myst-parser+ # sphinx+idna==3.20 \+ --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \+ --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c+ # via requests+imagesize==2.0.1 \+ --hash=sha256:b2ba6a4dea487a7ebcd53248d3476aca449d30db12a2dde5e0c5ca9624fd77e5 \+ --hash=sha256:ea0c9a0384df69ed86a943a15cde37d0360b82491b3910dc2215e202e62b5b02+ # via sphinx+jinja2==3.1.6 \+ --hash=sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d \+ --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67+ # via+ # myst-parser+ # sphinx+markdown-it-py==4.2.0 \+ --hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \+ --hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a+ # via+ # mdit-py-plugins+ # myst-parser+markupsafe==3.0.4 \+ --hash=sha256:007e1ffd9bf65bb6ee96df7b258fc632a4868dd5566037986c64781f35a36e98 \+ --hash=sha256:02fa4acbc6a3fc5c693c34d4dd8c1130b7fe99cc915181b0ddd6f72aeb296002 \+ --hash=sha256:03470d1a8268e692ecf79ecd565593e59d44219377a7ead61f1f1b94c1f7ff6b \+ --hash=sha256:04e7902ba80ee4bac1d50a549606527a1dcf0476cd81403db41099d3b60ec653 \+ --hash=sha256:051417f74bcaaefa316276e0ff723f541616ca51043d070da00249d9bddd3e3c \+ --hash=sha256:05295589e619b9bed252a86b532b8e27350abc372d18ba89b59375325e91ec1e \+ --hash=sha256:06de8ef6331f6e822c28d577dc8bf43fe398800477c49498f38fc38b67ff33fc \+ --hash=sha256:0764a13d34cae40db7bbf3a09b7e9b491bf4603e20b263a7a9d6b8e324975d0a \+ --hash=sha256:077293e425f28ec737dbcad442a71752e28f8ae27cde3d68acd1fb212091cd92 \+ --hash=sha256:0930db9bdc62d22944e10b066448bb65dc9abe9112880c7cab8da54db4284d5f \+ --hash=sha256:0cee7cb0f9a1b6892ea482237d9403b3d1b4603aee057d0ff01f0fac2d019a97 \+ --hash=sha256:0d9c47709875fdb321452056622e930c52afbc07a7d780762fbb8b4d91ce6fa4 \+ --hash=sha256:11935df9bf455ed0c04eb87bcd720f02b1fe5e02128a9430f23aed6f93336fc7 \+ --hash=sha256:12a606a492de952afcb43b59a14aaaaad120e708d3663dd0fdf2d738d427a691 \+ --hash=sha256:14bd2d845d62ab678eaf81da89d7b621b51756c72346745c1a594c09d49207a2 \+ --hash=sha256:15ba9e28640feef770374b116a6f019c21f52404aeabe516aa7f800587b98cfc \+ --hash=sha256:18a801868a884f216e784d7d14db2a4077143ce7610440aee2ce8f734e7cfcde \+ --hash=sha256:1c0df495a977d10460a94941799c72d5b5ab03d3858d949b55b5a66c8f371c99 \+ --hash=sha256:1caa2fa5a6184fb233153b35f654e6687bd555476f6170f29d8ee9be1a8b0af9 \+ --hash=sha256:1e1451fab512d1bcc3dc26988ec1edb0b82c2db909132872cd9356070a6b63df \+ --hash=sha256:1f1f9477e174582b0a1b583d60b66e1f2cf5d3fe12cee985e4aedf44766600e5 \+ --hash=sha256:2628d3a8cb648ecebb3c5d6b0a1052d400e4d8b7ac0fb786be8d285b50040d17 \+ --hash=sha256:26e9867520db70d37f7fb421a7f0d8adb40171011fb84ce869afa1a83370dfa8 \+ --hash=sha256:2a6ef68ae94aed8721934072b27a3b654ea2100b97e4ab864cf1489c90926fbc \+ --hash=sha256:2b2b1e18af909b448bb3cf9e3433366f7a8726271fc214e8b10e0f62a78c724b \+ --hash=sha256:2cb3dd71fc6be918ad4264346a8ed69485f9b7ed7bf35495d8e22807cd6b8bea \+ --hash=sha256:2d1b7d9308288661f56672b1b157d75fc536714d3638487bbea17b6318a78248 \+ --hash=sha256:2dad610540cb2e6272855c178f08ae9a1c7ac258a7fb71660553a5f104b42741 \+ --hash=sha256:2e5a7cd7fdd14fcb1ae5d7d8bf23d24fbd1daefd1fbca2580132e1ea75f098b5 \+ --hash=sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6 \+ --hash=sha256:340cbb1957ba99929cbf19a75626d36ba1ae21d1730b287d1cf7f824a20c4fc7 \+ --hash=sha256:34bdde374c5932765d7dc685c4a1d191a3207852d67e8e0a9eb6ea85156181f1 \+ --hash=sha256:353bd63081912ab8cfa6a0c7d185934cdf8426f04c618bba6bc4b394f2069b67 \+ --hash=sha256:387d8cd30e69b3f0a72877b9ae717033396404e19095b17fe89753a981fda44f \+ --hash=sha256:3882fb412298575bae3b9c46868251f15cc69307359f87bb1b382e53d6e5a2c9 \+ --hash=sha256:38fc55594dab834470b6733dead2ee9e3f657fb0608c769dcafa0ba5ab52f45c \+ --hash=sha256:396ec4e65cc889f69786b3b89478b471cee5a3bcf468b9d9bb03e1a30fb291fc \+ --hash=sha256:39dbacefc411633db5b4378b066a9aca70a3d7e2922c9e578d825f844026eeba \+ --hash=sha256:3a93d9616ddecfb393727a0041a562cf0b15a244e20f2bd25efc7949be4c4f17 \+ --hash=sha256:3d23795802fc8bd72534836d64489bbf0f67c088959091bdb22e10735a5107bf \+ --hash=sha256:434139499bb20b502ed3baa1f169e618f924a97e7a777fea1a49446d80106cf6 \+ --hash=sha256:436e3ffc6310d3c41878c601db29098102fe5d8a467c49da4a4125254e0980f2 \+ --hash=sha256:489505b03f692c3f376394e49194fa7a7f9e8558d6e293a7056a0032b0c38163 \+ --hash=sha256:4a540e2d3192792fc84eced57bef37851ccb2b41f73291bb17408eea77bcd278 \+ --hash=sha256:4a7cdc2a420ca01058182da4253329764d4bfa055564d1eced90e6ba1e8b1d3d \+ --hash=sha256:4bced6e2a6dba6a28f7dd3c6ce14df1b2dd495923f16ea484cad03decd463b2b \+ --hash=sha256:4cf3468d5ec187ffffcaca8e61929a37448f215dafc1386a12c750a72fe53634 \+ --hash=sha256:4e2c4809c14559aa7ef426f27fb35afbb38104c349a903bf8f3600456764bb38 \+ --hash=sha256:4ed644d75aa94a2baf7ec3a96eaa160ea58c742eb9d27c6506053c5c40fc84ed \+ --hash=sha256:4f6e0852a0283b1b1fd776eeb7b766a5f440b3e2bd31ab51af3b400585f3965c \+ --hash=sha256:5066b244f576f91afc8ee3ba029a89f99d39c79b1853fe9d39bea9f0afbec148 \+ --hash=sha256:5086f9975abb1ab531ee6afca1761e4b59a19b446f3f6522ed776963228cfe5a \+ --hash=sha256:50b5bedc9ed8a94fc8857a42ef4f84a81ea88f8d4f05dc8705fb23ee6d8dcca7 \+ --hash=sha256:52704c5d36eb6dda8866493decd61111fff86244c9b1ad225ca01b9e91e5970f \+ --hash=sha256:55ffd6ce583d97dc71dc92e930324c8c0d25aea7e3ade6ae54ef77cedb096811 \+ --hash=sha256:569d65055d367e3dcdf30c3f41119467b73d9ee9faf332bdf40402644f5ac08e \+ --hash=sha256:57f9947a7e57a081c1e3e0a2dd0d2dcf290a4531450e6f611e30084c222a7295 \+ --hash=sha256:5989cb26b2e1efc6a42216a9f6b5ee495ce5ace2e5b352a9af489976b32d1ee2 \+ --hash=sha256:5c22873ad1f0532ba40fa1727f3c0fc1bbbaab6d373d4cbe3f0dc74b2e2521c7 \+ --hash=sha256:5e8b3d0b18fd623afa12ecb2ce8d8becef69f9b5440c6330c7972200e0bb84b0 \+ --hash=sha256:61631e08084be9e21a8967ec3139c7616ed7c5e9368e05c86d1b39562c8a57b6 \+ --hash=sha256:64511c54db4e4987aef4c41923235927428729e8174c5dba488429be70a998ed \+ --hash=sha256:6669c1bf34080161ce49c589cc512ef24d4c704ac9d2b2d3667f519c60418378 \+ --hash=sha256:672d207103e6b16ca098611b0f9efad6bc00afd47c03d6ef62186495ca677dc0 \+ --hash=sha256:6768d67d1bce64270e0fdc2e69309d68b9b18ae56ddf6c711d168e9d051c2cac \+ --hash=sha256:6a45c3d514f2436064db00d7fc8778d888f0236ebfed649b53d13a59e69ad51b \+ --hash=sha256:6bd9e1788e15bfcf6a9082de42e30387e7b85d211ab21e57a939bb8cfaaf8d96 \+ --hash=sha256:6d2a9efe686f9de00d0d1ea32a4a5a86d558a2277501bd78d964214eab625e59 \+ --hash=sha256:6da83a088f8ef93b2d483a8232a4dbf4d69d3d8496b568a03c56becac43e1808 \+ --hash=sha256:7018d4af1cd272e847aa5917983ab5e83e4f6579f9dbfecd4a79c0ca80b144c2 \+ --hash=sha256:71f88e749ea29f67f21f3b36433c1dc54c7729ed2a6d9e2da2e0d9e0d7b224eb \+ --hash=sha256:737c9c3981998eba27f11786f84fddcbabc74068b72a4a1f454ea02094b57b65 \+ --hash=sha256:73e77980c7207854f00fc4e71fb1626868d5740ab4012623d55c7a99ad122a72 \+ --hash=sha256:799c39bdf5e2f1292fedd3009f7b3c9e760f10b2420cb9638d56920840ff6db8 \+ --hash=sha256:7a83aa6e4805df46fed18e989d3d16f86ef60cb50bbc8d9ce3a6be89165fbf6e \+ --hash=sha256:7d3391b2188d18737cb2fa147028b1096236eaa7e156446c650a489fa2cadc91 \+ --hash=sha256:7e1636da3d8dfc220b6dd10264db5f2b165e4888c4518594898fbe381049af8a \+ --hash=sha256:805c8b84534fa10891890f0e4be39f3a99e94615d93e8836bf9fa1fdca2feeb2 \+ --hash=sha256:811d02d5122171c1941357efd8f9bf4ffe907b7f0a1a4e729a880e4be3f46e3e \+ --hash=sha256:8138eb83940ec7299024d92d4dee45f601b9e6c5ffde9d25f4e35e326203c707 \+ --hash=sha256:83b3944fea42a8400edf92fd1770fb8d0d4f7de651353bd2d8525a92dba69a21 \+ --hash=sha256:849dd2bb0e5e4ab2b71c7191726a4a8d5aa8a610daa584728cbee0b710ddc4ef \+ --hash=sha256:8698d70a8081ee8c090dbb394768b5789a1da8b131b5499f89d071dd3cfaf6be \+ --hash=sha256:8781a792a070cf2bd1b86d3aa943894115faaba6e88122a7bf32d62072742453 \+ --hash=sha256:88d59b473bfb03259722600839af9bbd7fa13a2eb514beefeedb95997882f69a \+ --hash=sha256:8909c2f1c6dd65e054ac4b573a91c8384d1492281e55d82d159d653f7a13adf6 \+ --hash=sha256:8965520ac587c94a4ac48b729be3d8b8de00af39699b17585dfb599babe77977 \+ --hash=sha256:8b5d563170ff8ba3181caa967c99a3c804d1dedb702c7cb93a6a7c32247da978 \+ --hash=sha256:8e124f974786f831d6043728e38296969d3579db8896fe004682f5758e613581 \+ --hash=sha256:8f0fac8b13d14bb06c68195f849371924ae53dd7b1c00fed24650f704383b692 \+ --hash=sha256:9240187afb63d2f9ddc3e032c670356fe941f6e20662ea168a5dc3f1f317e1b3 \+ --hash=sha256:925f929d6b59a8b3f8b8c6ac363cd0af7eecc81efb3071770b3c6717c450a369 \+ --hash=sha256:9348cbb300d224fe3b89793262cb093504d4ae927004468463f745188a193e4a \+ --hash=sha256:9388003072b95f2f1e3fd908604194d653ba21330d811961a78b7da1a77e9e36 \+ --hash=sha256:9438a2648b2195980cb2dd8e53ed7b8df91319e2d0b70ae61a9e1d1bc8d3bec9 \+ --hash=sha256:94e4c421742086aeee4c32a506eec8859d7634aad943f7e6aacf70f813478768 \+ --hash=sha256:94f5407f7bc64fa6463906b896f9904beeeb7dd8dc116ee8e9056c8714ff9916 \+ --hash=sha256:971a3bbb75d97ae4e2e8f7d4834236f86f85f0c85e04ab2e191db1123b04f80b \+ --hash=sha256:9e227f3dbe6bde7491cf0a9965d00b88c6b1a4a95d11480ddf88bb96d397c19f \+ --hash=sha256:9e25feb9e330b63edb0278a0acdf85e50d0cb0fbf49c3084abbe4e24ae195346 \+ --hash=sha256:9f098115c247e11d138ab83a28fa0323c77015007ea2df73ba5fd714dfefd67c \+ --hash=sha256:a18f38cafc329bac5e3c2b96c765b4c96d3d103421ed22ab7988c1e3fce27464 \+ --hash=sha256:a4bbd2d87dd233b9fc5812160c3d0ffbe42edc22a26ce0469f58479ede633fe9 \+ --hash=sha256:a5fcffb37e602b0b3c1638a97746b9b96125caa9bcf6fa41d337a9261de231ee \+ --hash=sha256:a8e9f292fcda89b324f2f5c91d13f1424a153e40fc2756f38ee23b15835ff300 \+ --hash=sha256:a9f54054101545a9a9cccefddf54316aa6e4491611fcbef9e91b3b6bebec04f6 \+ --hash=sha256:aa2c838cc024642cc04c6854232f32b43e5e22833dd11119c1766c7873b8370d \+ --hash=sha256:ac0c7c9f1609b0c4c114feb1d7a3409564c7fb77e360bed9e97e5d25dfeaf868 \+ --hash=sha256:add96447a86d205ab616665d53b2950ee81083757f56e6ea833c8b2917646b46 \+ --hash=sha256:ae9dcb8fbe244cb82f8a6458b455b927a03685e383d9bacf1ea5ce180b96dc97 \+ --hash=sha256:b4a635a0487774f841cb1fb62e907e7195cc95bc761e053184b8acc3ceb20733 \+ --hash=sha256:b4d12837e0203bbace818ff4a7461afdcd78bcd782351cea148139180d7bcffe \+ --hash=sha256:b61687d0828e72bf5cda24a2690188f37170bd31c9359ac97e4e66569f120a16 \+ --hash=sha256:b807e598953730f82e4eae3bd30f6a122cf6b31c398c6b504c0e04c13c170429 \+ --hash=sha256:b8cd1f918b26fd7b1832ece557cc18f2d8747309ff8b3f0ef9d4250c5ad67a39 \+ --hash=sha256:b91cc9d336957239ff200f30097e6fea2dc6d6fb3c81e853eaa09eac904fd894 \+ --hash=sha256:bd3ce56ae2cbae3ba82b683bc425cd7e48d2ed8b10f3e818186b6f5646d9271c \+ --hash=sha256:be6cb0c799abb0e2ba3e618e6d28ddddf7e485f6c2ce938dfa237daf3905072c \+ --hash=sha256:befb4158af32106b9a93db8d6d1d1cbbd418c0d5aca0cabb7b1780abf0c89169 \+ --hash=sha256:bf053da3c97a4bc5ecfbb218cdd2983febd91c617be8367d139882aa11e490aa \+ --hash=sha256:c02e8f18bdedba082cef725942ac823b9b60656db07f7e265cb31618dfd00d77 \+ --hash=sha256:c1bc67752d5f21013cfe430df4062441714eab79f65a6a05e01505957e9c35fe \+ --hash=sha256:c61750fadcd119d0825bcb7d7d675dd264dcc89cc05292aab5be68ebdbb374ad \+ --hash=sha256:c90d5b3d4e944e065a301d741b3c1d784f6bd1f503aa68b4967e32b2ba313d85 \+ --hash=sha256:c9a7f43c0b202b334cc9184af09bb8f21d3a209e038efaf106936fb69e6b026e \+ --hash=sha256:cb96e6e088d6cf71c1ea977510948320234824cf226e32f6f6e044f7a9c82b34 \+ --hash=sha256:cf63c214fe879a65e69a386f915e36104fc84254ab141240f8854602d8e0be2a \+ --hash=sha256:d1aca03ede943eb80ab3d63bb082c84b7aab85ea83bd0fd0c200260945fb49d9 \+ --hash=sha256:d2e56fd3b00222722abfb3f5f0759ddbae4b90811b5ad4343c64030ad1bde70c \+ --hash=sha256:d5f93ebbeb8032d47e349328ec8662d973d9b05a70b3c35df1f91fe419b84749 \+ --hash=sha256:d882a373d8093c2941e01291b7ced96e9cbe4781da9a7751ca7e6c70385e5214 \+ --hash=sha256:d920abdfa61279ba1a2ef9484aab07bf03331f8c08a10120fa332353d06e6932 \+ --hash=sha256:da2af0d7aebfc2074080d72efa6ab8317c62481ef1f896f65d9999c1c01f4494 \+ --hash=sha256:dd8ea6ebee7aedbf7c749fa80521d9ccf1ba473e0d1e14805caafbaad281c889 \+ --hash=sha256:de8b364c423ef0a4bad9069657d617f9a5d2b2062457a89b1fa16ee199c399c1 \+ --hash=sha256:df1ae86ff54725a01fa1a0510b914ca53a161b7050be74f6204e24aded5971d0 \+ --hash=sha256:dff05cb7016dff1e9fd68f4122c127b65dfc59de5306cfb7ad92f956f230bee2 \+ --hash=sha256:e1a622f13970d81f95d0c72f9dc090dce9085fccfa4c9f2174377ee32bd15786 \+ --hash=sha256:e49fb0d1ce92cfa0cb198cc5b1b11cdf9d0638658e2a2db2687e39db7c87fc78 \+ --hash=sha256:e5c802729725bd07e2bc3ab7b76dc7e0bbfc53129d8f1eb1c002c24cf774717e \+ --hash=sha256:e841068dc0be4cb6dfb5c890eb88cbdcff2f4a332393c7ec94e8e618bd32c1a8 \+ --hash=sha256:e916035e3e9930cbdfdd10abf48861340221857f45509565898e012263f7b289 \+ --hash=sha256:eba154571c16e032112afac0dc2dfe9e63c2ceb7aedd07bb7eecf2ce26d4dd4c \+ --hash=sha256:f03460ff076f70ab595bb45a0205ccea1971443575b6920c52e755dec2b3fbfe \+ --hash=sha256:f0ec3b750b59375eab5b0fb2b9254810c00a3375be6d789899f1055a1d556237 \+ --hash=sha256:f291bcf42ae98eb5107edb162c3c998b4a89648fd8e99ed4cbd12705292788cd \+ --hash=sha256:f61efe1d2fe0de16158a5fe1d1cf3c14bdb6aecd54d8938fd26512c525c1f624 \+ --hash=sha256:f68edfc67aabac33708941f26f22a7b8e9f81429bc0cf249fcf7d66b23af8d19 \+ --hash=sha256:fa95848c929b6a75f6848d3c9793e59db365ee436776e57db835cdbfa79ba977 \+ --hash=sha256:fd9f8797427910198f95bced71ddfed61130d7e349213bfb8466c9c99e2c46a8 \+ --hash=sha256:fdb4ca07ab75ffadab4a8b135ad59cdbb3156b99310f3d565370da74a15d6bd3+ # via jinja2+mdit-py-plugins==0.6.1 \+ --hash=sha256:214c82fb2ac524472ab6a5bcab1de80f73b50443e187f401bfd77efbc7c6481d \+ --hash=sha256:a2bca0f039f39dbd35fb74ae1b5f998608c437463371f0ff7f49a19a17a114d0+ # via myst-parser+mdurl==0.1.2 \+ --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \+ --hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba+ # via markdown-it-py+myst-parser==5.1.0 \+ --hash=sha256:9c91c52b3cdb4d94a6506e4fab4e2f296c7623a0da0dcbe6de1565c3dad67a8a \+ --hash=sha256:ab69322dc6719dcc7f296479dbb70181b66df6ed315064f92dbc85c0e1bf2f02+ # via -r requirements.in+packaging==26.3 \+ --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \+ --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c+ # via sphinx+pygments==2.21.0 \+ --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \+ --hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c+ # via sphinx+pyyaml==6.0.3 \+ --hash=sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c \+ --hash=sha256:0150219816b6a1fa26fb4699fb7daa9caf09eb1999f3b70fb6e786805e80375a \+ --hash=sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3 \+ --hash=sha256:02ea2dfa234451bbb8772601d7b8e426c2bfa197136796224e50e35a78777956 \+ --hash=sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6 \+ --hash=sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c \+ --hash=sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65 \+ --hash=sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a \+ --hash=sha256:1ebe39cb5fc479422b83de611d14e2c0d3bb2a18bbcb01f229ab3cfbd8fee7a0 \+ --hash=sha256:214ed4befebe12df36bcc8bc2b64b396ca31be9304b8f59e25c11cf94a4c033b \+ --hash=sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1 \+ --hash=sha256:22ba7cfcad58ef3ecddc7ed1db3409af68d023b7f940da23c6c2a1890976eda6 \+ --hash=sha256:27c0abcb4a5dac13684a37f76e701e054692a9b2d3064b70f5e4eb54810553d7 \+ --hash=sha256:28c8d926f98f432f88adc23edf2e6d4921ac26fb084b028c733d01868d19007e \+ --hash=sha256:2e71d11abed7344e42a8849600193d15b6def118602c4c176f748e4583246007 \+ --hash=sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310 \+ --hash=sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4 \+ --hash=sha256:3c5677e12444c15717b902a5798264fa7909e41153cdf9ef7ad571b704a63dd9 \+ --hash=sha256:3ff07ec89bae51176c0549bc4c63aa6202991da2d9a6129d7aef7f1407d3f295 \+ --hash=sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea \+ --hash=sha256:418cf3f2111bc80e0933b2cd8cd04f286338bb88bdc7bc8e6dd775ebde60b5e0 \+ --hash=sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e \+ --hash=sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac \+ --hash=sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9 \+ --hash=sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7 \+ --hash=sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35 \+ --hash=sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb \+ --hash=sha256:5cf4e27da7e3fbed4d6c3d8e797387aaad68102272f8f9752883bc32d61cb87b \+ --hash=sha256:5e0b74767e5f8c593e8c9b5912019159ed0533c70051e9cce3e8b6aa699fcd69 \+ --hash=sha256:5ed875a24292240029e4483f9d4a4b8a1ae08843b9c54f43fcc11e404532a8a5 \+ --hash=sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b \+ --hash=sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c \+ --hash=sha256:6344df0d5755a2c9a276d4473ae6b90647e216ab4757f8426893b5dd2ac3f369 \+ --hash=sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd \+ --hash=sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824 \+ --hash=sha256:66291b10affd76d76f54fad28e22e51719ef9ba22b29e1d7d03d6777a9174198 \+ --hash=sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065 \+ --hash=sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c \+ --hash=sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c \+ --hash=sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764 \+ --hash=sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196 \+ --hash=sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b \+ --hash=sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00 \+ --hash=sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac \+ --hash=sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8 \+ --hash=sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e \+ --hash=sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28 \+ --hash=sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3 \+ --hash=sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5 \+ --hash=sha256:9c57bb8c96f6d1808c030b1687b9b5fb476abaa47f0db9c0101f5e9f394e97f4 \+ --hash=sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b \+ --hash=sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf \+ --hash=sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5 \+ --hash=sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702 \+ --hash=sha256:b30236e45cf30d2b8e7b3e85881719e98507abed1011bf463a8fa23e9c3e98a8 \+ --hash=sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788 \+ --hash=sha256:b865addae83924361678b652338317d1bd7e79b1f4596f96b96c77a5a34b34da \+ --hash=sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d \+ --hash=sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc \+ --hash=sha256:bdb2c67c6c1390b63c6ff89f210c8fd09d9a1217a465701eac7316313c915e4c \+ --hash=sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba \+ --hash=sha256:c2514fceb77bc5e7a2f7adfaa1feb2fb311607c9cb518dbc378688ec73d8292f \+ --hash=sha256:c3355370a2c156cffb25e876646f149d5d68f5e0a3ce86a5084dd0b64a994917 \+ --hash=sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5 \+ --hash=sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26 \+ --hash=sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f \+ --hash=sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b \+ --hash=sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be \+ --hash=sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c \+ --hash=sha256:efd7b85f94a6f21e4932043973a7ba2613b059c4a000551892ac9f1d11f5baf3 \+ --hash=sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6 \+ --hash=sha256:fa160448684b4e94d80416c0fa4aac48967a969efe22931448d853ada8baf926 \+ --hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0+ # via myst-parser+requests==2.34.2 \+ --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \+ --hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed+ # via sphinx+roman-numerals==4.1.0 \+ --hash=sha256:1af8b147eb1405d5839e78aeb93131690495fe9da5c91856cb33ad55a7f1e5b2 \+ --hash=sha256:647ba99caddc2cc1e55a51e4360689115551bf4476d90e8162cf8c345fe233c7+ # via sphinx+snowballstemmer==3.1.1 \+ --hash=sha256:7e207fa178741da09cdee59d3ecec3827ad5f92b1fc5c9ff3755b639f71f5752 \+ --hash=sha256:e07bbc54a0d798fe6010a12398422e62a8bfbba95c394fd0956ef58cb4d3e260+ # via sphinx+sphinx==9.1.1 \+ --hash=sha256:48b627f02908f22c601b3ba9c7b17265b4f315dd05c8bc64cd4da41183f44fbc \+ --hash=sha256:f8b60013ce25017be41a509e5c2d265bc1918410061315c36b809c7f335646c0+ # via+ # -r requirements.in+ # myst-parser+sphinxcontrib-applehelp==2.0.0 \+ --hash=sha256:2f29ef331735ce958efa4734873f084941970894c6090408b079c61b2e1c06d1 \+ --hash=sha256:4cd3f0ec4ac5dd9c17ec65e9ab272c9b867ea77425228e68ecf08d6b28ddbdb5+ # via sphinx+sphinxcontrib-devhelp==2.0.0 \+ --hash=sha256:411f5d96d445d1d73bb5d52133377b4248ec79db5c793ce7dbe59e074b4dd1ad \+ --hash=sha256:aefb8b83854e4b0998877524d1029fd3e6879210422ee3780459e28a1f03a8a2+ # via sphinx+sphinxcontrib-htmlhelp==2.1.0 \+ --hash=sha256:166759820b47002d22914d64a075ce08f4c46818e17cfc9470a9786b759b19f8 \+ --hash=sha256:c9e2916ace8aad64cc13a0d233ee22317f2b9025b9cf3295249fa985cc7082e9+ # via sphinx+sphinxcontrib-jsmath==2.0.0 \+ --hash=sha256:15ca92fe0eec82f0baf91a7efcc51ffacdb605924be6327683a52ebdacb6744c \+ --hash=sha256:551f780cf9687f9c3c74f0cf9f18aca06e0d6958853453f3803fe4d357c5b924+ # via sphinx+sphinxcontrib-qthelp==2.0.0 \+ --hash=sha256:4fe7d0ac8fc171045be623aba3e2a8f613f8682731f9153bb2e40ece16b9bbab \+ --hash=sha256:b18a828cdba941ccd6ee8445dbe72ffa3ef8cbe7505d8cd1fa0d42d3f2d5f3eb+ # via sphinx+sphinxcontrib-serializinghtml==2.0.0 \+ --hash=sha256:6e2cb0eef194e10c27ec0023bfeb25badbbb5868244cf5bc5bdc04e4464bf331 \+ --hash=sha256:e9d912827f872c029017a53f0ef2180b327c3f7fd23c87229f7a8e8b70031d4d+ # via sphinx+urllib3==2.8.0 \+ --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \+ --hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63+ # via requestsdiff --git a/Documentation/security/cryptography.rst b/Documentation/security/cryptography.rstnew file mode 100644index 00000000..879e8e24--- /dev/null+++ b/Documentation/security/cryptography.rst@@ -0,0 +1,274 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Security reviewers++Cryptography+============++Every cryptographic algorithm shirudo uses, where it uses it, and what+accepts other algorithms. OpenSSL 3.5 or newer provides the userspace+side, tpm2-tss talks to the TPM, and the kernel verifies loader+signatures and config roots. The :doc:`threat-model` gives the threats+each use answers.++Signatures+----------++.. list-table::+ :header-rows: 1+ :widths: 18 22 20 40++ * - Object+ - What is signed+ - Signed by+ - Verified by+ * - upatch loader, load or unload directive+ - The loader's instructions followed by the data of its frozen+ metadata map+ - ``shirudo build`` and ``shirudo bpm build`` on the operator+ - The kernel at ``BPF_PROG_LOAD``, against the ``.bpf`` keyring+ that ``attr.keyring_id`` names+ * - Repository index+ - The index document+ - ``shirudo bpm push``+ - ``shirudo bpm`` on the target, against the repository+ certificate in the signed config image+ * - Tree publication+ - The publication document+ - ``shirudo bpm tree append``+ - ``shirudo bpm tree sync``, against the runtime image's primary+ certificate+ * - Config root+ - The 64 lowercase hex characters of the dm-verity root hash+ - The operator's image tooling, with the config key+ - The kernel when shirudo creates the mapping, against the keyrings+ of assumption A7; ``shirudo image verify`` offline+ * - Vouch+ - The bytes ``shirudo-key-vouch``, a NUL byte, and the DER of the+ vouched certificate+ - ``shirudo keys vouch``+ - ``init`` and ``shirudo image update``, against the certificates+ already in the trusted set++All five use one format, produced by one function on the operator:++- Algorithm: ML-DSA-87 (FIPS 204). The signing code refuses any other+ key, the smaller ML-DSA parameter sets included.+- Container: a detached CMS ``SignedData`` with no certificates; the+ signer is named by its subject key identifier.+- With OpenSSL 3.x: signed attributes with a SHA-512 message digest and+ no signing time, because OpenSSL 3.x cannot sign ML-DSA without+ signed attributes and the kernel accepts only SHA-512 for ML-DSA in+ that form.+- With OpenSSL 4: no signed attributes; ML-DSA signs the content+ directly.++``shirudo genkey`` creates the ML-DSA-87 key and a self-signed X.509+certificate. ``shirudo keys vouch``, ``shirudo keys add`` and the image+tooling for the config certificate refuse a certificate whose key is not+ML-DSA-87.++What accepts other algorithms+-----------------------------++The ML-DSA-87 rule is enforced where shirudo signs, not everywhere it+verifies:++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Verifier+ - Accepts+ * - Kernel, loader signatures+ - Any algorithm the kernel's X.509 and PKCS#7 code supports for a+ certificate in ``.bpf``. ``init`` enrolls the runtime image's+ certificate and the vouched signers without checking their+ algorithm. The pre-flight check ``cert_algorithm`` refuses+ anything but ML-DSA-87, but in the initrd it reads+ ``/etc/shirudo/keys``, not that set (threat model U4).+ * - Kernel, config roots+ - Any key, of any supported algorithm, in the keyrings of+ assumption A7 (threat model U2).+ * - ``shirudo bpm``, indexes and tree publications+ - Whatever algorithm the repository or primary certificate holds+ (threat model U4).+ * - Vouch check on the target+ - Whatever algorithm the vouching certificate holds; the vouched+ certificate's algorithm is not checked on the target.+ * - TLS peers and endorsement key certificates+ - Whatever their certificate authorities use (residual risk R9).++Certificate validity+--------------------++No verifier enforces a certificate's validity period. shirudo's own+CMS and chain checks for signatures set ``X509_V_FLAG_NO_CHECK_TIME``.+The kernel compares a signature's signing time with the signer's+validity only when the signature carries a signing time, and shirudo's+signatures carry none. ``shirudo genkey`` writes a validity of ten years+into the certificate, which is informational. Retire a key by revoking+it (residual risks R13 and R16).++Digests+-------++.. list-table::+ :header-rows: 1+ :widths: 30 20 50++ * - Use+ - Algorithm+ - Input+ * - Payload digest of an upatch (``payload_sha256``)+ - SHA-256+ - The signed bytes: loader instructions followed by the map data+ * - ``excl_prog_hash`` of the metadata map+ - SHA-256+ - The loader's instructions+ * - Register events+ - SHA-256+ - A domain tag (``shirudo-init``, ``shirudo-upatch``,+ ``shirudo-unload``, ``shirudo-key-revoke``, ``shirudo-tree``)+ followed by the event's fields+ * - Register value+ - SHA-256+ - The TPM's NV extend: the old value followed by the event+ * - Register anchor in PCR 9+ - SHA-256+ - The string ``nvpcr-init:shirudo:0x1818e00:<name>``, where+ ``<name>`` is the index's TPM name in hex+ * - Config activation events+ - SHA-256+ - ``shirudo-config-root-v1``, the event kind and the root hash+ * - Certificate identity+ - SHA-256+ - The certificate's DER (``cert_sha256``) and its public key+ (fingerprint)+ * - OCI manifests and blobs+ - SHA-256+ - The content, compared with the ``sha256:`` digest that references+ it+ * - dm-verity images+ - SHA-256+ - Hash tree format 1 with 4096-byte data and hash blocks+ * - CMS signed attributes, OpenSSL 3.x+ - SHA-512+ - The signed content+ * - Seal label+ - SHA-256+ - The xattr name; the label is a public constant, not a secret++TLS+---++Every HTTPS connection, to a registry, an image download or a+collector, uses the same policy:++- TLS 1.3 only.+- Key exchange groups ``X25519MLKEM768`` (preferred) and+ ``SecP256r1MLKEM768``, both hybrid with ML-KEM-768.+- ``tls.classical_hosts`` in the runtime image's bootstrap settings+ lists exact host names that may also use ``X25519`` and+ ``secp256r1``. Each host of a redirect must be listed itself, and+ shirudo logs a warning when a classical group is negotiated.+- Cipher suites: OpenSSL's TLS 1.3 defaults; shirudo does not set them.+- The peer certificate is verified against the system's certificate+ authorities, or a CA file that ``BPM_OCI_CA_FILE`` or the export+ settings name. ``map_export.otel_insecure`` turns verification off+ for a collector.++TPM+---++.. list-table::+ :header-rows: 1+ :widths: 22 38 40++ * - Object+ - Algorithm+ - Use+ * - Attestation key+ - ECDSA on NIST P-256 with SHA-256; a restricted signing primary+ with a fixed template under the endorsement hierarchy+ - Signs ``TPM2_Quote`` and ``TPM2_NV_Certify`` with the verifier's+ nonce, up to 64 bytes. ``init`` records its name in the identity+ map.+ * - Endorsement key+ - The TCG default template, RSA-2048 or ECC P-256, with AES-128 in+ CFB mode as its symmetric algorithm+ - Credential activation for ``shirudo attest challenge``+ * - Credential+ - RSA-OAEP with SHA-256 and the label ``IDENTITY`` for an RSA+ endorsement key, or an ephemeral ECDH on P-256 with KDFe for an+ ECC one; then KDFa with HMAC-SHA256, AES-128-CFB and HMAC-SHA256+ - Made in software by ``shirudo attest challenge`` on the operator+ * - Endorsement certificate chain+ - X.509, verified with OpenSSL against the ``--ek-ca`` bundle; an+ intermediate in the bundle counts as a trust anchor+ - ``shirudo attest challenge``+ * - NV writer+ - RSA-3072, exponent 65537, RSASSA-PKCS1-v1_5 with SHA-256; an+ owner-hierarchy primary whose unique field is a 32-byte random+ seed drawn at each boot+ - Signs, inside the TPM, the SHA-256 of the session nonce, a zero+ expiration, the command hash of the exact ``TPM2_NV_Extend`` and+ the policy reference ``shirudo-nv-writer-v1``+ * - Measurement register+ - NV extend index ``0x01818E00`` with SHA-256 as its name algorithm+ - The write policy: ``PolicyOR`` of ``PolicyNvWritten`` and of+ ``PolicyNvWritten`` with ``PolicyPCR`` over PCRs 9 and 11 in the+ SHA-256 bank, then ``PolicySigned`` by the NV writer and+ ``PolicyCommandCode`` for ``TPM2_NV_Extend``+ * - PCRs+ - The SHA-256 bank+ - Reads, quotes, the anchor in PCR 9 and the config PCR++Sessions and authorization:++- The register's policy session uses SHA-256, is unsalted and unbound,+ and has no symmetric algorithm, so no parameter is encrypted and no+ response is authenticated by a session (threat model U8).+- Commands that need authorization use password sessions: the owner+ password from ``tpm.owner_auth``, when configured, in plain, and an+ empty password for the endorsement hierarchy. shirudo uses no HMAC+ session.++Key custody+-----------++.. list-table::+ :header-rows: 1+ :widths: 24 30 46++ * - Key+ - Where it lives+ - Custody+ * - Signing key+ - ``signing_key.pem`` beside ``cert.der`` in the operator's key+ directory+ - An unencrypted PEM file. The signing code refuses one that is+ not a regular file of mode ``0600``. Only ``shirudo-build`` links+ the signing code, and no target holds the key.+ * - Config key+ - With the operator+ - Signs config roots; its certificate travels in the runtime image+ and is enrolled in ``.dm-verity``.+ * - Attestation, endorsement and NV writer keys+ - In the TPM+ - The private parts never leave the TPM. The primaries are+ recreated from their templates when needed. The NV writer's seed+ is in the identity map and is not secret.+ * - TPM owner password+ - ``tpm.owner_auth`` in the runtime image's settings+ - Readable by root on the target (residual risk R20).++Related+-------++- :doc:`threat-model`, threats T5, T8 and T9 and residual risk R9.+- :doc:`/concepts/background/bpf-signing` and+ :doc:`/concepts/background/tpm` for the background.diff --git a/Documentation/security/index.rst b/Documentation/security/index.rstnew file mode 100644index 00000000..f8a7b32c--- /dev/null+++ b/Documentation/security/index.rst@@ -0,0 +1,22 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++Security+========++What shirudo protects, against whom, by which mechanism, and where each+mechanism stops. Start with the security model for the short version.+The threat model states every assumption, threat, residual risk and gap+not closed yet, with the hooks, counters and tests behind each claim.+The cryptography and tamper counter pages are references, and the last+page says how to report a vulnerability.++.. toctree::+ :titlesonly:++ security-model+ threat-model+ cryptography+ tamper-counters+ reportingdiff --git a/Documentation/security/reporting.rst b/Documentation/security/reporting.rstnew file mode 100644index 00000000..064051df--- /dev/null+++ b/Documentation/security/reporting.rst@@ -0,0 +1,65 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: All readers++Report a vulnerability+======================++Report a security problem in shirudo privately, so that it can be fixed+before it is public.++Before you begin+----------------++- Reproduce the problem on the ``main`` branch. shirudo has no releases+ or supported release branches yet, so ``main`` is what the policy+ covers.+- Check the :doc:`threat-model`. A gap listed under threats to resolve+ or residual risks is known. A report is still welcome when it shows a+ path the entry does not describe, a larger consequence, or a+ reproduction of an entry marked as a reading of the code.+- Note the commit of shirudo, the kernel tree and commit, and the parts+ of the kernel configuration and command line that matter for the+ problem.++Report the problem+------------------++1. Do not open a public issue, discussion or pull request about it.+2. Open the shirudo repository on GitHub,+ https://github.com/shirudo-dev/shirudo, and go to its Security tab.+3. Select Report a vulnerability.+4. Describe the problem: what an attacker needs, the steps that+ reproduce it, what it breaks, and the IDs of the goals, assumptions+ or threats in the :doc:`threat-model` it affects.+5. Submit the report.++Verify+------++GitHub lists the report as a draft security advisory in the repository's+Security tab, visible to you and the maintainers only. Follow up there.++Policy+------++The repository's `security policy+<https://github.com/shirudo-dev/shirudo/blob/main/SECURITY.md>`__,+``SECURITY.md``, is the policy of record. It says:++- Do not report a vulnerability in a public issue or discussion. Use+ GitHub's Report a vulnerability feature instead.+- shirudo is pre-release and has no stable releases or supported+ release branches. Reports about the ``main`` branch are welcome, to+ harden it before the first release.+- The policy will change as the project matures.++Next steps+----------++- :doc:`threat-model` for what shirudo protects and the known gaps.+- :doc:`/contribute/contributing` if you send the fix yourself, after+ the advisory is agreed.diff --git a/Documentation/security/security-model.rst b/Documentation/security/security-model.rstnew file mode 100644index 00000000..64bdaef9--- /dev/null+++ b/Documentation/security/security-model.rst@@ -0,0 +1,136 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: Security reviewers, Operators++Security model+==============++shirudo restricts the ``bpf()`` system call so that only loaders signed+with the operator's key install BPF code, root included. Every change to+the set of loaded upatches is measured in the TPM, and an operator+checks that measurement with evidence the TPM signs. This page is the short+version of the :doc:`threat-model`, which states each mechanism, its+limits and the gaps not closed yet.++What shirudo provides+---------------------++.. list-table::+ :header-rows: 1+ :widths: 20 32 30 18++ * - Goal+ - Mechanism+ - Limit+ - Threat model+ * - Only signed BPF enters the kernel+ - ``lsm/bpf`` admits only signed loaders from userspace. The kernel+ verifies them against the sealed ``.bpf`` keyring, and+ ``lsm/bpf_prog_load`` admits only that keyring.+ - Any artifact the key ever signed loads. In-kernel BPF users and+ classic BPF are outside the gate.+ - :ref:`T1 <tm-t1>`, R16, R18+ * - Enforcement stays attached+ - Detach, update and foreign attach commands are refused; pins,+ descriptors and the private bpffs mount are guarded.+ - The pins depend on the mount tree; a stopped runtime command+ keeps its descriptors.+ - :ref:`T2 <tm-t2>`, R3, U17+ * - Only shirudo changes its state+ - The seal labels ``/var/lib/shirudo`` and checks every change to+ a labeled inode; keyrings and authorized processes are guarded.+ - Directory marks can be evicted; some operations and other LSMs+ are not covered; offline writes bypass it.+ - :ref:`T3 <tm-t3>`, R15, R19, U5, U12+ * - Every change is measured+ - Loads, unloads, revocations and tree operations extend a TPM NV+ register whose writes ``lsm/tpm_command`` keeps to shirudo.+ - The TPM transport is not authenticated; the config PCR is not+ guarded.+ - :ref:`T5 <tm-t5>`, R4, U8, U9+ * - A verifier can tell+ - ``shirudo attest`` returns a TPM quote and a certification of the+ register; ``shirudo attest verify`` checks them offline.+ - Only the TPM-signed parts are evidence, and only with the+ verifier pinning the key, the binding and the expected state.+ - :ref:`T9 <tm-t9>`, U1+ * - Attempts leave a trace+ - Guards count their refusals in a frozen map that ``shirudo+ status`` and the keepalive report.+ - Some refusals move no counter; telemetry is not authenticated.+ - :ref:`T10 <tm-t10>`, R17+ * - Delivered content is authentic+ - Indexes, tree publications and configs are signed; the kernel+ verifies loaders and config roots.+ - A registry can withhold and replay; any key the kernel trusts for+ dm-verity signs a config.+ - :ref:`T7 <tm-t7>`, :ref:`T11 <tm-t11>`, R8, U2++Main adversary+--------------++The adversary shirudo is built against is root on the target without+the signing key: a compromised administrator account, a container+escape, a persistence implant. Capabilities do not stop it, so shirudo+does not rest on capabilities. A task gains authority only by a+successful exec of a file on the dm-verity runtime image, and the+guards let only such tasks through. Root can still run the runtime binary,+so the command interface is the boundary: root can make shirudo do+anything a shirudo command does, and every such change to the loaded+set is measured.++The other adversaries are unprivileged code, root with mount-namespace+and device control, the network and the registries, a malicious+collector, and the holder of a compromised signing key. The+:ref:`adversaries <tm-adversaries>` section says what each can do.++What shirudo assumes+--------------------++The properties above hold only on a deployment that provides the+:ref:`assumptions <tm-assumptions>`. In brief:++- A trusted kernel with the BPF LSM, the signed-loader ABI and the+ ``tpm_command`` patch.+- Module signature enforcement and lockdown in integrity mode, no+ 32-bit compatibility, no hibernation and no writes under mounted+ file systems.+- Secure Boot with a signed, measured UKI and an authenticated kernel+ command line.+- A kernel whose dm-verity trust path consults only keys trusted to+ sign shirudo configs.+- A TPM 2.0 reachable only through the kernel driver.+- A runtime image without generic tools.+- An operator host that keeps the signing key safe.++shirudo checks only some of these. The pre-flight of ``shirudo init``+checks that the BPF LSM is active and that the kernel has the+signed-loader ABI. It does not check lockdown, the kernel configuration+or the boot chain (U10).++What you must do+----------------++The deployer and the verifier each have a part that no code does for+them. The :ref:`duties <tm-duties>` section lists it in full. The+essentials:++- Build and boot the kernel as :doc:`/operate/hardening` describes.+- Start every shirudo unit from the runtime image, and keep the units'+ environment files empty.+- Verify each target with ``shirudo attest verify`` and always pass+ ``--ak-name``, the binding PCRs, an expected state and the expected+ config root, as :doc:`/operate/attest` describes.+- Treat ``shirudo status``, keepalives and tamper counters as the+ target's own account, and a ``tampered`` status as an incident+ (:doc:`/operate/incident-tampered`).++Related+-------++- :doc:`threat-model` for every mechanism, limit and open gap.+- :doc:`tamper-counters` for what the counters record.+- :doc:`cryptography` for the algorithms.diff --git a/Documentation/security/tamper-counters.rst b/Documentation/security/tamper-counters.rstnew file mode 100644index 00000000..1f4cbff4--- /dev/null+++ b/Documentation/security/tamper-counters.rst@@ -0,0 +1,307 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: Operators, security reviewers++Tamper counters+===============++Each point at which one of shirudo's guards refuses a caller has a+counter. The guard adds one to it when it refuses. The counters live in+the array map ``shirudo_tamper``, which ``init`` creates, freezes and+pins at ``/run/shirudo/bpffs/tamper`` at every boot, so they count this+boot's refusals. No task resets them from userspace; only the hooks add+to them. Threat T10 of the :doc:`threat-model` explains their purpose.++Counters+--------++The name and the meaning are what ``shirudo status`` prints. The hooks+are the section names of the BPF programs in ``bpf/`` that move the+counter.++.. list-table::+ :header-rows: 1+ :widths: 17 31 33 19++ * - Counter+ - Meaning+ - Hooks and condition+ - Errno+ * - ``LoadNotLoader``+ - program load that is not a signed loader+ - ``lsm/bpf``: ``BPF_PROG_LOAD`` of a type other than+ ``BPF_PROG_TYPE_SYSCALL``, every userspace caller+ - ``EACCES``+ * - ``LoadUnsigned``+ - loader-type program load without a signature+ - ``lsm/bpf``: ``BPF_PROG_LOAD`` of a syscall program without a+ signature, every userspace caller+ - ``EACCES``+ * - ``LoadUnverified``+ - program load whose signature the kernel did not verify+ - ``lsm/bpf_prog_load``, every userspace caller+ - ``EACCES``+ * - ``LoadKeyringKind``+ - program signed against a keyring of the wrong kind+ - ``lsm/bpf_prog_load``: a signature verified against the+ built-in, secondary or platform keyring, every userspace caller+ - ``EACCES``+ * - ``LoadKeyring``+ - program signed against a keyring that is not the anchor+ - ``lsm/bpf_prog_load``: a keyring serial other than the frozen+ one, every userspace caller. The kernel records serial 0 for+ ``.bpf``, which the hook does not compare, so this counter does+ not move on the target kernel.+ - ``EACCES``+ * - ``MapCreate``+ - map creation by another executable+ - ``lsm/bpf``: ``BPF_MAP_CREATE``+ - ``EACCES``+ * - ``MapWrite``+ - map update or freeze by another executable+ - ``lsm/bpf``: ``BPF_MAP_UPDATE_ELEM``, ``BPF_MAP_FREEZE``+ - ``EACCES``+ * - ``MapFdWrite``+ - writable map descriptor for another executable+ - ``lsm/bpf_map``: a writable descriptor+ - ``EACCES``+ * - ``ProgRun``+ - test run of a program by another executable+ - ``lsm/bpf``: ``BPF_PROG_TEST_RUN``+ - ``EACCES``+ * - ``ProgAttach``+ - link or raw tracepoint attach by another executable+ - ``lsm/bpf``: ``BPF_LINK_CREATE``, ``BPF_RAW_TRACEPOINT_OPEN``+ - ``EACCES``+ * - ``ObjPin``+ - pin of a BPF object by another executable+ - ``lsm/bpf``: ``BPF_OBJ_PIN``+ - ``EACCES``+ * - ``BpfCommand``+ - detach, update, delete or unclassified bpf() command+ - ``lsm/bpf``: every command not listed elsewhere, such as+ ``BPF_LINK_DETACH``, ``BPF_LINK_UPDATE``, ``BPF_PROG_ATTACH``,+ ``BPF_BTF_LOAD`` and the map deletions, from every userspace+ caller, shirudo included+ - ``EACCES``+ * - ``ExeIdentity``+ - executable change through PR_SET_MM+ - ``lsm/task_prctl``: ``PR_SET_MM_EXE_FILE``, ``PR_SET_MM_MAP``+ - ``EPERM``+ * - ``KeyringWrite``+ - write, unlink, revoke or invalidate on the anchor keyring+ - ``lsm/key_permission``: write, setattr, unlink or a search+ through an unpossessed reference on ``.bpf``, ``.dm-verity``,+ the config key or an enrolled key+ - ``EACCES``+ * - ``PinUnlink``+ - unlink of a pin in the private bpffs+ - ``lsm/inode_unlink`` in the private bpffs+ - ``EPERM``+ * - ``PinRename``+ - rename of a pin in the private bpffs+ - ``lsm/inode_rename``, either directory in the private bpffs+ - ``EPERM``+ * - ``PinXattr``+ - xattr change on a pin in the private bpffs+ - ``lsm/inode_setxattr``, ``lsm/inode_removexattr`` in the private+ bpffs+ - ``EPERM``+ * - ``BpffsUmount``+ - unmount of the private bpffs+ - ``lsm/sb_umount``: the bpffs superblock, every caller+ - ``EPERM``+ * - ``BpffsUmountAbove``+ - unmount of a mount above the private bpffs+ - ``lsm/sb_umount``: an unmount whose subtree or propagation+ reaches the recorded bpffs mount, or a tree the walk cannot+ finish, every caller+ - ``EPERM``+ * - ``BpffsMount``+ - move, mount over or remount of the private bpffs+ - ``lsm/move_mount``, ``lsm/sb_mount``, ``lsm/sb_remount``, every+ caller+ - ``EPERM``+ * - ``SealWrite``+ - write open of a sealed file+ - ``lsm.s/file_open``+ - ``EACCES``+ * - ``SealUnlink``+ - unlink of a sealed file+ - ``lsm.s/inode_unlink``+ - ``EACCES``+ * - ``SealRename``+ - rename of or over a sealed file+ - ``lsm.s/inode_rename``: a labeled source or victim+ - ``EACCES``+ * - ``SealSetattr``+ - truncate, chmod, chown or utimes of a sealed file+ - ``lsm.s/inode_setattr``+ - ``EACCES``+ * - ``SealXattr``+ - xattr change on a sealed file+ - ``lsm.s/inode_setxattr``, ``lsm.s/inode_removexattr``+ - ``EACCES``+ * - ``SealLabel``+ - seal label set by another executable+ - ``lsm.s/inode_setxattr``: the exact name ``security.bpf.shirudo``+ on any inode+ - ``EACCES``+ * - ``SealPtrace``+ - ptrace of a shirudo task+ - ``lsm/ptrace_access_check``+ - ``EACCES``+ * - ``SealPerf``+ - perf event bound to a shirudo task+ - ``lsm/perf_event_alloc``+ - ``EACCES``+ * - ``ExecTraced``+ - exec of shirudo by a traced task+ - ``lsm.s/bprm_check_security`` in the seal object, and+ ``lsm/bprm_check_security`` in the ``bpf2`` object+ - ``EACCES``, or ``EPERM`` from the ``bpf2`` hook+ * - ``SealEntry``+ - entry created, linked or renamed into a sealed directory+ - ``lsm/inode_create``, ``lsm/inode_mkdir``,+ ``lsm/inode_symlink``, ``lsm/inode_mknod``, ``lsm/inode_link`` in+ the seal object, and ``lsm.s/inode_rename`` for the destination+ - ``EACCES``+ * - ``PerfAttach``+ - program attached to a perf event by another executable+ - ``lsm/file_ioctl``, ``lsm/file_ioctl_compat``: the ioctl number+ of ``PERF_EVENT_IOC_SET_BPF`` on any file+ - ``EACCES``+ * - ``PinEntry``+ - directory or link made in the private bpffs by another executable+ - ``lsm/inode_mkdir``, ``lsm/inode_symlink``, ``lsm/inode_link`` in+ the ``bpf2`` object+ - ``EPERM``+ * - ``SealCopyUp``+ - overlay copy-up of a sealed inode+ - ``lsm/inode_copy_up``+ - ``EPERM``+ * - ``Kexec``+ - kexec image or initramfs load+ - ``lsm/kernel_load_data``, ``lsm/kernel_read_file``, every caller+ - ``EPERM``+ * - ``TpmExtend``+ - extension of shirudo's TPM NV index by another executable+ - ``lsm/tpm_command``: ``TPM2_NV_Extend`` of the frozen index+ without runtime authority, or a command too short to inspect+ from any caller+ - ``EACCES``+ * - ``ObjGet``+ - pin, map or link opened by another executable+ - ``lsm/bpf``: ``BPF_OBJ_GET``, ``BPF_MAP_GET_FD_BY_ID``,+ ``BPF_LINK_GET_FD_BY_ID``; ``lsm/bpf_map``: a read-only+ descriptor; ``lsm/file_open`` in the ``bpf2`` object: a+ non-directory inode in the private bpffs+ - ``EACCES``++Unless the row says every caller, a task with runtime authority is+not refused and moves nothing.++Refusals without a counter+--------------------------++A zero counter does not mean nobody tried. These refusals move no+counter:++.. list-table::+ :header-rows: 1+ :widths: 45 55++ * - Refusal+ - Where+ * - The kernel's own signature errors at ``BPF_PROG_LOAD``, such as+ ``ENOKEY``, ``EKEYREJECTED``, ``EPERM`` for a caller-supplied+ keyring and ``EACCES`` for CO-RE relocations+ - The kernel, before ``lsm/bpf_prog_load`` runs+ * - rmdir in the private bpffs+ - ``lsm/inode_rmdir``+ * - Inode and mount operations on the ``/run/shirudo`` tmpfs+ - The ``bpf2`` inode guards and ``lsm/sb_umount``,+ ``lsm/move_mount``, ``lsm/sb_mount``, ``lsm/sb_remount``+ * - Unmount, move, mount over and remount of the runtime and config+ image mounts+ - ``lsm/sb_umount``, ``lsm/move_mount``, ``lsm/sb_mount``,+ ``lsm/sb_remount``+ * - Device-mapper control ioctls+ - ``lsm/file_ioctl``, ``lsm/file_ioctl_compat``+ * - A dm-verity mapping that is already recorded, or whose root+ cannot be read+ - ``lsm.s/bdev_setintegrity``+ * - Exec of a runtime file under a seccomp filter, and an exec for+ which task storage cannot be allocated+ - ``lsm.s/bprm_check_security``+ * - A fork that cannot copy a task mark+ - ``lsm/task_alloc``+ * - A new inode under a marked directory that cannot receive the+ label+ - ``lsm/inode_init_security``+ * - Executable mappings of an authorized task that are writable or+ not from the runtime image+ - ``lsm/mmap_file``, ``lsm/file_mprotect``+ * - Refusals by another LSM ordered before ``bpf``+ - The kernel calls no BPF program for an operation another LSM+ already refused+ * - shirudo's own refusals, such as ``tampered``,+ ``payload_mismatch`` and ``attach_scope_mismatch``+ - Userspace++Reading the counters+--------------------++Read the counters with ``shirudo status`` started from the runtime+image, the way the drop-in that ``shirudo-gen-runtime --unit-output``+generates starts ``init``. A binary outside the runtime image cannot+open the counter map, and its attempt moves ``ObjGet``.++``shirudo status`` prints the section ``Tamper attempts (refused this+boot):`` with one line per counter that is not zero: its name, its+count and its meaning. It prints ``none`` when every counter is zero,+and ``(none recorded: init has not pinned the counters this boot)``+before ``init`` has run.++``shirudo status --json`` carries every counter under+``tamper_attempts``, with the sum in ``total`` and each counter by name+in ``counters``, so a collector's keys stay the same from one record to+the next. The value is ``null`` before ``init`` has pinned the map.++The keepalive, ``shirudo status --otel``, sends the same status as an+OTLP log record and adds the total as the attribute+``shirudo.tamper_attempts``. The attribute is absent when the counters+cannot be read.++What a non-zero counter means+-----------------------------++A counter that moved means that a guard refused an operation this boot.+The refusal is what moved it: the operation did not happen.++A non-zero counter does not mean:++- That the target is compromised. A refused attempt is an attempt.+- That root made the attempt. ``lsm/bpf`` runs before the kernel checks+ capabilities, so an unprivileged process moves the counters of+ ``bpf()`` commands.+- That a foreign program made it. ``BpfCommand``, ``Kexec``,+ ``BpffsUmount``, ``BpffsUmountAbove``, ``BpffsMount`` and a malformed+ TPM command count refusals of shirudo's own tasks too, and a shirudo+ binary outside the runtime image moves ``ObjGet``.+- That the operation was the one the meaning names. ``PerfAttach``+ counts the ioctl number on any file, whatever the device.++A counter does not change the verdict of ``shirudo status``. It is the+target's own account, like the rest of the status, and it travels+unauthenticated to the collector. Only ``shirudo attest verify`` is+evidence. To act on a counter, see :doc:`/operate/incident-tampered`.++Related+-------++- :doc:`threat-model`, threat T10, for the purpose and the limits.+- :doc:`/internals/enforcement` for the hooks.diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rstnew file mode 100644index 00000000..315fb09d--- /dev/null+++ b/Documentation/security/threat-model.rst@@ -0,0 +1,1782 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: Kernel developers, security reviewers++Threat model+============++This page states what shirudo protects, against whom, by which+mechanism, and where each mechanism stops. It describes the code in the+tree. Where the code and this page disagree, the code is right and the+page is a bug.++Purpose and how to read it+--------------------------++The page serves reviewers who judge whether the design holds, and+contributors who change a security-relevant path. Read it before you+change signature verification, an LSM hook, the TPM paths, the seal or+the artifact format. A change that keeps the shape of the code but+breaks a property below ships a false sense of safety to targets that+are hard to patch. :doc:`security-model` gives the short version for+operators.++Every entry has a stable ID that commits, issues and other pages cite:++.. list-table::+ :header-rows: 1+ :widths: 22 78++ * - IDs+ - Meaning+ * - G1 to G8+ - Security goals: what shirudo sets out to provide.+ * - A1 to A15+ - Assumptions the goals depend on, and whether shirudo checks them.+ * - ADV-A to ADV-G+ - Adversaries.+ * - T1 to T14+ - Threats shirudo addresses, each with a fact box.+ * - R1 to R22+ - Residual risks: known and bounded limits of the mechanisms.+ * - U1 to U17+ - Threats to resolve: gaps in the code that are not closed yet.+ * - D1 to D9+ - Deferred mitigations that are in scope.++Each threat is explained in prose and then summarized in a fact box.+The fields of the box are:++- Adversary: who mounts the threat.+- Enforced at: the BPF LSM programs that refuse it, by their section+ name in ``bpf/``.+- Refusal: what the caller sees.+- Counters: the tamper counters the refusal moves, described in+ :doc:`tamper-counters`.+- Tests: the target tests under ``testing/functional/`` that exercise+ the refusal.+- Residual: the residual risks and threats to resolve that bound it.++A claim on this page is one of three kinds, and the text says which. A+hook in the kernel enforces it, shirudo checks it in userspace, or an+operator detects it by verifying TPM evidence. The three are not+interchangeable. A userspace check runs in a process that root can+start, and detection needs a verifier who asks the right questions.++Security goals+--------------++.. list-table::+ :header-rows: 1+ :widths: 8 64 28++ * - ID+ - Goal+ - Threats+ * - G1+ - After ``init`` has attached the gates, every eBPF program that a+ userspace process loads through ``bpf()`` is a signed loader the+ kernel verified against the sealed ``.bpf`` keyring, or a+ program such a loader loads.+ - T1, T4+ * - G2+ - The enforcement programs and the loaded upatches stay attached+ until shirudo removes them or the target reboots.+ - T2, T6+ * - G3+ - Only shirudo changes its writable state, its keyrings and its+ authorized processes.+ - T3, T11+ * - G4+ - Every change to the set of loaded upatches is measured in the+ TPM before or as it takes effect.+ - T5, T12, T14+ * - G5+ - A verifier tells a target in the expected state from one that is+ not by TPM-signed evidence, not by the target's own report.+ - T9+ * - G6+ - A refused attempt leaves a trace on the target.+ - T10+ * - G7+ - The artifacts, packages, trees and configs a target accepts are+ the ones the operator's keys signed.+ - T7, T8, T11+ * - G8+ - No process without runtime authority reads or drains the maps+ and pins of shirudo and its upatches.+ - T13++The goals hold only together with the assumptions below. None of them+says that an upatch is correct: shirudo establishes provenance, not+correctness.++.. _tm-assumptions:++Assumptions+-----------++Each assumption is a property of the deployment that the threats rely+on. The last column says whether shirudo checks it. Where it does not,+a deployment that breaks the assumption runs without an error and+without the protection.++.. list-table::+ :header-rows: 1+ :widths: 6 40 34 20++ * - ID+ - Assumption+ - Why it matters+ - Checked by shirudo+ * - A1+ - The kernel is trusted: the BPF verifier and JIT, the keyring and+ PKCS#7 code, dm-verity and the TPM driver behave as specified.+ - Every hook and every signature check runs in it.+ - No.+ * - A2+ - The BPF LSM is active. Another LSM ordered before ``bpf`` can+ refuse an operation first, and the BPF program then does not+ run.+ - All enforcement is BPF LSM programs.+ - Yes, the pre-flight check ``bpf_lsm_active`` reads+ ``/sys/kernel/security/lsm``. The order of the LSMs is not+ checked.+ * - A3+ - The kernel has the signed-loader ABI of the bpf-next tree shirudo+ targets and the ``tpm_command`` LSM hook. Upstream has no such+ hook, and shirudo carries it as+ ``kernel/0002-tpm-Let-LSMs-inspect-userspace-commands.patch``.+ - T1 needs the ABI, T5 the hook.+ - Yes. The pre-flight check ``signed_loader_kernel_abi`` tests the+ ABI. Without the hook the ``bpf2`` object does not load and+ ``init`` fails.+ * - A4+ - The kernel refuses unsigned modules (``CONFIG_MODULE_SIG`` with+ enforcement) and runs with lockdown in integrity mode+ (``CONFIG_SECURITY_LOCKDOWN_LSM`` and ``lockdown=integrity``).+ - An unsigned module is kernel code of root's choosing. Module+ signatures alone leave root ``/dev/mem``, MSR writes, port I/O,+ PCI BAR access, debugfs writes, ACPI table overrides and+ hibernation, each a way to change or replace the running+ kernel, and lockdown refuses them. Lockdown refuses an unsigned+ module only on a kernel that checks module signatures at all.+ - No, see U10. In confidentiality mode the kernel withholds+ ``bpf_probe_read_kernel()`` from BPF programs, which shirudo's+ own programs use, so that mode would stop ``init``. This is a+ reading of the kernel source and is not tested.+ * - A5+ - 32-bit compatibility is off: ``CONFIG_COMPAT=n``, and on x86-64+ also ``CONFIG_IA32_EMULATION=n`` and ``CONFIG_X86_X32_ABI=n``.+ - The device-mapper and perf checks hook the native and the compat+ ioctl paths; no other 32-bit entry point is considered.+ - No.+ * - A6+ - The target boots with Secure Boot from a signed, measured UKI+ whose initrd carries shirudo, its bootstrap settings and the+ runtime root hash, and systemd measures the ``enter-initrd`` and+ ``leave-initrd`` phases into PCR 11.+ - ``init`` takes the runtime root hash from the initrd's+ ``/etc/shirudo/shirudo.conf``. The binding of the register to+ the initrd rests on the PCR 11 phase values.+ - No. shirudo checks neither Secure Boot nor where the initrd came+ from. ``init`` warns when PCR 11 holds no phase measurement.+ * - A7+ - Only keys trusted to sign shirudo configs can sign a dm-verity+ root. The kernel tries ``.builtin_trusted_keys`` (or the+ secondary keyring with+ ``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_SECONDARY_KEYRING``), then+ the platform keyring with+ ``CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_PLATFORM_KEYRING``, and+ only then ``.dm-verity``. Both options are off and no built-in+ certificate belongs to a holder not trusted for configs.+ - A config chooses repository certificates, vouched signers,+ revocations and export endpoints.+ - No, see U2. The test ``t5102`` shows a built-in certificate+ signing an accepted config root.+ * - A8+ - The TPM is reachable only through the kernel driver: no+ ``i2c-dev`` or ``spidev`` driver that root could bind to the+ TPM's bus, and no MMIO access to it (A4).+ - ``lsm/tpm_command`` sees only commands written to ``/dev/tpm0``+ and ``/dev/tpmrm0``.+ - No.+ * - A9+ - Hibernation is unavailable. Lockdown in integrity mode disables+ it.+ - A hibernation image is kernel memory on disk that root can+ change before resume, through ``/dev/snapshot`` among others.+ The behavior of the register across hibernation is not analyzed+ here.+ - No.+ * - A10+ - No process writes to the block device under a mounted file+ system: ``CONFIG_BLK_DEV_WRITE_MOUNTED=n``.+ - The seal guards file operations. A write to the device under+ ``/var/lib/shirudo`` bypasses it.+ - No. See R19.+ * - A11+ - The kernel command line is authenticated as part of the UKI. It+ carries ``lsm=`` with ``bpf``, ``lockdown=integrity``,+ ``bpf.keyring_unsealed=1`` and ``dm_verity.keyring_unsealed=1``,+ and nothing that masks or skips ``shirudo-initrd.service``.+ - The command line decides whether the LSM runs, whether the+ keyrings accept shirudo's keys and whether ``init`` runs at all.+ - Partly. ``init`` refuses a ``.bpf`` keyring the kernel sealed+ empty at boot, which is what a boot without+ ``bpf.keyring_unsealed=1`` leaves.+ * - A12+ - The operator host is trusted: the signing key, clang/LLVM,+ libbpf, ``veritysetup`` and ``mkfs.ext4``.+ - They produce every signature and every image.+ - No.+ * - A13+ - The initrd is a dracut initrd with systemd 256 or newer and the+ phase measurement, and no other component restricts ``.bpf`` or+ ``.dm-verity`` before ``init``.+ - ``shirudo-initrd.service`` orders itself after ``tpm2.target``.+ A keyring sealed by someone else leaves no room for shirudo's+ keys.+ - Partly. ``init`` refuses a ``.bpf`` keyring that another task+ restricted or filled (``t6129``).+ * - A14+ - The runtime image holds no executable that exposes a generic+ primitive: a shell or interpreter, ``bpftool``, TPM tools,+ ``keyctl``, mount or device-mapper tools, a file editor.+ - Authority follows the exec, not the program. Every executable on+ the runtime image hands root shirudo's authority.+ - No.+ * - A15+ - The TPM is a correct TPM 2.0 with RSA-3072 support and an+ endorsement hierarchy without an authorization value.+ - The register, the NV writer and the attestation key live in it.+ - Partly. ``init`` fails without a TPM and when the attestation+ key cannot be created under the endorsement hierarchy.++Assets+------++.. list-table::+ :header-rows: 1+ :widths: 24 30 46++ * - Asset+ - Where it lives+ - What protects it+ * - Signing private key+ - The operator host, ``signing_key.pem`` beside ``cert.der``+ - Operator custody (A12). The signing code refuses a key file whose+ mode is not ``0600``. It never reaches a target.+ * - Enrolled BPF certificates+ - ``.bpf`` keyring+ - Sealed by ``init`` with a reject-all restriction;+ ``lsm/key_permission`` (T3).+ * - Config certificate+ - ``.dm-verity`` keyring, from the runtime image+ - Sealed by ``init``; ``lsm/key_permission`` (T3). The kernel also+ trusts the keyrings A7 names.+ * - Runtime image and its root hash+ - A dm-verity mapping mounted at ``/run/shirudo/runtime``; the root+ hash in the initrd's bootstrap settings and in the identity map+ - dm-verity, ``lsm.s/bdev_setintegrity`` and the mount hooks (T11);+ the boot chain (A6).+ * - Config images+ - Cache under ``/var/lib/shirudo/images``; the active one mounted+ at ``/run/shirudo/config``+ - The kernel's root-hash signature check, dm-verity, the seal on+ the cache (T11).+ * - Enforcement links and upatch links+ - Pins in the private bpffs at ``/run/shirudo/bpffs``+ - The bpffs inode and mount guards, the descriptor checks (T2).+ * - Identity map+ - ``shirudo_bpffs_sb``, pinned as ``identity``+ - Frozen by ``init``; opened only by tasks with runtime authority+ (T13). It holds the keyring serials, the runtime root, the AK+ name, the NV writer seed and public key, and the NV index.+ * - Task marks+ - ``shirudo_tasks`` task storage, pinned as ``task_authority``+ - Frozen against ``bpf()`` writes; only the seal's programs set a+ mark (T3).+ * - Device records and expected roots+ - ``shirudo_devices`` (frozen) and ``shirudo_roots`` (not frozen,+ written by authorized tasks for their own config mapping)+ - The descriptor checks (T13); ``lsm.s/bdev_setintegrity`` (T11).+ * - Tamper counters+ - ``shirudo_tamper``, pinned as ``tamper``+ - Frozen; only the hooks add to it (T10).+ * - Payload binding of a pin+ - The ``security.bpf.shirudo.payload`` xattr on each upatch pin+ directory+ - ``lsm/inode_setxattr`` and ``lsm/inode_removexattr`` in the+ private bpffs (T4).+ * - Measurement register+ - TPM NV index ``0x01818E00``, cleared at TPM reset+ - Its write policy and ``lsm/tpm_command`` (T5).+ * - NV writer+ - An RSA-3072 owner-hierarchy primary, recreated from the seed in+ the identity map+ - The private key never leaves the TPM; the seed is not secret+ (T5).+ * - Attestation key+ - An ECDSA P-256 endorsement-hierarchy primary; its name in the+ identity map and with the operator+ - The TPM; the verifier's pin of its name (T9).+ * - Eventlog+ - ``/var/lib/shirudo/eventlog``; the initrd's record at+ ``/run/shirudo/eventlog.pending`` until adoption+ - The seal (T3) and replay against the register (T5).+ * - Writable state+ - ``/var/lib/shirudo``: archived upatches, keys, package and tree+ state, the config selection journal+ - The seal (T3). Across reboots only signatures and the register+ (R19).+ * - TPM owner password+ - ``tpm.owner_auth`` in the runtime image's ``shirudo.conf``+ - Nothing on the target: root reads it (R20).+ * - Registry and collector credentials+ - The environment of the bpm and export units, Docker and registry+ auth files, ``/etc/shirudo/map-export.env``+ - File permissions only; root reads them (U3).+ * - Host EnvironmentFiles+ - ``/etc/shirudo/bpm/environment``,+ ``/etc/shirudo/map-export.env``, ``/etc/shirudo/init.env``+ - Nothing: root writes them, and the processes that read them hold+ runtime authority (U3).+ * - Repository certificates+ - The signed config image+ - The config signature (T11).+ * - Status, reports and telemetry+ - The target's output and the collector+ - Nothing. They are the target's own account (R17).++.. _tm-trust-boundaries:++Trust boundaries+----------------++Figure 1 shows the parties and where trust ends.++.. figure:: /images/security-trust-boundaries.svg+ :alt: The operator host and the verifier on the left, the untrusted+ network with the registry and the collector in the middle, and+ the target on the right with its TCB of runtime tasks, kernel+ and TPM below the untrusted root processes and the sealed+ state. The evidence box splits the TPM-signed quote and NV+ certification from the target's own account.++ Figure 1. Trust boundaries and the evidence boundary.++The target TCB is the kernel with its configuration and command line+(A1, A4, A11) and the ``tpm_command`` patch; the firmware, boot loader+and UKI (A6); the TPM (A15); the initrd and every unit it runs before+``shirudo-initrd.service`` completes; and the runtime image. The+runtime image holds the shirudo binary with its two embedded BPF+objects, ``bpf2`` and ``seal``, the libraries it links (OpenSSL,+libcurl, tpm2-tss, libbpf, libelf, zlib, zstd, LuaJIT, the C library),+every other executable on the image (A14), the certificates+and the bootstrap settings. The memory of every task with runtime+authority is in the TCB too, the Lua decoders it runs included.++Every other process on the target, root with every capability among+them, is outside the TCB and constrained by it. Root is not trusted+because it is root. A task gains authority only by a successful exec of+a file on the runtime image (T3).++The operator TCB is the operator host, the signing key, clang/LLVM,+libbpf, ``veritysetup`` and ``mkfs.ext4`` (A12). The verifier is a+party of its own: it trusts the TPM's signatures and the values it+pinned, and nothing the target says about itself.++Outside both are the OCI registries, the network, the collectors, their+TLS certificates, and whatever remote access an administrator uses. A+registry can withhold and replay signed content. It cannot forge an+upatch, because the kernel verifies every loader (T1). What a registry+can do to indexes, tree publications and the transport is described in+T7 and U3 to U4.++The evidence boundary runs through the attestation document. Only two+parts of what ``shirudo attest`` produces are authenticated: the+``TPM2_Quote`` over the selected PCRs and the ``TPM2_NV_Certify`` of the+register, both signed by the attestation key over the verifier's nonce.+Everything else in the document is the target's own account: the+eventlog records, the config history, the fields of the init record+(``bound_in``, ``ts``, ``boot_id``, the certificate list and the set),+and the logs. A record proves something only through what folds into+the certified register value, into the certified index name or into a+quoted PCR. A check that depends on which records are present, such as+one init record per TPM reset, holds only for a document the target did+not trim. A check on a field no digest covers, such as+``--require-initrd`` on ``bound_in``, holds only for an honest target.++.. _tm-adversaries:++Adversaries+-----------++ADV-A, unprivileged local code+ Constrained by the kernel. shirudo adds nothing it needs, but every+ caller reaches ``lsm/bpf`` before the kernel checks capabilities, so+ unprivileged code can move the ``bpf()`` tamper counters (T10).++ADV-B, root on the target without the signing key+ The main adversary: a compromised administrator account, a container+ escape, a persistence implant. It issues any system call, writes any+ file the kernel lets root write, ptraces whatever the kernel allows, loads+ signed modules and runs any binary, the runtime image's included.+ shirudo must keep it from loading BPF, from detaching or replacing+ shirudo's BPF, from changing shirudo's state unnoticed, and from+ making a tampered target look healthy to a verifier.++ADV-C, root with mount-namespace and device control+ A refinement of ADV-B that uses private mount namespaces, bind+ mounts over shirudo's paths, overlays, substitute device nodes and+ ``/proc`` substitution to show a shirudo command a different world.+ T3, T11 and T14 address parts of it. R22, U8 and U9 are the parts+ that remain.++ADV-D, network and registry+ Towards the target: observes, drops, delays and replays traffic, and+ serves any content a registry holds, old signed content included+ (T7, R8). Towards the operator: a registry from which ``shirudo bpm+ config update --base-package oci://`` takes a package runs commands+ on the operator host (U14), and so can become ADV-F.++ADV-E, malicious collector+ Receives keepalives and map snapshots. It can refuse or delay them+ and put a short error message into the target's log. It cannot+ change enforcement or state. What it receives is unauthenticated+ (R17).++ADV-F, holder of a compromised or revoked signing key+ Its blast radius: every target whose ``.bpf`` keyring holds the key+ loads any loader it signed, until a config that revokes the key is+ activated there (R13). It unloads any upatch whose payload digest it+ knows (R1). Its loaders run ``bpf()`` calls from kernel context,+ which both gates admit, so it can open shirudo's maps and attach+ programs that write them: the maps are frozen against ``bpf()``+ writes, not against programs. An upatch does what its author wrote,+ disabling enforcement included. Keys it vouched for stay admitted+ where a config lists them, and if it is the runtime image's primary+ key it signs tree publications that revocation does not reach (U13).+ A key that signs configs (A7) chooses repositories, vouched signers+ and revocations.++ADV-G, physical access and TPM hardware+ Out of scope: bus interposers, TPM fault injection, cold boot, and+ offline changes to the disk beyond what R19 states.++Threats addressed+-----------------++.. _tm-t1:++T1 Loading unsigned BPF+~~~~~~~~~~~~~~~~~~~~~~~++Root's most direct move is to load a BPF program of its own: a kprobe,+an LSM program that allows what shirudo refuses, a program that writes+kernel data. The kernel would allow it, since root holds ``CAP_BPF`` and+``CAP_SYS_ADMIN``. Capabilities cannot tell root from shirudo, so the+gate rests on what root does not hold: the operator's signing key.++``lsm/bpf`` runs at the entry of every ``bpf()`` call, before the kernel+acts on the attributes or checks capabilities. For ``BPF_PROG_LOAD`` from+userspace it admits only a ``BPF_PROG_TYPE_SYSCALL`` program that+carries a signature (``LoadNotLoader`` and ``LoadUnsigned`` otherwise).+The kernel then verifies that signature in+``bpf_prog_verify_signature()``, over the loader's instructions and its+frozen metadata map, against the keyring that ``attr.keyring_id``+names. Booted with ``bpf.keyring_unsealed=1``, the kernel refuses a+caller-supplied user keyring with ``EPERM``.++``lsm/bpf_prog_load`` runs after that verification. It admits a+userspace load only when the kernel recorded a verified signature+against a keyring of the BPF kind, which is the ``.bpf`` keyring+``init`` enrolled and sealed (``LoadUnverified`` and ``LoadKeyringKind``+otherwise). A signature that verifies against the built-in, secondary+or platform keyring fails here. The hook also compares the keyring+serial with the one ``init`` froze (``LoadKeyring``), but the kernel+records serial 0 for the ``.bpf`` keyring and the hook skips the+comparison for 0, so on the target kernel the kind check is what pins+the keyring.++Root cannot assemble a validly signed loader outside shirudo either. A+loader needs its metadata map, and ``BPF_MAP_CREATE`` needs runtime+authority (``MapCreate``), as do the routes to an existing map (T13).+The programs a verified loader loads run in kernel context, and both+hooks admit calls whose ``kernel`` argument is set.++A modified loader, one signed by a foreign key, or one whose certificate+the keyring does not hold fails in the kernel's signature check, before+``lsm/bpf_prog_load``, with the kernel's own error such as ``ENOKEY`` or+``EKEYREJECTED``. Those refusals move no counter.++The gates cover ``bpf()`` from userspace. In-kernel BPF users, classic+BPF and programs loaded before ``init`` are outside them (R18, R7), and+any loader the key ever signed passes (R16).++.. rst-class:: facts++:Adversary: ADV-B, root on the target without the signing key+:Enforced at: ``lsm/bpf``, ``lsm/bpf_prog_load``+:Refusal: ``EACCES`` from ``bpf()``; the kernel's signature errors, such+ as ``ENOKEY``, ``EKEYREJECTED``, or ``EPERM`` for a caller-supplied+ keyring+:Counters: ``LoadNotLoader``, ``LoadUnsigned``, ``LoadUnverified``,+ ``LoadKeyringKind``, ``MapCreate``+:Tests: ``t6102``, ``t6103``, ``t6104``, ``t6107``, ``t6108``, ``t6138``+:Residual: R7, R16, R18++.. _tm-t2:++T2 Detaching or replacing enforcement+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++A BPF program stays attached while something references its link: a+pin in a bpffs or an open descriptor. shirudo's commands exit after each+operation, so the pins in the private bpffs at ``/run/shirudo/bpffs`` are+the only lasting references to the enforcement links and the upatch+links. After a refused load, root's next move is to drop those+references, or to take one of its own that outlives them.++``lsm/bpf`` refuses to every userspace caller, shirudo included, the+commands that detach or replace a link or a program:+``BPF_LINK_DETACH``, ``BPF_LINK_UPDATE``, ``BPF_PROG_ATTACH``,+``BPF_PROG_DETACH``, ``BPF_BTF_LOAD``, the map deletions, and every+command it does not classify, including commands a newer kernel adds+(``BpfCommand``). It leaves ``BPF_LINK_CREATE``,+``BPF_RAW_TRACEPOINT_OPEN`` and ``BPF_OBJ_PIN`` to tasks with runtime+authority (``ProgAttach``, ``ObjPin``). Root therefore cannot attach a+vetted program at a site of its choosing, or pin an object into the+private bpffs.++A link descriptor keeps the link attached after shirudo removes the pin+for an unload, a revocation or the undo of a refused load, and no LSM+hook sees a link descriptor being handed out. ``lsm/bpf`` therefore+refuses ``BPF_OBJ_GET``, ``BPF_MAP_GET_FD_BY_ID`` and+``BPF_LINK_GET_FD_BY_ID`` to tasks without runtime authority, and+``lsm/file_open`` in the ``bpf2`` object refuses them the opening of any+non-directory inode in the private bpffs (``ObjGet``). Directories stay+listable. ``BPF_PROG_GET_FD_BY_ID`` and ``BPF_BTF_GET_FD_BY_ID`` stay+open, because a descriptor of a program type shirudo ships attaches+nowhere without the commands above or the ioctl below (R18).++The one attach that does not pass through ``bpf()`` is+``PERF_EVENT_IOC_SET_BPF``, which binds a program reached by id to a+perf event of the caller's. ``lsm/file_ioctl`` and+``lsm/file_ioctl_compat`` keep that ioctl number to tasks with runtime+authority (``PerfAttach``).++In the private bpffs, unlink, rename, mkdir, symlink, hard link, rmdir+and xattr changes need runtime authority (``PinUnlink``, ``PinRename``,+``PinEntry``, ``PinXattr``; rmdir is refused without a counter). The+VFS removes a rename's victim without asking ``inode_unlink``, so the+rename hook checks both directories. A symbolic link in place of a pin+directory would send the next load's pins into a bpffs of root's, and a+hard link to a pin would keep a link alive past its unlink.++The pins live as long as the bpffs superblock, which goes with its last+mount. ``lsm/sb_umount``, ``lsm/move_mount``, ``lsm/sb_mount`` and+``lsm/sb_remount`` refuse every caller, shirudo included, an unmount, a+move, a mount over or a remount of the private bpffs (``BpffsUmount``,+``BpffsMount``). The kernel asks ``sb_umount`` only about the mount it+was given, so the hook also walks what the unmount would take, the+subtree and its propagation peers and slaves, from the bpffs mount+``init`` recorded, and refuses an unmount that reaches it+(``BpffsUmountAbove``). The walk runs without the namespace lock,+within fixed bounds of 1024 mounts, 32 levels and 4 masters, and+refuses a tree it cannot finish. The tmpfs at ``/run/shirudo`` gets the+same treatment without counters: no caller unmounts, moves or remounts+it, and only authorized tasks mount onto it.++Root also controls part of the site a load attaches at, since root+runs ``shirudo upatch load``. A ``cgroup_skb`` program attaches at the+root of the caller's cgroup namespace, a ``netfilter`` program in the+caller's network namespace, and a kprobe through the PMU that sysfs+names. The load compares the link the kernel reports with the signed+attach metadata before it pins the link, and refuses+``attach_scope_mismatch``.++.. rst-class:: facts++:Adversary: ADV-B, root on the target without the signing key+:Enforced at: ``lsm/bpf``, ``lsm/file_open``, ``lsm/file_ioctl``,+ ``lsm/file_ioctl_compat``, ``lsm/inode_unlink``,+ ``lsm/inode_rename``, ``lsm/inode_mkdir``, ``lsm/inode_symlink``,+ ``lsm/inode_link``, ``lsm/inode_rmdir``, ``lsm/inode_setxattr``,+ ``lsm/inode_removexattr``, ``lsm/sb_umount``, ``lsm/move_mount``,+ ``lsm/sb_mount``, ``lsm/sb_remount``+:Refusal: ``EACCES`` from ``bpf()``, from opening a pin and from the+ perf ioctl; ``EPERM`` from the inode and mount guards;+ ``attach_scope_mismatch`` from ``shirudo upatch load``+:Counters: ``BpfCommand``, ``ProgAttach``, ``ObjPin``, ``ObjGet``,+ ``PerfAttach``, ``PinUnlink``, ``PinRename``, ``PinEntry``,+ ``PinXattr``, ``BpffsUmount``, ``BpffsUmountAbove``, ``BpffsMount``+:Tests: ``t6105``, ``t6106``, ``t6107``, ``t6108``, ``t6109``,+ ``t6116``, ``t6119``, ``t6120``, ``t6121``, ``t6138``+:Residual: R1, R2, R3, U17++.. _tm-t3:++T3 Tampering with shirudo's files and process+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++shirudo keeps its archive of loaded upatches, the eventlog, the keys,+the package and tree state, the config selection journal and the image+cache under ``/var/lib/shirudo``. Root owns that file system, and+neither permissions nor ownership stop root. A changed archive would be+restored at the next boot, a truncated eventlog would make the register+unexplainable, and a planted file would be taken for shirudo's own.++The seal (``bpf/seal.c`` and ``bpf/seal.h``) marks shirudo's inodes+with the extended attribute ``security.bpf.shirudo`` and checks every+operation on a marked inode against the caller's authority. ``init``+labels the existing tree on the run that brings enforcement up, before+the seal attaches. On every later run a state root without the label is+refused, since it is a tree bound over the path rather than the one+``init`` sealed (``t6123``). For a labeled inode, a write open, an+unlink, either end of a rename, a setattr (truncate, chmod, chown,+utimes) and an xattr change need runtime authority (``SealWrite``,+``SealUnlink``, ``SealRename``, ``SealSetattr``, ``SealXattr``). Only an+authorized task sets the exact label, on any inode (``SealLabel``).++The label is a public constant, the same on every build. It marks a+target and never grants authority: a file system root mounts can carry+it, and a binary that carries it gains nothing. A label read that fails+with an error other than ``ENODATA``, ``EOPNOTSUPP``, ``EACCES`` or+``EPERM`` requires authority, and so does a failure to allocate the+seal's scratch memory. The two permission errors count as unlabeled+because the kernel checks read permission for the caller before it+returns the label (U12).++The seal keeps a mark in inode storage on every labeled directory it+has seen since the inode came into memory. A new inode under a marked+directory receives the label inside the transaction that creates it+(``lsm/inode_init_security``), and a marked directory takes new entries,+by create, mkdir, symlink, mknod, hard link or rename, only from+authorized tasks (``SealEntry``). shirudo's writers hold the parent+directory open while they create, which keeps the mark in memory. An+overlay copy-up of a marked inode is refused (``SealCopyUp``), so a+write through an overlay root mounts over sealed state fails instead of+landing in root's upper directory. Where the mark is absent, R15+applies.++shirudo opens sealed state without following symbolic links and takes+no entry without the label for its own: ``init`` ignores such an entry+rather than labeling, following or restoring it. A path that root+names for shirudo to write, a report, an export, evidence or a+download, must be a regular file without the label that is not reached+through a symbolic link and not created under a labeled directory. The+contents of a config image are read from the descriptor of its verified+root with ``openat2(2)`` and ``RESOLVE_BENEATH``, never through a+``/proc/<pid>/fd`` path that root could mount over.++The ``.bpf`` and ``.dm-verity`` keyrings are sealed with+``KEYCTL_RESTRICT_KEYRING`` and no restriction type, so the kernel+rejects every further link. ``init`` refuses a keyring that holds+anything besides the trusted certificates, a nested keyring or a key it+cannot describe included, and one that another task restricted.+``lsm/key_permission`` refuses write, setattr, unlink and search+through an unpossessed reference, on both keyrings, the config key and+the enrolled keys, to tasks without authority (``KeyringWrite``). That+covers clear, unlink, revoke, invalidate, a permission change and a+timeout. Viewing, reading and linking a key elsewhere stay open, and+the kernel's own signature search uses a possessed reference.++Authority is a mark in task storage. At every exec the seal stages a+candidate, and when the exec commits the candidate becomes the mark. A+task becomes authorized only by a successful exec of a file that sits+directly on the runtime image ``init`` recorded, not through an overlay,+while the task is neither traced nor under a seccomp filter. Fork+copies the mark, a failed exec keeps it, and a successful exec of+anything else clears it. The initrd's ``init`` process receives a+bootstrap mark through a pidfd before the gates attach.++An authorized process is protected against being taken over:++- ``lsm/ptrace_access_check`` refuses every ptrace mode against a marked+ task: attach, ``/proc/<pid>/mem``, ``/proc/<pid>/fd``,+ ``pidfd_getfd(2)`` and ``process_vm_readv(2)`` (``SealPtrace``).+- ``lsm/perf_event_alloc`` refuses a perf event bound to a marked task+ (``SealPerf``). Events on all tasks of a CPU, and events opened on a+ task before the exec that marks it, are not checked (D9).+- The exec of a runtime file by a traced task is refused+ (``ExecTraced``), and so is one under a seccomp filter, without a+ counter.+- ``lsm/bprm_check_security`` in the ``bpf2`` object runs every+ runtime executable in secure-exec mode, so the C library ignores the+ loader variables, and shirudo itself is static.+- ``lsm/task_prctl`` refuses ``PR_SET_MM_EXE_FILE`` and+ ``PR_SET_MM_MAP`` to tasks without authority (``ExeIdentity``). The+ mark does not depend on the executable link in any case.+- ``lsm/mmap_file`` and ``lsm/file_mprotect`` refuse an authorized task,+ other than the bootstrap task, an executable mapping that is writable+ or not backed by the runtime image.+- At start, shirudo makes itself non-dumpable, sets no-new-privileges,+ disables core dumps, loads no OpenSSL configuration file, resolves+ host names without NSS modules and locks its memory, and refuses to+ run when the lock fails.++.. rst-class:: facts++:Adversary: ADV-B and ADV-C+:Enforced at: ``lsm.s/file_open``, ``lsm.s/inode_unlink``,+ ``lsm.s/inode_rename``, ``lsm.s/inode_setattr``,+ ``lsm.s/inode_setxattr``, ``lsm.s/inode_removexattr``,+ ``lsm/inode_create``, ``lsm/inode_mkdir``, ``lsm/inode_symlink``,+ ``lsm/inode_mknod``, ``lsm/inode_link``, ``lsm/inode_init_security``,+ ``lsm/inode_copy_up``, ``lsm/key_permission``,+ ``lsm.s/bprm_check_security``, ``lsm.s/bprm_committed_creds``,+ ``lsm/task_alloc``, ``lsm/bprm_check_security``,+ ``lsm/ptrace_access_check``, ``lsm/perf_event_alloc``,+ ``lsm/task_prctl``, ``lsm/mmap_file``, ``lsm/file_mprotect``+:Refusal: ``EACCES`` from the seal and the task hooks; ``EPERM`` from a+ copy-up, a traced exec in the ``bpf2`` hook and ``PR_SET_MM``;+ ``tampered`` or a foreign-entry warning from shirudo+:Counters: ``SealWrite``, ``SealUnlink``, ``SealRename``,+ ``SealSetattr``, ``SealXattr``, ``SealLabel``, ``SealEntry``,+ ``SealCopyUp``, ``KeyringWrite``, ``SealPtrace``, ``SealPerf``,+ ``ExecTraced``, ``ExeIdentity``+:Tests: ``t6001``, ``t6006``, ``t6007``, ``t6110``, ``t6111``,+ ``t6112``, ``t6113``, ``t6114``, ``t6115``, ``t6118``, ``t6123``,+ ``t6124``, ``t6127``, ``t6129``, ``t6131``, ``t6133``, ``t6134``,+ ``t6135``, ``t6136``, ``t6137``+:Residual: R2, R15, R19, R22, U5, U12++T4 Substituting artifacts+~~~~~~~~~~~~~~~~~~~~~~~~~++A signed artifact is only as useful to root as the parts it can change.+If the name an upatch loads under, the sites it attaches at, or the+upatch an unload directive removes sat outside the signature, root+could aim a signed program elsewhere or turn one directive against+another upatch.++The signature covers the loader's instructions and the data in its+frozen metadata map, and the kernel refuses a modified loader. The+metadata map is exclusive to its loader through ``excl_prog_hash``, the+SHA-256 of the loader's instructions. The name, the attach metadata, and+for an unload directive the target name and the expected payload digest+ride in signed sections of that data. A load takes its attach sites+from nowhere else, and refuses an artifact whose attach metadata the+signature does not cover (``parser_rejected``).++An unload directive is a signed loader of its own and goes through the+same ``BPF_PROG_LOAD``. Before it removes anything, shirudo compares the+payload digest recorded on the upatch's pin directory, in the xattr+``security.bpf.shirudo.payload`` that only authorized tasks can change+(``PinXattr``), with the directive's signed expected payload. It refuses+``payload_mismatch`` when they differ or when the xattr cannot be read.+A directive therefore removes the upatch its signer made it for and no+other.++.. rst-class:: facts++:Adversary: ADV-B, root on the target without the signing key+:Enforced at: ``lsm/bpf_prog_load``, ``lsm/inode_setxattr``,+ ``lsm/inode_removexattr``+:Refusal: the kernel's signature error for a modified loader;+ ``payload_mismatch`` and ``parser_rejected`` from ``shirudo upatch``+:Counters: ``PinXattr`` for a forged payload binding; none for a+ modified loader, which the kernel refuses first+:Tests: ``t3104``, ``t6117``, ``t6138``+:Residual: R1, R16++.. _tm-t5:++T5 Silent state change+~~~~~~~~~~~~~~~~~~~~~~++A target that loads or unloads upatches without a record cannot be told+apart from a healthy one. Every ``init``, load, unload, revocation and+tree operation therefore extends the measurement register with a+domain-separated SHA-256 event and appends the event to+``/var/lib/shirudo/eventlog``. A TPM 2.0 is mandatory and there is no+unmeasured mode. :doc:`/internals/measurement-register` describes the+register in detail.++The register is a TPM NV extend index, ``0x01818E00``, that the TPM+clears at every reset. Its write policy is a ``PolicyOR`` of two+branches. The written branch needs the index to be written. The init+branch needs it unwritten and PCRs 9 and 11 at the values the policy+was computed from. Both continue with a ``PolicySigned`` by the NV+writer over the session nonce and the hash of the exact+``TPM2_NV_Extend`` command, and with ``PolicyCommandCode`` for+``TPM2_NV_Extend``. ``init`` performs the first write from the initrd,+before ``leave-initrd`` moves PCR 11, and extends PCR 9 with the index+name right after it. An index recreated at runtime under the same+policy cannot be written, because PCR 11 has moved. One recreated under+a policy over the runtime PCR values has another name, which a verifier+that pins the binding values rejects (U9).++The NV writer is an RSA-3072 primary key in the owner hierarchy. Its+private key never leaves the TPM, but the seed it is recreated from is+not secret, so root can recreate the writer and have the TPM sign. A+signature alone does not change the register: the TPM must receive the+``TPM2_NV_Extend``. ``lsm/tpm_command``, the hook of A3, sees every+command written to ``/dev/tpm0`` or ``/dev/tpmrm0`` before the driver+queues it, and refuses an ``NV_Extend`` of shirudo's frozen index from a+task without authority, through inherited and nonblocking descriptors+too (``TpmExtend``). Other NV indices, PCR extensions and TPM signing+stay open to everyone.++The order of the steps decides what a crash or a stopped process+leaves. A load whose archive copy or extension fails is undone, pins+and archive. An unload or a purge is measured before it detaches, so an+interruption leaves a register that claims more than happened, never a+detach it does not know. A measuring command holds a lock beside the+eventlog from its extend to its append, so the register and the log+advance in one order. An append that fails after a successful extend+leaves the register ahead of the log; shirudo reports the desync and+``shirudo status`` reports a register its replay cannot explain.++``init`` binds one register per TPM reset. On a re-run with this boot's+record it reuses the register and adds no event; when the register it+recorded is gone or replaced it refuses ``tampered``. Which record+counts as this boot's depends on what the caller sees (U9). A load or+an unload refuses ``eventlog_full`` before it touches the TPM when the+log would exceed ``eventlog.max_bytes``, and ``init`` checks the limit+before it binds. Tree operations and revocations do not check it (U6).+``upatch load`` and ``upatch unload`` given ``--expect-chain`` compare+it with the register before acting. The comparison is not atomic with+the extend and does not serialize concurrent commands, and package and+tree operations run without it.++.. rst-class:: facts++:Adversary: ADV-B, root on the target without the signing key+:Enforced at: ``lsm/tpm_command``+:Refusal: ``EACCES`` from ``write(2)`` on the TPM device; ``tampered``,+ ``tpm_error`` and ``eventlog_full`` from shirudo+:Counters: ``TpmExtend``+:Tests: ``t4002``, ``t4003``, ``t4102``, ``t4103``, ``t6115``,+ ``t6122``, ``t6128``+:Residual: R4, R12, R20, U6, U8, U9++T6 Boot window+~~~~~~~~~~~~~~++Enforcement is BPF and does not survive a reboot. Until ``init`` has+attached the gates, nothing refuses anything.+``shirudo-initrd.service`` runs ``init`` in the initrd, after the root+file system is mounted at ``/sysroot`` and the ``enter-initrd`` phase is+measured, and before the switch to the root file system. There ``init``+binds ``/sysroot/var/lib/shirudo`` writable, enrolls the config+certificate in ``.dm-verity`` and seals it, enrolls the runtime+certificate and the vouched config signers in ``.bpf`` and seals it,+labels the state, attaches the guards, mounts the runtime image, restores the+archived upatches and binds the register with exactly one init event.+The pins and the identity map live under ``/run``, which systemd+carries across the switch. ``shirudo.service`` then runs ``init`` again+from the runtime image and adopts the initrd's eventlog record.+:doc:`/internals/boot-flow` follows the sequence step by step.++A kexec would open that window again without closing this boot. It+hands the machine to a kernel and an initrd of root's choosing with the+TPM as it is: PCRs 9 and 11 at this boot's values and the register with+this boot's history, so this boot's evidence would vouch for whatever+runs next. ``lsm/kernel_load_data`` and ``lsm/kernel_read_file`` refuse+every kexec image and initramfs to every task, shirudo included, by+either system call (``Kexec``).++.. rst-class:: facts++:Adversary: ADV-B, root on the target without the signing key+:Enforced at: ``lsm/kernel_load_data``, ``lsm/kernel_read_file``+:Refusal: ``EPERM`` from ``kexec_load(2)`` and ``kexec_file_load(2)``+:Counters: ``Kexec``+:Tests: ``t4003``, ``t4101``, ``t6126``+:Residual: R6, R7, R12, U11, U16++.. _tm-t7:++T7 Delivery path+~~~~~~~~~~~~~~~~++Targets pull packages and trees from OCI registries that shirudo does+not trust. ``shirudo bpm repo update`` fetches a repository's index and+its detached CMS signature and verifies them against the repository+certificate in the signed config image. A package installed from a+repository must match the digests in that index, and the loader in it+is a signed upatch the kernel verifies at load (T1).++``shirudo bpm tree sync`` fetches a signed tree publication and verifies+it against the runtime image's primary certificate. A publication+carries a digest for each operation, must have a higher generation than+the one applied, and names its parent, which the target compares when+the generation is exactly one higher. A delete applies the signed+unload directive whose name equals the operation's id.++The transport is TLS 1.3 only, with the hybrid groups+``X25519MLKEM768`` and ``SecP256r1MLKEM768`` and certificate+verification. ``tls.classical_hosts`` in the runtime image's bootstrap+settings opts exact host names into the classical groups ``X25519`` and+``secp256r1`` as well, and shirudo logs a warning when one is+negotiated.++A registry can still withhold or replay signed content (R8). The+environment of the bpm units selects parts of the transport (U3), index+and tree signatures accept algorithms other than ML-DSA (U4), and+revocation does not reach tree publications (U13).++.. rst-class:: facts++:Adversary: ADV-D, network and registry+:Enforced at: no hook; ``shirudo bpm`` verifies in userspace, and the+ kernel verifies each loader (T1)+:Refusal: the ``bpm`` command fails and installs nothing+:Counters: none+:Tests: ``t7005``, ``t7101``, ``t7102``, ``t7103``, ``t8005``+:Residual: R8, R9, U3, U4, U13, U15++T8 Quantum-capable adversaries against the trust anchor+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Embedded fleets keep trusting a certificate for years. A signature that+a future adversary could forge would let it install BPF on every device+that still trusts the old certificate. shirudo signs with ML-DSA-87+(FIPS 204) only. ``shirudo genkey`` makes nothing else, every operator+signature refuses a key that is not ML-DSA-87, and ``shirudo keys+vouch`` and ``shirudo keys add`` refuse another kind of certificate.+Digests are SHA-256 and SHA-512. :doc:`cryptography` lists every+algorithm and where it is used.++On the target, the pre-flight check ``cert_algorithm`` refuses a+certificate other than ML-DSA-87 in the key directory it reads. In the+initrd that is ``/etc/shirudo/keys``, not the runtime image's set that+``init`` enrolls (U4).++.. rst-class:: facts++:Adversary: a future adversary with a cryptographically relevant+ quantum computer and recorded signatures and traffic+:Enforced at: no hook; the operator's signing code and the pre-flight+ check ``cert_algorithm``+:Refusal: the signing command fails; ``init`` fails its pre-flight+:Counters: none+:Tests: ``t2001``, ``t2002``, ``t2004``+:Residual: R9, U4++.. _tm-t9:++T9 A target lying about its state+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++``shirudo status``, the keepalive and the tamper counters are the+target's own account, and a compromised target says what root wants.+``shirudo attest`` makes the TPM speak instead. It produces a quote+over the selected PCRs, by default 0 to 7, 9 and 11 to 15, and a+certification of the register, both signed by the attestation key with+the verifier's nonce. The attestation key is an ECDSA P-256 primary+with a fixed template under the endorsement hierarchy. A credential the+verifier makes under the target's endorsement key (``shirudo attest+challenge``), and the target activates while attesting, proves that the+attestation key sits in the TPM whose endorsement key the evidence+carries.++``shirudo attest verify`` checks the nonce, the attributes of the+attestation key, its name against its public area and, with+``--ak-name``, against the pinned name. It checks the quote's PCR+digest, that the certification names the listed index and value, and+that both come from one TPM reset. It recomputes the index's public area+from the recorded PCR 9 and 11 binding values and the NV writer's public+key, so a recreated index fails. It replays the eventlog to the+certified value, checks that every event's digest derives from its+fields, and checks the PCR 9 anchor. With ``--cert`` and ``--upatch``+it computes the expected init event, with ``--expect-chain`` it compares+the register, and with ``--expect-bind-pcr``, ``--expect-pcr`` and+``--expect-config-root`` it compares the values the operator pins.+Which firmware, kernel and initrd values are acceptable is the platform+owner's policy.++The evidence boundary of :ref:`tm-trust-boundaries` applies: what is+not signed by the TPM is the target's account. Without ``--ak-name`` a+document can carry a software key's signatures (U1).+:doc:`/operate/attest` is the procedure.++.. rst-class:: facts++:Adversary: ADV-B and ADV-C+:Enforced at: no hook; the TPM signs and the verifier checks+:Refusal: ``verdict: FAIL`` from ``shirudo attest verify``, with the+ failed check named+:Counters: none+:Tests: ``t4003``, ``t4004``, ``t4102``+:Residual: R10, R11, U1, U8, U9++.. _tm-t10:++T10 An attempt that leaves no trace+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++A refusal the operator never sees invites the next attempt. Each named+point at which a guard refuses counts the refusal in ``shirudo_tamper``,+an array map ``init`` creates, freezes and pins at every boot. Only the+hooks add to it, and no task resets it from userspace. ``shirudo+status`` lists the counters that are not zero with their meaning,+``status --json`` carries them all, and the keepalive carries the total+as the attribute ``shirudo.tamper_attempts``.++A counter is evidence of an attempt, not of a compromise. Some+refusals move no counter: the kernel's signature errors, the guards of+the ``/run/shirudo`` tmpfs and the image mounts, the device-mapper and+mapping checks, the seccomp and memory checks, and refusals by another+LSM ordered before ``bpf``. Zero does not mean that nobody tried.+:doc:`tamper-counters` lists every counter, its hooks and the refusals+without one.++.. rst-class:: facts++:Adversary: ADV-A and ADV-B+:Enforced at: every hook that counts; :doc:`tamper-counters` lists them+:Refusal: the refused operation fails and its counter moves+:Counters: all, see :doc:`tamper-counters`+:Tests: ``t6003``, ``t6108``+:Residual: R17++.. _tm-t11:++T11 Config and executable substitution+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Authority comes from the runtime image and settings come from the+config image, so each must be the one the operator built. Both are+dm-verity images. The runtime root hash comes from the bootstrap+settings in the initrd and is frozen in the identity map. A config root+carries a detached signature over its 64 lowercase hex characters, and+the kernel verifies it when shirudo creates the mapping.+:doc:`/internals/config-images` describes the formats.++``lsm.s/bdev_setintegrity`` classifies each dm-verity mapping when the+kernel sets its root. A root equal to the frozen runtime root makes the+device a runtime device. A config device needs an authorized task that+staged that exact root for itself first, and the stage is used once.+Other mappings gain no status. Only a file directly on a runtime device,+on a read-only superblock, grants authority at exec (T3).++``lsm/file_ioctl`` and ``lsm/file_ioctl_compat`` refuse every+device-mapper control ioctl other than the read-only ones to tasks+without authority, through old and inherited descriptors too, and for+unrelated device-mapper devices as well. The mount hooks refuse every+caller an unmount, a move, a mount over or a remount of the runtime+image. For a config image they refuse a remount to every caller and the+rest to tasks without authority.++shirudo validates the verity superblock, the format and the sizes,+creates or validates a strict read-only mapping, and reads every data+block of a config mapping before it parses or measures it. It reads+the config's files through the held root and refuses symbolic links and+special files. A config never authorizes an executable, supplies no+bootstrap key or TPM setting, and cannot enroll a key while the target+runs: a live activation that would trust a key the ``.bpf`` keyring does+not hold refuses before it changes anything.++Which keys can sign a config is A7, and U2 is the gap there.++.. rst-class:: facts++:Adversary: ADV-B and ADV-C+:Enforced at: ``lsm.s/bdev_setintegrity``, ``lsm/bdev_free_security``,+ ``lsm/file_ioctl``, ``lsm/file_ioctl_compat``, ``lsm/sb_mount``,+ ``lsm/move_mount``, ``lsm/sb_umount``, ``lsm/sb_remount``,+ ``lsm/key_permission``, ``lsm.s/bprm_check_security``,+ ``lsm/mmap_file``, ``lsm/file_mprotect``+:Refusal: ``EPERM`` or ``EACCES`` from the mapping, ioctl and mount+ calls; ``shirudo image update`` and ``init`` fail+:Counters: ``KeyringWrite``; the mapping, ioctl and image mount+ refusals move none+:Tests: ``t5101``, ``t5102``, ``t5103``, ``t5104``, ``t6101``,+ ``t6113``, ``t6127``, ``t6130``, ``t6131``, ``t6132``+:Residual: R5, R14, U2++T12 Interrupted image activation+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++A config activation changes keys, repositories and revocations and+extends the config PCR. An interruption half way must not leave a+target that runs one config while its records claim another.+``shirudo image update`` makes the candidate and the pending selection+durable before it extends the PCR. A validation failure before that+point leaves the active config in use. After it, including on an+ambiguous TPM response, the target needs a manual reboot. The target+keeps running, shirudo never reboots it, refuses further state changes and+config attestation, and ``shirudo status`` reports ``reboot-pending``.++At the next boot, ``init`` verifies the selected image again, reads its+whole mapping, extends the config PCR with a fresh boot event and+applies revocations before it restores upatches. It records completion+only after startup succeeds. A selected image that is missing or+invalid fails ``init`` rather than falling back to an older config.++.. rst-class:: facts++:Adversary: ADV-B, and faults such as a crash or power loss+:Enforced at: no hook+:Refusal: state-changing commands refuse while the activation is+ pending; ``shirudo status`` reports ``reboot-pending``+:Counters: none+:Tests: ``t4004``, ``t5105``+:Residual: R4, R14++T13 Reading or draining upatch state+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++The maps of upatches hold observations, and shirudo's own maps hold the device+records and the identity. A read-only map descriptor reads that state,+and a serializer program run with ``BPF_PROG_TEST_RUN`` drains an+interval before the export takes it. Either lets root read or erase what+the operator relies on.++``lsm/bpf_map`` refuses every map descriptor to tasks without runtime+authority: a writable one as ``MapFdWrite`` and a read-only one as+``ObjGet``. ``lsm/bpf`` refuses the routes to a descriptor,+``BPF_OBJ_GET`` and ``BPF_MAP_GET_FD_BY_ID`` (``ObjGet``), and+``BPF_PROG_TEST_RUN`` (``ProgRun``). ``lsm/file_open`` refuses opening a+pin as a file, through which bpffs would print a map's contents+(``ObjGet``). A writable memory mapping of an arena needs a writable+descriptor. A process whose executable is not on the runtime image+therefore neither reads nor drains the maps, and reads the identity+only through a runtime command such as ``shirudo status``.++The boundary is the command interface: root can run the runtime binary,+and ``shirudo upatch map`` drains a serializer unless ``--peek`` is+given (R2).++.. rst-class:: facts++:Adversary: ADV-B, root on the target without the signing key+:Enforced at: ``lsm/bpf``, ``lsm/bpf_map``, ``lsm/file_open``+:Refusal: ``EACCES`` from ``bpf()`` and from opening a pin+:Counters: ``ObjGet``, ``MapFdWrite``, ``ProgRun``+:Tests: ``t6107``, ``t6108``, ``t6109``, ``t6110``+:Residual: R2++T14 Substituting the TPM+~~~~~~~~~~~~~~~~~~~~~~~~++shirudo reaches the TPM through a device node it opens by path. In image+mode it accepts only a device TCTI, by default ``device:/dev/tpmrm0``,+set in the authenticated bootstrap settings. Root can put another+device at that path in a mount namespace of its own, an emulator for+instance, and the emulator would answer every check that compares+public values, since the index name, the policy and the reset count are+in the readable init record.++Before it binds or extends the register, and before a config+activation, shirudo recreates the attestation key under the endorsement+hierarchy and compares its name with the one ``init`` froze in the+identity map. An emulator lacks the TPM's endorsement seed and produces+another name, and the command refuses. The comparison authenticates the+TPM's answer to that one command, not the responses that follow: shirudo+uses unsalted, unbound sessions, so a device that forwards some+commands to the real TPM and answers others itself is not detected+(U8). ``lsm/tpm_command`` refuses an unauthorized extension only for+commands that reach the real driver.++.. rst-class:: facts++:Adversary: ADV-C, root with mount-namespace and device control+:Enforced at: ``lsm/tpm_command`` for commands that reach the driver;+ the attestation key comparison in userspace+:Refusal: ``tampered`` from the register path+:Counters: ``TpmExtend`` for a refused extension; none for a+ substituted device+:Tests: ``t4103``, ``t6125``+:Residual: U8++Residual risks+--------------++Each residual risk is known and bounded, and each says how an operator+detects it. Several stay silent on the target and show only in+evidence a verifier checks.++R1 Unload runs in userspace, and directives are reusable+ The kernel's ``bpf_sys_bpf()`` cannot detach a link or remove a pin,+ so a signed unload directive authorizes and shirudo removes the pins+ in userspace. The directive's target name and expected payload are+ signed, so root cannot aim it at another upatch. Root keeps the+ moment: every directive ever published is root's to apply at any+ time. A directive is not bound to the signer of the load either. Any+ key in the ``.bpf`` keyring that signed a directive with the right+ name and payload digest, both visible in ``shirudo status`` and the+ eventlog, unloads the upatch. Detection: every application is an+ unload event in the register. Mitigation: D5.++R2 The command interface of the runtime binary is the boundary+ Root can run any command of the runtime binary. It can load any+ signed artifact (R16), apply any published directive (R1), drain a+ serializer with ``shirudo upatch map`` and send the output where it+ chooses, and hold the lock files shirudo serializes on. No hook+ covers signals, so root can also stop a running command, which+ keeps open whatever descriptors it holds (U17).+ ``CAP_SYS_RESOURCE`` can rewrite a process's executable link, which+ ``lsm/task_prctl`` refuses and the mark does not depend on. The+ initrd's bootstrap binary and the memory of authorized tasks stay+ in the TCB. Detection: loads and unloads are measured; drains,+ stops and lock holding are not.++R3 Pins depend on the mount tree+ The pins hold the links through the bpffs superblock. The guards of+ T2 cover unmounts of the bpffs and of mounts above it in ``init``'s+ namespace. A private copy of the tree in another namespace is any+ process's to drop, which releases nothing. Legacy ``mount(2)`` with+ ``MS_MOVE`` reaches ``lsm/sb_mount`` with the target only, so the+ source mount is not checked (D8). ``pivot_root(2)`` is not hooked,+ and ``mount_setattr(2)`` has no LSM hook at all, so root can change+ mount attributes and propagation, making the bpffs read-only for+ instance. A mount over ``/run`` or an ancestor hides the pins without+ releasing them: enforcement continues, ``shirudo status`` reports the+ LSM as not attached, and ``upatch load`` and ``upatch unload`` refuse+ ``tampered`` with the message ``lsm_detached`` in their pre-flight.+ The walk's bounds refuse every unmount of a tree they cannot cover.+ Mitigation: D7.++R4 Config PCR writers are not authenticated+ The config PCR, one of 0 to 15 other than 9 and 11 chosen in the+ bootstrap settings, is extended with ``TPM2_PCR_Extend``, which+ ``lsm/tpm_command`` does not restrict. Any root process can extend+ it. Garbage makes the config history fail its replay, a denial of+ service. The digest of a valid activation, which is public, records+ an activation that never happened. The verifier also takes the+ value the history starts from out of the evidence rather than+ requiring zero. A fresh nonce and a genuine quote prove neither who+ extended the PCR nor that an activation completed. Detection: none+ reliable. Mitigation: D1.++R5 The boot chain and process memory stay trusted+ dm-verity verifies runtime blocks as they are read. It does not+ protect process memory, and it trusts the UKI and the kernel that+ chose the root hash (A6). ``SHIRUDO_VERSION_ID`` keeps an operator+ and a target of different builds apart; it authenticates nothing.++R6 A failed or skipped init leaves the target unprotected+ There is no fallback mode. When ``init`` fails in the initrd, or+ the unit does not run, the boot continues without enforcement and+ without a bound register (U11). Detection: attestation fails for+ want of an init record, and ``shirudo status`` reports the LSM as+ not attached.++R7 The boot window before init+ Before ``init`` attaches ``lsm/bpf`` in the initrd, any process in+ the initrd can load and attach BPF, and what it leaves attached+ stays. The initrd is measured into PCR 9 and, on a measured UKI+ boot, its phases into PCR 11, and it is in the TCB (A6). Without+ the phase measurements PCR 11 holds no phase, and a verifier tells+ an initrd binding from a later one by PCR 9 alone. A first ``init``+ from the root file system runs after every process before it, reads+ its settings from the root file system's ``/etc/shirudo/shirudo.conf``+ and binds the register after ``leave-initrd``. ``--expect-bind-pcr``+ with the initrd's values rejects such a binding.++R8 Registry withholding and replay+ A registry or a network adversary can withhold any content and+ serve any older, validly signed index or package. The target keeps+ the last index that verifies, and nothing orders one index before+ another or binds it to the registry it came from. ``shirudo bpm+ list`` shows the target's own state, and a repository update is not+ measured. Detection: compare the upatch payloads and tree operations+ that ``attest verify`` certifies with what you published.++R9 Classical pieces+ The WebPKI certificates of registries and collectors authenticate+ the transport, not the artifacts. Hosts opted into+ ``tls.classical_hosts`` get a classical key exchange, so recorded+ traffic to them may be exposed to a future quantum-capable+ adversary. The attestation key is ECDSA P-256, because TPMs sign+ with nothing post-quantum today, the NV writer's authorization is+ RSA-3072, and credential activation uses the endorsement key's RSA+ or ECC algorithm. The evidence is therefore classical even though+ the artifacts it describes are not.++R10 Endorsement key trust+ Credential activation ties the attestation key to the endorsement+ key in the evidence, and the endorsement certificate ties that key+ to a manufacturer. ``shirudo attest challenge`` makes no challenge+ unless the certificate chains to the issuers given with+ ``--ek-ca``, the key is pinned with ``--ek-name`` from an inventory,+ or the operator waives the check with ``--trust-presented-ek``,+ which proves only that the same party answers each time. Virtual+ TPMs usually have no certificate. Which issuers to trust is the+ operator's decision.++R11 The anchor shares PCR 9+ PCR 9 also carries the initrd measurements and systemd's NvPCR+ events. ``attest verify`` proves the anchor exactly only when nothing+ is measured into PCR 9 after ``init``; otherwise it reports a note+ and leaves the replay of the systemd measurement log, which the+ evidence carries, to the verifier. ``--strict-anchor`` turns the+ note into a failure. Mitigation: D3.++R12 A process before init can bind first+ A process that runs before ``init`` in the same boot phase can define+ and write the register first. ``init`` then rebinds it with a+ warning, which discards what was written. Anything the earlier+ process extended into PCR 9 changes the binding value, which+ ``--expect-bind-pcr=9`` with the expected value rejects. A record of+ this boot that such a process leaves names an NV writer it cannot+ know, since ``init`` draws the writer's seed at random each boot, and+ ``init`` then refuses to bind, a denial of service. From the initrd+ such a process is part of the TCB (A6); from the root file system it+ is R7.++R13 Revocation reaches a target only through a config+ A revocation arrives with a signed config that the target activates,+ live with ``shirudo image update`` or at boot. ``shirudo keys+ revoke`` refuses. A live activation unlinks the key from ``.bpf``,+ measures a ``key_revoke`` event and then purges the key's upatches,+ each with an unload event. If that extension fails, the key stays+ unlinked, the revocation is unmeasured and the purge does not run.+ At boot the revoked key is not enrolled, and the init event's+ certificate list shows it. A target that has not activated the+ config still trusts the key. Vouches and tree publications are U13.++R14 Configs roll back+ shirudo accepts any validly signed config. A live activation cannot+ add a key to ``.bpf`` this boot, but it can roll back every other+ setting: repositories and their certificates, the tree subscription,+ export endpoints, the eventlog limit and revocation records, and the+ selection persists across reboots. The selection journal under+ ``/var/lib/shirudo/config-update`` is not authenticated, so a change+ to it between boots selects any config in the cache under+ ``/var/lib/shirudo/images``, its trusted set included. The config+ certificate itself changes only with the runtime image and a reboot.+ Detection: ``--expect-config-root`` with ``--expect-config-pcr``.+ Mitigation: D2.++R15 Directory marks can be evicted+ The label at creation and the entry checks follow a mark that the+ seal keeps on a directory inode in memory. Root can evict the inode,+ by dropping caches for instance, whenever shirudo does not hold the+ directory open, or make the label read fail (U12). While the mark is+ absent, root can create entries in a labeled directory and+ hard-link an already labeled inode into it; a hard link is the same+ inode and carries the label. shirudo replaces state by rename, so+ root can keep earlier labeled versions alive through hard links in+ an unsealed directory on the same file system and bring them back.+ An unlabeled entry stays inert: shirudo neither follows nor restores+ it. A returned labeled entry is taken for shirudo's own. Detection:+ only signatures and measurement; an archived upatch restored at the+ next boot appears in the init event's set. Mitigation: D6.++R16 Any artifact ever signed loads at any time+ There is no version floor, no expiry and no per-target+ authorization. Neither shirudo nor the kernel checks a certificate's+ validity period. Root can roll an upatch back to an older vulnerable+ version or load a signed debug upatch. Detection: the load is+ measured, and a verifier with an expected state sees it. The only+ way to retire one artifact is to revoke the key that signed it.++R17 Telemetry has no proof of origin+ Keepalives, map snapshots and the tamper counters they carry are+ unsigned and not bound to the TPM. ``host.name`` is the target's+ host name, and the credentials come from files root reads.+ ``map_export.otel_insecure`` turns certificate verification off.+ Root can withhold, drain or forge telemetry. Only ``attest verify``+ is evidence.++R18 BPF outside the gates+ ``lsm/bpf`` and ``lsm/bpf_prog_load`` admit every call whose+ ``kernel`` argument is set. That includes in-kernel light skeletons+ loaded through ``kern_sys_bpf()``, such as the ``bpf_preload`` module,+ which a signed module can bring in (A4). Classic BPF, for seccomp+ filters and ``SO_ATTACH_FILTER``, does not use ``bpf()``. Program+ descriptors stay open to root, and the attach paths outside+ ``bpf()`` that take one, socket options and netlink among them,+ accept only program types those paths support. The operator's build+ refuses sections of those types; the kernel does not refuse them in+ a signed loader.++R19 Raw device and offline writes bypass the seal+ The seal guards file operations. A write to the block device under+ ``/var/lib/shirudo`` while it is mounted (A10), or any change between+ boots, bypasses it. Removing the label from the state root offline+ makes the next bootstrap run of ``init`` label everything under it.+ Across reboots only signatures and the register protect state:+ upatches are verified at load and measured in the init event, and+ the package, tree and config selection state is not authenticated.++R20 The TPM owner password is not a secret on the target+ ``tpm.owner_auth`` lives in the runtime image's ``shirudo.conf``,+ where root reads it, and shirudo sends it as a plain password+ session. Root can undefine the register, which makes every measuring+ command refuse until the next TPM reset, or use the owner hierarchy.+ An image shared across a fleet shares the password.++R21 upatches can be neutralized without detaching them+ An upatch stays loaded and measured while root makes it ineffective:+ by unloading the module a kprobe targets, by replacing the binary a+ ``uprobe.multi`` target names with a new inode, or, without lockdown+ (A4), by disabling kprobes through debugfs. These are readings of the+ kernel source and are not tested.++R22 Labelled inodes are interchangeable+ The label carries no identity. Any labeled inode passes shirudo's+ checks at any sealed path, and ``lsm/sb_mount`` does not guard the+ file system that holds ``/var/lib/shirudo``. In a mount namespace of+ its own, root can bind one labeled inode over another sealed path+ for a shirudo command it runs there. U9 is one consequence; others+ are a hidden eventlog, which makes measuring commands fail, and+ package or tree state read from the wrong file. This is a reading of+ the code and is not reproduced.++Threats to resolve+------------------++These gaps are in the code today and are not closed. Each entry says+what it affects, the consequence, whether it is confirmed in the code+or a reading of a code path that is not reproduced yet, and what a+deployer can do meanwhile.++U1 Verification passes without a pinned key or an expected state+ :Affects: ``shirudo attest verify``.+ :Consequence: ``--ak-name`` is optional and its absence only warns;+ the document then authenticates nothing, since a software P-256+ key can carry the required attribute bits. Without ``--cert``,+ ``--upatch`` or ``--expect-chain`` the register's value is+ reported, not checked. ``--require-initrd`` reads ``bound_in``,+ which no digest covers.+ :Status: Confirmed in code.+ :Meanwhile: Always pass ``--ak-name``, an expected state,+ ``--expect-bind-pcr=9=<value>`` and ``--expect-bind-pcr=11=<value>``,+ and ``--expect-config-root`` with ``--expect-config-pcr``. See+ :doc:`/operate/attest`.++U2 Any key the kernel trusts for dm-verity signs a config+ :Affects: Config images (A7).+ :Consequence: A distribution's built-in key, and with the Kconfig+ options of A7 a MOK or UEFI db key, signs a config the target+ accepts, with its repositories, vouched signers, revocations and+ export endpoints. shirudo cannot tell which key verified a root.+ :Status: Confirmed in code and in the kernel; ``t5102`` exercises a+ built-in certificate.+ :Meanwhile: Build both options off, build in no certificate whose+ holder is not trusted to sign configs, and verify with+ ``--expect-config-root``.++U3 The environment reaches authorized processes+ :Affects: The bpm and export units and any runtime command root+ starts.+ :Consequence: ``BPM_OCI_SCHEME=http`` turns TLS off,+ ``BPM_OCI_CA_FILE`` adds a trust anchor, proxy variables redirect+ the traffic, and credentials come from the environment and auth+ files. Libraries in the process honor ``SSLKEYLOGFILE`` (libcurl)+ and ``TSS2_LOGFILE`` (tpm2-tss), which open a file root names+ with the process's authority, sealed state included. The+ environment files of the shipped units are writable by root.+ :Status: Confirmed in code for shirudo's own variables; the library+ variables are a code-path reading, not reproduced.+ :Meanwhile: Keep ``/etc/shirudo/bpm/environment``,+ ``/etc/shirudo/map-export.env`` and ``/etc/shirudo/init.env``+ absent or empty and owned by root, and watch who runs runtime+ commands.++U4 Signatures other than ML-DSA-87 are accepted in places+ :Affects: Repository indexes, tree publications and the trust set+ ``init`` enrolls.+ :Consequence: Index and tree signatures verify with whatever+ algorithm the certificate holds, and no step checks that a+ repository certificate is ML-DSA-87. The pre-flight check+ ``cert_algorithm`` runs on the initrd's ``/etc/shirudo/keys``,+ not on the runtime image's certificate and the vouched signers+ that ``init`` enrolls, and the kernel accepts other algorithms in+ ``.bpf``.+ :Status: Code-path reading, not reproduced.+ :Meanwhile: Use only certificates that ``shirudo genkey`` made, for+ repositories too.++U5 The seal does not cover every operation+ :Affects: Writable state (T3).+ :Consequence: ``inode_rmdir``, ``inode_file_setattr`` (``chattr``)+ and the POSIX ACL hooks are not attached, so root can remove an+ empty labeled directory, set the immutable or append-only flag+ on sealed files, and change their ACLs. The seal's link check+ looks at the destination directory only, so a hard link keeps a+ labeled inode alive in an unsealed directory (R15).+ :Status: The missing hooks are confirmed in code; the consequences+ are a code-path reading, not reproduced.+ :Meanwhile: Nothing on the target. A changed upatch archive still+ fails at load or shows in the init event.++U6 The eventlog becomes unreadable at 8 MiB+ :Affects: Every reader of the eventlog: replay, ``shirudo status``,+ ``shirudo attest`` and ``init``.+ :Consequence: The readers stop at 8 MiB, ``eventlog.max_bytes`` has+ no default, the log is never rotated, and tree operations and+ revocations do not check the limit. Root can grow the log by+ applying published load and unload pairs. Past 8 MiB, status,+ replay and attestation fail across reboots. With a limit set,+ measuring commands and ``init`` refuse ``eventlog_full`` instead.+ :Status: Confirmed in code for the limits; the effect is a code-path+ reading, not reproduced.+ :Meanwhile: Watch the size of ``/var/lib/shirudo/eventlog``.++U7 The shipped timer units run the host binary+ :Affects: ``shirudo-keepalive.service``,+ ``shirudo-map-export.service``,+ ``shirudo-bpm-repo-update.service`` and+ ``shirudo-bpm-tree-sync.service``.+ :Consequence: Only ``shirudo.service`` receives the drop-in that+ ``shirudo-gen-runtime --unit-output`` generates. The others start+ ``shirudo`` from the root file system, which has no runtime+ authority: it cannot open the identity pin, so the command fails+ once enforcement is live and moves ``ObjGet`` at every run.+ :Status: Confirmed in code; the failure of each unit is a code-path+ reading, not reproduced.+ :Meanwhile: Install a drop-in for each of these services that+ starts its commands from the runtime image, as the test VM does+ in ``testing/vm/guest.sh``.++U8 The TPM transport is not authenticated+ :Affects: The register (T5) and the device check (T14).+ :Consequence: shirudo opens the TPM by path and uses unsalted,+ unbound sessions, so no response is authenticated. A device in+ root's mount namespace that forwards the attestation key's+ creation to the real TPM and answers the rest can accept+ extensions that never reach the TPM. Root then drops those+ records from the evidence it relays, and the evidence verifies+ while an upatch was loaded or removed unmeasured. The owner+ password, when configured, goes to that device too.+ :Status: Confirmed in code for the sessions and the device path; the+ attack is a code-path reading, not reproduced.+ :Meanwhile: No deployment setting closes it. Pin the bind PCRs and+ the expected state on every verification so that other+ substitutions fail.++U9 init can rebind the register after hiding this boot's record+ :Affects: The one-binding-per-reset rule (T5).+ :Consequence: ``init`` decides whether it bound the register this+ boot from the eventlog and the boot ID it reads by path in its+ mount namespace. When it finds no record it undefines and+ redefines the register under the current PCR values (R22). Once+ the earlier init record is dropped from the document, the evidence+ of such a binding passes every check except a pin of the binding+ PCRs.+ :Status: Code-path reading, not reproduced.+ :Meanwhile: Always pass ``--expect-bind-pcr=9`` and+ ``--expect-bind-pcr=11`` with the initrd's values, or+ ``--expect-pcr=9`` with the predicted value.++U10 Kernel prerequisites are not checked+ :Affects: A4, A5, A7, A9 and A10.+ :Consequence: A target without lockdown, with 32-bit compatibility,+ with the dm-verity keyring options on, with hibernation available+ or with writes under mounted file systems allowed initializes+ without an error and without the protection those assumptions+ give.+ :Status: Confirmed in code: the pre-flight checks none of them.+ :Meanwhile: Boot with ``lockdown=integrity`` on an authenticated+ command line and build the kernel as :doc:`/operate/hardening`+ describes.++U11 The boot continues when init fails+ :Affects: ``shirudo-initrd.service`` and the root file system's+ ``init`` (R6, R7).+ :Consequence: The initrd unit is wanted by ``initrd.target`` and has+ conditions, so a failure or a skip lets the target boot+ unprotected. A first ``init`` from the root file system is not+ refused and takes its settings from the root file system.+ :Status: Confirmed in code.+ :Meanwhile: Attest every target after every boot with the bind PCRs+ pinned, and treat a missing keepalive as a signal. A deployer who+ prefers a halted boot can add an ``OnFailure=`` drop-in to+ ``shirudo-initrd.service``; this is not tested.++U12 Another LSM can switch the seal off+ :Affects: The seal (T3).+ :Consequence: The kernel's label read checks the caller's read+ permission, and every LSM's ``inode_permission`` hook takes part.+ A policy that grants write or unlink but refuses read makes a+ labeled file look unlabeled, and the operation goes through+ without a counter. The same refusal on a directory open removes+ its mark.+ :Status: Confirmed in code and in the kernel; the attack is a+ code-path reading, not reproduced.+ :Meanwhile: Run no other LSM whose policy root can change at+ runtime.++U13 Revocation does not reach everything+ :Affects: Tree publications and vouched keys (R13).+ :Consequence: Tree publications verify against the runtime image's+ primary certificate without a revocation check. Vouches carry no+ time, and a revoked key's vouch for another key still admits it+ when a config lists that key.+ :Status: Confirmed in code.+ :Meanwhile: Ship a new runtime image when the primary key is+ compromised, and drop from the config every key the revoked key+ vouched for.++U14 The operator runs commands from a registry package+ :Affects: ``shirudo bpm config update --base-package oci://...``+ without ``-f`` on the operator host.+ :Consequence: The command takes the Beefile from a package checked+ only against the registry's manifest digest and runs its updater+ commands on the host that holds the signing key. A hostile+ registry becomes ADV-F.+ :Status: Confirmed in code; the usage text says the commands are+ trusted as operator-side code.+ :Meanwhile: Always pass ``-f`` with a local Beefile, or a local+ ``.bee`` file as the base package.++U15 Certificates are fetched without a pin+ :Affects: ``tools/gen-initrd/install.sh --cert <url>`` and+ ``shirudo bpm key add oci://...``, which image mode refuses on a+ target.+ :Consequence: The certificate installed is whatever the URL served.+ :Status: Confirmed in code.+ :Meanwhile: Pass a local file after checking its fingerprint.++U16 Boot restore is not all or nothing+ :Affects: ``init`` (T6).+ :Consequence: ``init`` restores archived upatches in name order and+ stops at the first failure. The upatches it already restored stay+ attached and pinned while no register is bound, so they run+ unmeasured.+ :Status: Confirmed in code.+ :Meanwhile: Treat a failed ``init`` as an incident; attestation fails+ for want of an init record. See :doc:`/operate/incident-tampered`.++U17 A stopped runtime command keeps its descriptors+ :Affects: The descriptor checks of T2.+ :Consequence: Runtime commands open link pins for short checks. No+ hook covers signals, so root can stop such a command while it+ holds a link descriptor, and that link then stays attached after+ its pin is removed by an unload or a revocation.+ :Status: Code-path reading, not reproduced.+ :Meanwhile: A stopped shirudo process is visible in the process+ list; compare the loaded links with the measured set when one is+ found.++Deferred mitigations+--------------------++These are in scope and not built yet:++D1 Authenticated config PCR writers+ Restrict who extends the config PCR and bind its measurements to+ completed activations (R4).++D2 Config rollback prevention+ Refuse a config older than the one a target activated, and+ authenticate the selection journal (R14).++D3 The register as a systemd NvPCR+ Register the index as a systemd NvPCR, so that its name follows the+ UKI signing key instead of each boot's PCR values and systemd-aware+ verifiers find it in PCR 9, and measure the anchor through+ ``systemd-pcrextend`` so that systemd's log explains it (R11).++D4 Signed PCR policies+ Signed policies for the kernel and initrd PCRs, so that a verifier+ needs no golden values.++D5 In-kernel detach+ Detach and unpin from the signed unload directive in kernel context,+ which ``bpf/unload.c`` holds a placeholder for, once ``bpf_sys_bpf()``+ supports it (R1).++D6 A sleepable hook at dentry instantiation+ A ``d_instantiate`` hook in which the BPF LSM can read the label,+ marking a directory the moment its dentry is bound and closing the+ eviction gap (R15). The `directory-entry investigation+ <https://github.com/shirudo-dev/shirudo/issues/13>`__ records the+ analysis.++D7 Pins without the mount tree+ Keep the enforcement links alive without depending on the bpffs+ mount (R3), tracked in `issue 22+ <https://github.com/shirudo-dev/shirudo/issues/22>`__.++D8 Legacy mount moves+ Check the source of a legacy ``MS_MOVE`` (R3), tracked in `issue 12+ <https://github.com/shirudo-dev/shirudo/issues/12>`__.++D9 Perf events across exec+ Refuse task-bound perf events that a task opened before the exec+ that marks it (T3), tracked in `issue 11+ <https://github.com/shirudo-dev/shirudo/issues/11>`__.++Out of scope+------------++- Compromise of the operator host or of the signing key itself. U14 is+ in scope, because it turns a registry into that compromise.+- A malicious or faulty kernel, verifier, TPM or hardware, and physical+ attacks (ADV-G).+- Denial of service: removing the binary, cutting the network, filling+ the disk, holding a lock file, stopping a process. shirudo refuses+ rather than fail over, and several such refusals are listed above.+- The correctness or safety of an upatch an authorized signer built.+- Fleet inventory, rollout order, retries, scheduling and consistency+ across targets. shirudo reports one machine.+- Remote access and audit retention, which belong to the infrastructure+ the operator already runs.++.. _tm-duties:++Duties+------++The mechanisms above hold only when the deployer and the verifier do+their part. :doc:`/operate/hardening` and :doc:`/operate/attest` are+the procedures.++The deployer:++- Builds the kernel with the signed-loader ABI and the ``tpm_command``+ patch (A3), ``CONFIG_MODULE_SIG`` with enforcement and+ ``CONFIG_SECURITY_LOCKDOWN_LSM`` (A4), ``CONFIG_COMPAT=n`` (A5), both+ dm-verity keyring options off and no foreign built-in certificate+ (A7), the TPM driver without ``i2c-dev`` or ``spidev`` on its bus+ (A8), and ``CONFIG_BLK_DEV_WRITE_MOUNTED=n`` (A10).+- Boots a signed, measured UKI under Secure Boot whose command line+ carries ``lsm=`` with ``bpf``, ``lockdown=integrity``,+ ``bpf.keyring_unsealed=1`` and ``dm_verity.keyring_unsealed=1`` (A6,+ A11).+- Keeps generic tools off the runtime image (A14).+- Keeps the environment files of the units absent or empty (U3) and+ starts every shirudo unit from the runtime image (U7).+- Uses only ML-DSA-87 certificates from ``shirudo genkey``, repository+ certificates included (U4).+- Treats the TPM owner password as known to root (R20).+- Never runs ``shirudo bpm config update --base-package oci://...``+ without ``-f`` (U14), and checks the fingerprint of every certificate+ it installs (U15).+- Watches the size of the eventlog (U6) and the keepalives, and treats a+ ``tampered`` status as an incident to understand, not a condition to+ retry (:doc:`/operate/incident-tampered`).++The verifier:++- Uses a fresh, unique ``--nonce`` for each verification.+- Records the attestation key name at enrollment after a challenge whose+ endorsement key chains through ``--ek-ca`` or matches ``--ek-name``,+ and passes ``--ak-name`` on every verification (U1, R10).+- Pins the binding with ``--expect-bind-pcr=9=<value>`` and+ ``--expect-bind-pcr=11=<value>`` (U9, R7, R12).+- Gives an expected state: ``--cert`` with ``--upatch`` or ``--expect``+ and ``--tree-root``, or ``--expect-chain`` (U1).+- Gives ``--expect-config-root`` with ``--expect-config-pcr`` (U2,+ R14).+- Gives ``--strict-anchor`` where nothing else measures into PCR 9+ after ``init`` (R11), and ``--expect-pcr`` for the firmware, kernel and+ initrd values its policy accepts.+- Treats ``bound_in``, the eventlog's content beyond the replay,+ ``shirudo status``, the keepalives and the tamper counters as the+ target's own account (R17).++Related+-------++- :doc:`security-model` for the short version.+- :doc:`tamper-counters` for every counter and its hooks.+- :doc:`cryptography` for every algorithm and where it is used.+- :doc:`/internals/enforcement`, :doc:`/internals/seal`,+ :doc:`/internals/signed-loader` and+ :doc:`/internals/measurement-register` for the mechanisms.+- :doc:`/concepts/background/bpf-lsm`,+ :doc:`/concepts/background/keyrings`, :doc:`/concepts/background/tpm`+ and :doc:`/concepts/background/dm-verity` for the platform background.diff --git a/Documentation/start/guides/attest-target.rst b/Documentation/start/guides/attest-target.rstnew file mode 100644index 00000000..2d103ef2--- /dev/null+++ b/Documentation/start/guides/attest-target.rst@@ -0,0 +1,298 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Tutorial+:audience: Operators++Attest a target+===============++In this tutorial you enroll the test target's TPM and then verify what the+target runs. You take a first piece of evidence and record the TPM's+attestation key from it. A credential challenge then proves that this key+lives in the same TPM as the endorsement key the evidence names. With the+key pinned, you predict the target's measurement register and verify+evidence against the prediction.++The target's TPM signs the evidence, and you check it on the operator+host against values you compute yourself from your certificates and+artifacts.++Before you begin+----------------++- The test VM from the :doc:`/start/quickstart`, running as+ ``quickstart``, with the upatch ``basic`` loaded and unloaded. The+ examples come from a test VM on which other guides ran as well, so+ their lists of events after boot are longer than yours.+- The operator shell from the quickstart: in the root of your checkout,+ with ``shirudo`` on ``PATH``, ``KEYS`` naming the test VM's key+ directory and ``PAYLOAD`` holding the payload digest of+ ``basic.upatch``.+- ``jq`` and the ``openssl`` command on the operator host.+- A root shell on the target (``make -C testing vm-ssh+ VM_NAME=quickstart``) in which ``shirudo`` runs the runtime binary:++ .. code-block:: console++ target# alias shirudo=shirudo-runtime++Take the first evidence+-----------------------++1. Name the second enrolled certificate and the directory the test VM+ shares with the host:++ .. code-block:: console++ operator$ OWN=build/test-vm/host-bundle-bpf-next-verity/fixtures/own.der+ operator$ RESULT=build/test-vm/vms/quickstart/result++ The guest sees ``$RESULT`` as ``/mnt/shirudo-out``.++2. Make a nonce:++ .. code-block:: console++ operator$ NONCE1=$(openssl rand -hex 32)+ operator$ echo "$NONCE1"++3. Take evidence on the target with that nonce:++ .. code-block:: console++ target# shirudo attest --nonce=<nonce1> --out=/mnt/shirudo-out/first.json++ ``<nonce1>`` is the value you printed.++Record the key names+--------------------++1. Read the names of the attestation key and the endorsement key from the+ evidence:++ .. code-block:: console++ operator$ AK=$(jq -r .ak.name "$RESULT/first.json")+ operator$ EK=$(jq -r .ek.name "$RESULT/first.json")++ The attestation key (AK) signs the evidence. It is a primary key that+ the TPM derives from a fixed template under its endorsement hierarchy,+ so the same TPM yields the same key and name again on later boots.+ The endorsement key (EK) identifies the TPM. So far these are only+ names the document claims, and nothing ties them to a TPM yet.++Challenge the attestation key+-----------------------------++1. Make a credential challenge for the attestation key:++ .. code-block:: console++ operator$ shirudo attest challenge --evidence="$RESULT/first.json" --ak-name="$AK" --trust-presented-ek --out="$RESULT/challenge.json"+ ok: attestation key: the pinned key+ ok: endorsement key: name matches its public area+ ok: endorsement key: TCG default template under the endorsement policy+ note: no endorsement certificate: the endorsement key is trusted as presented+ challenge: build/test-vm/vms/quickstart/result/challenge.json+ credential: b17d3f29447eaf539bcffa2556b010082a7a10e2b7ab60746c485d176b7a40cc++ The challenge holds a random credential, encrypted to the endorsement+ key and bound to the attestation key's name. Only the TPM that holds+ the endorsement key can decrypt it, and that TPM releases it only to a+ key with that exact name. The command prints the credential. Keep it+ for the verification, and do not hand it to the target.++2. Keep the credential:++ .. code-block:: console++ operator$ CRED=<credential>++ ``<credential>`` is the value the command printed.++The software TPM of the test VM carries no endorsement certificate, so+nothing vouches for its endorsement key, and ``--trust-presented-ek``+accepts it as presented. Never use that option for a production target:+whoever controls the target could present the keys of a software TPM,+answer the challenge there and sign any evidence. Use one of these+instead:++- ``--ek-ca=<bundle>``, a PEM bundle of the TPM vendors' CA certificates.+ The command then requires the endorsement certificate the TPM carries+ to chain to one of them and to describe the presented key.+- ``--ek-name=<ek-name>``, an endorsement key name you recorded through a+ channel you trust, for example when the machine was provisioned.++Answer the challenge on the target+----------------------------------++1. Make a second nonce on the operator host:++ .. code-block:: console++ operator$ NONCE2=$(openssl rand -hex 32)+ operator$ echo "$NONCE2"++2. Take evidence that answers the challenge:++ .. code-block:: console++ target# shirudo attest --nonce=<nonce2> --challenge=/mnt/shirudo-out/challenge.json --out=/mnt/shirudo-out/enrolled.json++ The TPM activates the credential for its attestation key, and the+ evidence carries the recovered value. A challenge made for another+ attestation key fails here and writes no evidence:++ .. code-block:: console++ attest: the challenge was made for another attestation key+ attest: the challenge was refused (tampered?)++Verify the enrollment+---------------------++1. Verify the evidence with both key names, the credential and the+ enrolled certificates:++ .. code-block:: console++ operator$ shirudo attest verify --evidence="$RESULT/enrolled.json" --nonce="$NONCE2" --ak-name="$AK" --ek-name="$EK" --expect-credential="$CRED" --cert="$KEYS/cert.der" --cert="$OWN" --allow-runtime-events+ ok: nonce matches the request+ ok: attestation key: restricted, fixed to this TPM+ ok: attestation key: name matches its public area+ ok: attestation key: the pinned key+ ok: endorsement key: name matches its public area+ ok: endorsement key: TCG default template under the endorsement policy+ ok: endorsement key: the pinned key+ ok: attestation key: activated the credential made for it under the endorsement key+ ...+ ok: eventlog: 7 records replay to the certified value+ ok: anchor: record digest matches the index name+ ok: anchor: PCR 9 equals the recorded value extended by the anchor+ ok: state: init event covers the expected certificate, set and tree root+ ok: state: 6 events after boot change the register+ note: event after boot: upatch_load basic+ note: event after boot: upatch_unload basic+ ...+ verdict: ok++ The credential proves that the attestation key sits in the same TPM+ as the endorsement key. ``--cert`` gives every certificate the target+ enrolled, and the boot event must cover exactly that set.+ ``--allow-runtime-events`` accepts the loads and unloads after boot+ without checking them.++2. Record ``$AK`` and ``$EK`` with the target's other records. They are+ its identity from now on. Every later verification pins the signer+ with ``--ak-name``, and the credential needs no second check.++Predict the register+--------------------++1. Predict the register at boot from the enrolled certificates:++ .. code-block:: console++ operator$ shirudo attest predict --cert="$KEYS/cert.der" --cert="$OWN"+ set_digest: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855+ init_event: cb206abf8e514bc714fc69f372d464d2c7512f1489431aed2319551c5ed34b9a+ register_at_boot: d1bdb80f7c0cfc1560f0a5a0b974d282bfd05fc95852b7649d59a054b450aa51++ Your values differ, because the bundle generated your keys. The boot+ event covers the digest of the whole enrolled set. With one+ certificate missing, the prediction describes another target:++ .. code-block:: console++ operator$ shirudo attest predict --cert="$KEYS/cert.der"+ set_digest: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855+ init_event: 1014642f2d76b1eb10b4872c4299a70e191be0eb2958de65a7098bfe92a93124+ register_at_boot: 33ec2c3ed20693c2e40131e693a11b169b91efd8f7438f86313c915e512121e5++ Verifying against that set fails with ``FAIL: state: init event+ covers the expected certificate, set and tree root``.++2. Add the events since boot, in their order:++ .. code-block:: console++ operator$ shirudo attest predict --cert="$KEYS/cert.der" --cert="$OWN" --event=load:basic="$PAYLOAD" --event=unload:basic="$PAYLOAD"+ set_digest: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855+ init_event: cb206abf8e514bc714fc69f372d464d2c7512f1489431aed2319551c5ed34b9a+ register_at_boot: d1bdb80f7c0cfc1560f0a5a0b974d282bfd05fc95852b7649d59a054b450aa51+ register_after_events: fe7bd139c02aca0d6e5efc3940c1cd902adbe676b7875be4c73c878b3f5212b8++ ``register_after_events`` is the register value after the load and the+ unload: the value the unload printed in the quickstart, and the+ ``Chain`` that ``shirudo status`` shows on the target. If you followed+ other quick guides on this VM, the target measured their loads and+ unloads too. Add them in the order you ran them, each with the payload+ digest of its upatch.++Verify evidence+---------------++1. Make a fresh nonce:++ .. code-block:: console++ operator$ NONCE3=$(openssl rand -hex 32)+ operator$ echo "$NONCE3"++2. Take evidence with it on the target:++ .. code-block:: console++ target# shirudo attest --nonce=<nonce3> --out=/mnt/shirudo-out/ev.json++3. Verify it with the pinned key and the predicted register:++ .. code-block:: console++ operator$ shirudo attest verify --evidence="$RESULT/ev.json" --nonce="$NONCE3" --ak-name="$AK" --expect-chain=<register-after-events>+ ok: nonce matches the request+ ...+ ok: eventlog: 7 records replay to the certified value+ ok: anchor: record digest matches the index name+ ok: anchor: PCR 9 equals the recorded value extended by the anchor+ ok: state: register equals the expected value+ note: event after boot: upatch_load basic+ note: event after boot: upatch_unload basic+ ...+ verdict: ok++ ``<register-after-events>`` is the last value of the prediction.++``attest verify`` requires only ``--evidence`` and ``--nonce``. Without+``--ak-name`` it warns ``attest verify: no --ak-name; the signer is not+pinned``. Without a state expectation it checks no state at all, yet+still reports ``verdict: ok``:++.. code-block:: console++ operator$ shirudo attest verify --evidence="$RESULT/ev.json" --nonce="$NONCE3" --ak-name="$AK"+ ...+ ok: anchor: PCR 9 equals the recorded value extended by the anchor+ note: no expected state given; the register value is 52764aa4e68b762c7e5bbacf1261bd3242b44a0b66876f34c89c5b8d57da7177+ note: event after boot: upatch_load basic+ ...+ verdict: ok++That verdict says only that the pinned TPM signed some state. Always give+``--ak-name`` and a state expectation: ``--expect-chain``, or ``--cert``+with ``--upatch`` or ``--expect`` for the upatches restored at boot. The+threat model lists this behavior among the threats to resolve.++Next steps+----------++- :doc:`/operate/attest` attests production targets, with the binding+ PCRs and the approved config image.+- :doc:`/concepts/measurement-register` explains the register, its events+ and its binding.+- :doc:`/reference/cli/attest-verify` lists every check and option of+ ``shirudo attest verify``.+- :doc:`/security/threat-model` describes what attestation covers and+ what it leaves open.diff --git a/Documentation/start/guides/first-upatch.rst b/Documentation/start/guides/first-upatch.rstnew file mode 100644index 00000000..4c04a648--- /dev/null+++ b/Documentation/start/guides/first-upatch.rst@@ -0,0 +1,217 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Tutorial+:audience: upatch authors++Your first upatch+=================++In this tutorial you write a small upatch of your own: a BPF program that+counts the calls of a kernel function in a map. You build and sign it,+load it on the test target, read the count and unload it again.++Before you begin+----------------++- The test VM from the :doc:`/start/quickstart`, running as+ ``quickstart``.+- The operator shell from the quickstart: in the root of your checkout,+ with ``shirudo`` and ``shirudo-build`` on ``PATH`` and ``KEYS`` naming+ the test VM's key directory.+- A root shell on the target (``make -C testing vm-ssh+ VM_NAME=quickstart``) in which ``shirudo`` runs the runtime binary:++ .. code-block:: console++ target# alias shirudo=shirudo-runtime++Write the program+-----------------++1. Make a directory for your work in the checkout:++ .. code-block:: console++ operator$ mkdir -p build/tutorial++ Git ignores ``build/``, and the guest sees the directory as+ ``/workspace/shirudo/build/tutorial``.++2. Write ``build/tutorial/sleep-count.bpf.c``:++ .. code-block:: c++ // SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause+ #include "vmlinux.h"+ #include <bpf/bpf_helpers.h>+ #include <bpf/bpf_tracing.h>++ char _license[] SEC("license") = "Dual BSD/GPL";++ struct {+ __uint(type, BPF_MAP_TYPE_ARRAY);+ __uint(max_entries, 1);+ __type(key, __u32);+ __type(value, __u64);+ } calls SEC(".maps");++ SEC("fentry/do_nanosleep")+ int BPF_PROG(count_nanosleep)+ {+ __u32 key = 0;+ __u64 *n;++ n = bpf_map_lookup_elem(&calls, &key);+ if (n)+ __sync_fetch_and_add(n, 1);+ return 0;+ }++ The ``fentry`` program runs on every entry to the kernel function+ ``do_nanosleep()``, which ``nanosleep(2)`` and ``clock_nanosleep(2)``+ reach, and adds one to the single entry of the array map ``calls``.+ ``vmlinux.h`` declares the kernel's types, so the program compiles once+ and the loader relocates it to the target kernel's layout. Keep the+ license string GPL-compatible: the kernel refuses LSM programs without+ one, and kernel functions and kernel structures to any program without+ one.++Build and sign it+-----------------++1. Build the upatch:++ .. code-block:: console++ operator$ shirudo build build/tutorial/sleep-count.bpf.c --keys-dir "$KEYS" -o build/tutorial/sleep-count.upatch+ wrote build/tutorial/sleep-count.upatch (insns=1184 sig=4853 data=3024 sections=2 maps=1 progs=1 decoders=0 name=sleep-count)++ Run from the checkout root, the helper finds the libbpf headers in+ ``vendor/libbpf`` and the kernel types in ``vendor/linux/vmlinux.h``.+ The upatch takes its name, ``sleep-count``, from the file name, and it+ carries one map and one program. The sizes and digests on this page+ depend on your toolchain and paths.++2. Inspect it:++ .. code-block:: console++ operator$ shirudo upatch info build/tutorial/sleep-count.upatch+ File: build/tutorial/sleep-count.upatch+ Name: sleep-count+ Type: LOAD+ Payload type: bpf+ Version: 1+ Payload SHA256: d7eaea457b679a8e9a6d4a8708ded501c6a3f604c8756388d9e5e4d6f2922c6f+ ...++ Check that ``Name`` is ``sleep-count`` and ``Type`` is ``LOAD``.++3. Keep its payload digest:++ .. code-block:: console++ operator$ COUNT_PAYLOAD=$(shirudo upatch info --json build/tutorial/sleep-count.upatch | jq -r .payload_sha256)++4. Build the unload directive for this payload:++ .. code-block:: console++ operator$ shirudo build --unload sleep-count --payload-sha256 "$COUNT_PAYLOAD" --keys-dir "$KEYS" -o build/tutorial/sleep-count.unload.upatch+ wrote build/tutorial/sleep-count.unload.upatch (insns=1320 sig=4853 data=2808 sections=2 maps=1 progs=1 decoders=0 name=sleep-count UNLOAD)++Load it and read the map+------------------------++1. Load the upatch on the target:++ .. code-block:: console++ target# shirudo upatch load /workspace/shirudo/build/tutorial/sleep-count.upatch+ loaded signed loader: prog_fd=10 keyring=531121468 sig=4853B insns=148 data=3024B+ loader ok, retval=0 (maps=1 progs=1)+ attached + pinned prog 0 (raw_tracepoint) -> /run/shirudo/bpffs/upatches/sleep-count/link+ pinned map 0 (calls, type=2) -> /run/shirudo/bpffs/upatches/sleep-count/maps/calls+ upatch load: name=sleep-count keyring=531121468 progs=1+ upatch load: chain extended, value=88e45b0c80b0ffe83d471b6372402082a5dcf82173adc5c4bdd631039fe4609c+ upatch load measured: name=sleep-count chain=88e45b0c80b0ffe83d471b6372402082a5dcf82173adc5c4bdd631039fe4609c++ The loader created the map and the program in the kernel. shirudo+ pinned both in its private bpffs and measured the load.++2. Sleep a few times:++ .. code-block:: console++ target# sleep 1; sleep 1; sleep 1++3. List the maps of the loaded upatches:++ .. code-block:: console++ target# shirudo upatch map+ UPATCH MAP TYPE ENTRIES+ sleep-count calls array max=1++4. Read the map:++ .. code-block:: console++ target# shirudo upatch map sleep-count calls+ upatch: sleep-count+ Map: calls+ Type: array+ Max entries: 1+ Entries: 1 of 1+ Key type: unsigned int (4 B)+ Value type: unsigned long long (8 B)++ Contents:+ key = 0+ -> 3++ The value is the number of calls so far. It counts every caller on+ the guest, not only your ``sleep`` commands, so yours can be higher.+ Only shirudo's runtime binary can read the map: the LSM refuses the map+ to every other task, root included.++Unload it+---------++1. Unload the upatch:++ .. code-block:: console++ target# shirudo upatch unload /workspace/shirudo/build/tutorial/sleep-count.unload.upatch+ loaded signed loader: prog_fd=10 keyring=531121468 sig=4853B insns=165 data=2808B+ upatch unload: payload matches for 'sleep-count'+ upatch unload: chain extended, value=52764aa4e68b762c7e5bbacf1261bd3242b44a0b66876f34c89c5b8d57da7177+ upatch unload measured: name=sleep-count chain=52764aa4e68b762c7e5bbacf1261bd3242b44a0b66876f34c89c5b8d57da7177+ upatch unload: detached + unpinned sleep-count++2. Check that the map is gone:++ .. code-block:: console++ target# shirudo upatch map+ (no pinned maps)++The count was lost with the unload: the map lived only as long as the+upatch. A single counter fits an array map. An upatch that accumulates+records keeps them in a BPF arena, with a serializer program that exports+them in one consistent snapshot.++Next steps+----------++- :doc:`/upatches/kernel-fix-tutorial` takes a real kernel fix to a+ shipped upatch.+- :doc:`/upatches/attach-kinds` lists the attachment kinds besides+ ``fentry``.+- :doc:`/upatches/maps-arenas-serializers` explains arenas and+ serializers.+- :doc:`publish-package` ships an upatch through an OCI registry.+- :doc:`/reference/cli/upatch-map` describes every option of+ ``shirudo upatch map``.diff --git a/Documentation/start/guides/index.rst b/Documentation/start/guides/index.rstnew file mode 100644index 00000000..4452c0aa--- /dev/null+++ b/Documentation/start/guides/index.rst@@ -0,0 +1,18 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++Quick guides+============++These tutorials continue from the :doc:`/start/quickstart` and run in its+test VM. Each takes one task from start to finish: writing an upatch of+your own, shipping one as a package through an OCI registry, and+enrolling the target's TPM to verify what the target runs.++.. toctree::+ :titlesonly:++ first-upatch+ publish-package+ attest-targetdiff --git a/Documentation/start/guides/publish-package.rst b/Documentation/start/guides/publish-package.rstnew file mode 100644index 00000000..7ef44f68--- /dev/null+++ b/Documentation/start/guides/publish-package.rst@@ -0,0 +1,209 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Tutorial+:audience: Operators, upatch authors++Publish and install a package+=============================++In this tutorial you put an upatch into a package, publish the package to+an OCI registry on your host and install it on the test target from+there. Targets always pull: the operator publishes to a registry, and the+target fetches, checks and loads.++A package is a ``.bee`` archive built from a ``Beefile``. It holds the+``Beefile``, the signed upatches, the signed unload directive of each,+the certificate of the key that signed them, the README when the package+directory has one, and ``build-environment.json``, a record of the build.++Before you begin+----------------++- The test VM from the :doc:`/start/quickstart`, running as+ ``quickstart``.+- The operator shell from the quickstart: in the root of your checkout,+ with ``shirudo`` and ``shirudo-build`` on ``PATH`` and ``KEYS`` naming+ the test VM's key directory.+- Docker on the operator host, for a local registry.+- A root shell on the target (``make -C testing vm-ssh+ VM_NAME=quickstart``) in which ``shirudo`` runs the runtime binary:++ .. code-block:: console++ target# alias shirudo=shirudo-runtime++Start a registry+----------------++1. Run a registry on the host's loopback interface:++ .. code-block:: console++ operator$ docker run -d --name shirudo-registry -p 127.0.0.1:5000:5000 docker.io/library/registry:3++ The registry speaks plain HTTP on port 5000. The test VM reaches the+ host's loopback interface at ``10.0.2.2`` through QEMU's user network.++Build the package+-----------------++1. Make a package directory with an upatch in it:++ .. code-block:: console++ operator$ mkdir ~/hello+ operator$ cp testing/fixtures/basic.bpf.c ~/hello/hello.bpf.c++2. Link the checkout's vendored headers into it:++ .. code-block:: console++ operator$ ln -s "$PWD/vendor" ~/hello/vendor++ The helper compiles in the package directory and looks for the libbpf+ headers and ``vmlinux.h`` under ``vendor/`` there. An installed operator+ package uses its own copies under ``/usr/share/shirudo`` and needs no+ link.++3. Write ``~/hello/Beefile``:++ .. code-block:: toml++ [package]+ name = "hello"+ description = "A first shirudo package"+ license = "GPL-2.0 OR BSD-2-Clause"++ [[upatches]]+ source = "hello.bpf.c"++ Each ``[[upatches]]`` table names one BPF source. The upatch takes its+ name, ``hello``, from the file name.++4. Write ``~/hello/README.md``:++ .. code-block:: markdown++ # hello++ The hello package installs the hello upatch, an fentry program on+ do_nanosleep that does nothing.++ ``shirudo bpm info`` prints this file from a package archive or an+ ``oci://`` reference, for whoever inspects the package.++5. Build the package from its parent directory:++ .. code-block:: console++ operator$ cd ~+ operator$ shirudo bpm build hello --version 1.0.0 --keys-dir "$KEYS"+ wrote /tmp/shirudo-bpm-build.<random>/0.upatch (insns=992 sig=4853 data=2376 sections=2 maps=0 progs=1 decoders=0 name=hello)+ wrote /tmp/shirudo-bpm-build.<random>/0.unload.upatch (insns=1320 sig=4853 data=2808 sections=2 maps=1 progs=1 decoders=0 name=hello UNLOAD)+ /root/hello-1.0.0.bee++ ``<random>`` is the suffix of a temporary directory. The builder+ compiles and signs the upatch, signs an unload directive bound to its+ payload, and writes ``<name>-<version>.bee`` to the current directory.+ The archive itself is not signed: what protects the target are the+ signatures on its upatches and directives.++Publish it+----------++1. Push the package to the registry:++ .. code-block:: console++ operator$ BPM_OCI_SCHEME=http shirudo bpm push hello-1.0.0.bee oci://127.0.0.1:5000/example/hello --keys-dir "$KEYS"+ oci://127.0.0.1:5000/example/hello:1.0.0++ The push tags the package with its version. With ``--keys-dir``, it+ also adds the package to the registry's signed index,+ ``shirudo/bpm-index:stable``, which targets read when they install from+ a registered repository. ``BPM_OCI_SCHEME=http`` drops TLS, which suits+ only a registry on your own host. Without it, shirudo speaks HTTPS with+ TLS 1.3 and a hybrid ML-KEM key exchange.++Install it on the target+------------------------++On a production target, the signed config image registers the+repositories the target may install from. The test VM's config registers+none, so here the target installs by direct reference.++1. Install the package:++ .. code-block:: console++ target# BPM_OCI_SCHEME=http shirudo bpm install oci://10.0.2.2:5000/example/hello:1.0.0+ upatch load: --no-precheck, pre-flight state check skipped+ loaded signed loader: prog_fd=11 keyring=531121468 sig=4853B insns=124 data=2376B+ loader ok, retval=0 (maps=0 progs=1)+ attached + pinned prog 0 (raw_tracepoint) -> /run/shirudo/bpffs/upatches/hello/link+ upatch load: name=hello keyring=531121468 progs=1+ upatch load: chain extended, value=55a8c670eb10d9bc6a9dc7475e3fc94407066016798dddbc59870138525f61b6+ upatch load measured: name=hello chain=55a8c670eb10d9bc6a9dc7475e3fc94407066016798dddbc59870138525f61b6++ The target honors ``BPM_OCI_SCHEME`` as the operator does. It+ downloads the package and checks its digest against the registry's+ manifest. It refuses the package unless the package's certificate+ holds the same public key as the target's+ ``/var/lib/shirudo/keys/cert.der``. Then it loads every upatch in the+ package as ``shirudo upatch load --no-precheck`` does: the kernel checks+ each signature and the target measures each load.++2. List the installed packages:++ .. code-block:: console++ target# shirudo bpm list+ hello 1.0.0 direct++ ``direct`` marks a package installed by reference rather than from a+ registered repository.++3. Check that its upatch is loaded:++ .. code-block:: console++ target# shirudo upatch list+ upatches (/var/lib/shirudo/upatches):+ loaded type kind payload-sha256 name+ yes load bpf 109848737a32f431.. hello++Remove it+---------++1. Uninstall the package on the target:++ .. code-block:: console++ target# shirudo bpm uninstall hello+ upatch unload: --no-precheck, pre-flight state check skipped+ loaded signed loader: prog_fd=11 keyring=531121468 sig=4853B insns=165 data=2808B+ upatch unload: payload matches for 'hello'+ upatch unload: chain extended, value=f4f9b2f7cb9b442d78acc3b0527ad79a4cf9dd1eae1eaedffce9263c53571c05+ upatch unload measured: name=hello chain=f4f9b2f7cb9b442d78acc3b0527ad79a4cf9dd1eae1eaedffce9263c53571c05+ upatch unload: detached + unpinned hello++ The target runs the unload directives that shipped in the package and+ removes the package. ``shirudo bpm list`` no longer lists it.++2. Stop the registry on the host:++ .. code-block:: console++ operator$ docker rm -f shirudo-registry++Next steps+----------++- :doc:`/upatches/beefile` describes every key of a ``Beefile``.+- :doc:`/upatches/publishing` publishes to a registry and to the signed+ upatch tree.+- :doc:`/operate/deliver-packages` registers repositories in the signed+ config and lets the timers keep targets up to date.+- :doc:`/reference/cli/bpm` describes every ``shirudo bpm`` command.diff --git a/Documentation/start/how-it-works.rst b/Documentation/start/how-it-works.rstnew file mode 100644index 00000000..43d35ccf--- /dev/null+++ b/Documentation/start/how-it-works.rst@@ -0,0 +1,201 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++How it works+============++This page follows one upatch from a kernel fix to a measured load on a+target, and back out again. Figure 1 shows the path: the operator host+builds and signs, an OCI registry stores, the target pulls and loads, its+kernel checks the signature, its TPM records the change, and the operator+verifies the record. The numbers in the figure match the steps below. The+background and internals pages linked from each step explain the+mechanisms in depth.++.. figure:: /images/start-how-it-works.svg+ :alt: The operator host builds, signs and pushes to an OCI registry. The+ target pulls, its kernel checks the signature and runs the loader,+ its TPM extends the register and signs evidence, which the+ operator verifies.++ Figure 1. The life of an upatch. Only the operator host holds the+ signing key, and only the target's TPM signs evidence.++Before the first upatch+-----------------------++A target enforces nothing until ``shirudo init`` has run. In production,+systemd runs it from the initrd of a measured unified kernel image (UKI),+before the root file system starts other workloads. ``init`` mounts the+runtime image whose dm-verity root hash the UKI carries, and the config+image whose signed root hash the kernel checks against its trusted keys,+among them the sealed ``.dm-verity`` keyring. It enrolls the trusted certificates in the kernel's+``.bpf`` keyring and seals it, loads the BPF LSM programs embedded in the+binary, restores the upatches archived on earlier boots and binds this+boot's measurement register in the TPM. The root file system runs ``init``+a second time to take over what the initrd set up.++From then on, the kernel accepts BPF programs from userspace only through+a signed loader. :doc:`/internals/boot-flow` describes the two runs, and+:doc:`/concepts/background/boot` and+:doc:`/concepts/background/initrd-dracut` explain the boot mechanisms they+rely on.++Build and sign+--------------++1. An upatch starts as BPF C source, often a few lines that refuse the+ call a kernel fix closes. It reads kernel structures through CO-RE, so+ the target kernel adjusts field offsets to its own layout when the+ program loads (:doc:`/concepts/background/co-re-btf`).++ A BPF object cannot be signed as it is. libbpf rewrites it while loading:+ it fills in map descriptors, applies relocations and resolves kernel+ symbols, so the bytes the kernel would check are not the bytes the+ operator built. shirudo therefore signs a loader instead. ``shirudo+ build`` hands the work to the operator-only helper ``shirudo-build``,+ which compiles the source with clang and lets libbpf generate a loader: a+ small program of type ``BPF_PROG_TYPE_SYSCALL`` that performs the load+ steps inside the kernel, with the payload programs in its data. The+ helper appends the upatch's name, its attach metadata and any decoders+ to that data, signs the loader instructions followed by the data with+ the operator's ML-DSA-87 key, and writes the ``.upatch`` file.++ The same command with ``--unload`` builds the unload directive that+ removes the upatch later. :doc:`/concepts/background/bpf-signing`+ explains the kernel's side of the scheme.++Package and publish+-------------------++2. ``shirudo bpm build`` reads a Beefile, builds each upatch it lists with+ its unload directive, and packs them into a ``.bee`` package.+ ``shirudo bpm push`` uploads the package to an OCI registry and, given+ the signing key, adds it to the registry's signed package index.+ ``shirudo bpm tree append`` can also publish the package's upatches as+ operations of a signed upatch tree, each with a selector that names the+ targets it applies to.++ The registry stores and serves bytes, and the design does not trust it.+ It can withhold or replay what the operator published, but it cannot+ produce an index, a tree or an upatch that passes the target's signature+ checks. :doc:`/concepts/upatches-and-packages` describes the objects, and+ :doc:`/concepts/background/oci` the registry protocol.++Pull+----++3. On the target, ``shirudo-bpm-repo-update.timer`` runs ``shirudo bpm repo+ update`` and then ``shirudo bpm upgrade``, a minute after the previous+ run ends. ``repo update`` fetches the index and checks its signature+ against the repository certificate in the signed config image.+ ``upgrade`` fetches the newest indexed version of each installed+ package, checks its digests against the index, unpacks it and loads its+ upatches. ``shirudo bpm install`` does the same for a package named by+ hand.++ ``shirudo-bpm-tree-sync.timer`` runs ``shirudo bpm tree sync`` every+ minute. It fetches the tree publication, checks its signature, and+ applies in sequence the operations whose selectors match this target.++Load+----++4. Every path ends in the same load, the one ``shirudo upatch load``+ performs. shirudo copies the loader's data into an array map, freezes+ the map, and makes it usable by this loader alone by naming the SHA-256+ of the loader's instructions. It then asks the kernel to load the loader+ with ``BPF_PROG_LOAD``, passing the signature and the ``.bpf`` keyring.++5. The kernel checks one signature over the loader's instructions followed+ by the frozen map contents, before its verifier runs. Two of shirudo's+ BPF LSM programs bracket that check. ``lsm/bpf`` admits a program load+ from userspace only for a signed ``BPF_PROG_TYPE_SYSCALL`` program, and+ ``lsm/bpf_prog_load`` admits it only when the kernel recorded the+ signature as verified against the ``.bpf`` keyring.++ shirudo then runs the loader. The loader creates the upatch's maps and+ loads its programs from kernel context, where the verifier still checks+ each one. shirudo attaches every program at the site the signed attach+ metadata names, compares the link the kernel reports with that site,+ and pins links and maps in its private bpffs under+ ``/run/shirudo/bpffs/upatches/``. It records the payload digest on the+ pin directory and archives the artifact in ``/var/lib/shirudo/upatches/``+ for the next boot. :doc:`/internals/signed-loader` walks through each+ system call, and :doc:`/concepts/background/bpf-lsm` explains the hooks.++Measure+-------++6. Once the artifact is archived, shirudo extends the measurement register+ with an event over the payload digest and the upatch's name, and appends+ a matching record to the eventlog. When the archive copy or the+ extension fails, shirudo undoes the load rather than leave it+ unmeasured. If the undo fails as well, the command says so and leaves+ the target for the operator to reconcile.++ The register starts from zero at every boot. Its value depends only on+ the trusted certificates, the set restored at boot, the upatch tree's+ position and the events since then, so the operator can compute it+ without the target's history. :doc:`/concepts/measurement-register`+ explains why the register is built this way.++Attest+------++7. The operator chooses a fresh nonce, and ``shirudo attest+ --nonce=<hex>`` on the target produces evidence: a TPM quote over the+ PCRs and a TPM certification of the register, both signed by the TPM's+ attestation key, together with this boot's eventlog records. On the+ operator host, ``shirudo attest predict`` computes the register value+ the shipped certificates and artifacts must produce, and ``shirudo+ attest verify`` checks the signatures and the nonce, replays the records+ to the certified value and compares it with that expectation. Neither+ command opens a TPM. :doc:`/operate/attest` shows the procedure, and+ :doc:`/concepts/background/tpm` explains the TPM operations.++Export+------++Two more timers send telemetry while upatches run.+``shirudo-map-export.timer`` runs ``shirudo upatch map --all``, which reads+the maps of every loaded upatch, runs their serializers and signed Lua+decoders, and sends the records to the destinations the config image's+``map_export`` settings name. ``shirudo-keepalive.timer`` runs ``shirudo+status --otel --include-system``, which sends the target's status as an+OTLP log record when an endpoint is configured. Both run five seconds after+the previous run ends.++Telemetry carries no proof of origin. It is the target's own account, and+the TPM-signed evidence of step 7 is the check. :doc:`/operate/telemetry`+covers the export settings.++Unload+------++An upatch leaves the target through its unload directive. ``shirudo+upatch unload`` loads the directive's loader through the same signature+check, and that check is what authorizes the unload. The loader itself+never runs. shirudo compares the payload digest the directive names with+the one recorded on the upatch's pin, and refuses with+``payload_mismatch`` when they differ.++shirudo extends the register with the unload event before it removes the+pins. An unload interrupted between the two leaves a register that records+more than happened, never a detach the register does not know. shirudo+also deletes the archived copy, so the next boot does not restore the+upatch. ``shirudo bpm uninstall`` and a tree ``delete`` operation remove+upatches through their directives in the same way.++Related+-------++- :doc:`what-is-shirudo` for the problem shirudo addresses and its scope.+- :doc:`/concepts/operator-and-target` for what each side holds.+- :doc:`/internals/architecture` for the components and their code.+- :doc:`/security/security-model` for what each step protects against+ and where it stops.diff --git a/Documentation/start/index.rst b/Documentation/start/index.rstnew file mode 100644index 00000000..1a288757--- /dev/null+++ b/Documentation/start/index.rst@@ -0,0 +1,23 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++Start+=====++Start here if you are new to shirudo. The quickstart builds it, boots a+protected test target in a VM and takes one upatch through its whole+life. The next two pages explain the problem shirudo addresses and the+path an upatch takes from a kernel fix to a measured load. The+installation page and the quick guides then cover the first tasks:+installing the packages, writing an upatch, publishing a package and+attesting a target.++.. toctree::+ :titlesonly:++ quickstart+ what-is-shirudo+ how-it-works+ install+ guides/indexdiff --git a/Documentation/start/install.rst b/Documentation/start/install.rstnew file mode 100644index 00000000..21869899--- /dev/null+++ b/Documentation/start/install.rst@@ -0,0 +1,250 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Install shirudo+===============++shirudo installs in one of two roles. The operator host holds the signing+key and builds, signs and publishes. A target verifies and enforces. Each+role has its own package, built from a checkout, and one host takes one+role. This page installs the packages, or the same files from source, and+lists what a target needs before it enforces anything.++Before you begin+----------------++- Decide which hosts are operators and which are targets.+ :doc:`/concepts/operator-and-target` explains the split.+- A checkout of shirudo on a build host that meets the build requirements+ in :doc:`/operate/system-requirements`.+- ``dpkg-deb`` (package ``dpkg-dev``) to build ``.deb`` packages, or+ ``rpmbuild`` (package ``rpm`` on Debian and Ubuntu, ``rpm-build`` on+ Fedora) to build ``.rpm`` packages.+- The target package links everything statically and installs on any+ supported distribution. The operator package links the build host's+ shared libraries, so build it on the distribution you install it on.++Packages+--------++.. list-table::+ :header-rows: 1+ :widths: 22 18 60++ * - Package+ - Host+ - Installs+ * - ``shirudo-operator``+ - Operator host+ - - ``/usr/bin/shirudo``, linked against the host's shared libraries+ - the helper ``/usr/libexec/shirudo/shirudo-build``+ - the image generators ``shirudo-gen-image``,+ ``shirudo-gen-runtime`` and ``shirudo-gen-verity`` under+ ``/usr/libexec/shirudo/gen-image/``+ - ``/usr/share/shirudo/vmlinux.h``, the one the package was built+ with+ - the BPF headers under ``/usr/share/shirudo/bpf/include/``+ - bash completion++ It depends on clang, LLVM and ``veritysetup`` (``cryptsetup-bin``+ or ``cryptsetup``) and installs no systemd unit.+ * - ``shirudo-target``+ - Target+ - - ``/usr/bin/shirudo``, a static PIE+ - ``/usr/bin/shirudo-gen-initrd``+ - the dracut module ``/usr/lib/dracut/modules.d/90shirudo``+ - the units ``shirudo.service`` and ``shirudo-initrd.service``+ - the services ``shirudo-map-export``, ``shirudo-keepalive``,+ ``shirudo-bpm-repo-update`` and ``shirudo-bpm-tree-sync``, each+ with its timer+ - bash completion++ It carries no key and no configuration file.++Both packages install ``/usr/bin/shirudo``, so they conflict, and a host+holds only one of them. On a development host that plays both roles, run+shirudo from a checkout as in the :doc:`quickstart`.++Build the packages+------------------++1. In the checkout, build the ``.deb`` packages:++ .. code-block:: console++ $ make -C packaging bindeb-pkg++ The build starts from ``make clean``, rebuilds with the prefix+ ``/usr`` and writes ``shirudo-target_<version>_<arch>.deb`` and+ ``shirudo-operator_<version>_<arch>.deb`` to the checkout root.+ For ``.rpm`` packages, run ``make -C packaging binrpm-pkg`` instead,+ which writes ``shirudo-target-<version>-<release>.<arch>.rpm`` and+ ``shirudo-operator-<version>-<release>.<arch>.rpm``.++2. To build the operator package for another distribution, build only+ that package on a host of that distribution:++ .. code-block:: console++ $ make -C packaging bindeb-pkg PKG_ROLES=operator++ ``PKG_ROLES=target`` builds only the target package.++Install the operator package+----------------------------++1. Install the package on the operator host:++ .. code-block:: console++ # apt install ./shirudo-operator_<version>_<arch>.deb++ On an RPM distribution, run+ ``dnf install ./shirudo-operator-<version>-<release>.<arch>.rpm``.++2. Check that ``shirudo`` finds its helper:++ .. code-block:: console++ operator$ shirudo build --help+ ...+ SHIRUDO_BUILD, /usr/libexec/shirudo/shirudo-build, then shirudo-build on PATH.+ ...++ The second path is where the package installed the helper.++Install the target package+--------------------------++1. Install the package on the target:++ .. code-block:: console++ # apt install ./shirudo-target_<version>_<arch>.deb+ ...+ shirudo: shirudo.service enabled; it runs 'shirudo init' early on the+ shirudo: next boot. To enforce now: systemctl start shirudo.service+ shirudo: shirudo-map-export.timer enabled for the next boot+ shirudo: shirudo-keepalive.timer enabled for the next boot+ shirudo: shirudo-bpm-repo-update.timer enabled for the next boot+ shirudo: shirudo-bpm-tree-sync.timer enabled for the next boot++ On an RPM distribution, run+ ``dnf install ./shirudo-target-<version>-<release>.<arch>.rpm``. The RPM+ prints the same lines on its first installation.++ The package enables ``shirudo.service`` and the four timers for the next+ boot and starts none of them. Starting ``shirudo.service`` by hand does+ nothing yet, whatever the message says: the unit runs only when+ ``/run/shirudo/runtime`` is mounted, and the shirudo initrd mounts it at+ boot. Removing the package disables the units again.++2. Check the pre-flight on the target:++ .. code-block:: console++ target# shirudo init --check-only++ It lists each prerequisite of ``init`` with its result and changes no+ enforcement state. On a fresh target it reports what is still missing,+ such as the certificate.++Install the target from a tarball+---------------------------------++``make -C packaging bintar-pkg`` builds two target tarballs,+``shirudo.tar.gz`` and ``shirudo-static.tar.gz``. Both carry the same+static target binary and the other files of the target package, with the+binaries under ``/usr/local/bin``.++1. Unpack the tarball on the target:++ .. code-block:: console++ $ tar -xzf shirudo.tar.gz++2. Run its installer as root:++ .. code-block:: console++ # ./shirudo-installer/install.sh+ shirudo installer: installed into /++ The installer copies the files and reloads systemd. It enables no unit:+ enable ``shirudo.service`` and the timers yourself with+ ``systemctl enable``. Set ``DESTDIR=<dir>`` to stage the files into+ ``<dir>`` instead.++Install from source+-------------------++The install targets of the checkout install the same files as the+packages, with the binaries under ``/usr/local`` unless you set+``prefix``. Like the packages, the two roles install the same+``bin/shirudo``, so install one role per host.++1. On an operator host, build and install the operator role:++ .. code-block:: console++ # make install-operator++2. On a target, build and install the target role:++ .. code-block:: console++ # make install-target++ This builds OpenSSL, libcurl and tpm2-tss from source first and links+ the static target binary against them and the static archives that+ :doc:`/operate/system-requirements` lists. It enables no unit.++3. Check the installation on either host:++ .. code-block:: console++ $ shirudo version++ It prints the release and the version ID that ``upatch load+ --expect-version-id`` compares against.++Before a target enforces+------------------------++Installing ``shirudo-target`` protects nothing by itself. A target+enforces once it boots through the shirudo initrd with everything that+``init`` verifies there:++- A kernel that meets :doc:`/operate/system-requirements`, booted with+ the BPF LSM active and with ``bpf.keyring_unsealed=1+ dm_verity.keyring_unsealed=1``, so that ``init`` can enroll the trusted+ certificates and then seal the ``.bpf`` and ``.dm-verity`` keyrings.+- A TPM 2.0 that the kernel exposes as ``/dev/tpmrm0``.+- The operator's certificate in ``/var/lib/shirudo/keys/cert.der``, which+ the dracut module copies into the initrd.+- A dm-verity runtime image and a signed config image, built on the+ operator host with the image generators, and the bootstrap+ configuration that names them.+- An initrd built with ``shirudo-gen-initrd``, booted from an+ authenticated unified kernel image.+- A drop-in that makes ``shirudo.service`` run the binary on the runtime+ image instead of ``/usr/bin/shirudo``, which ``shirudo-gen-runtime``+ writes. On a protected target shirudo runs only from the runtime image,+ so the timer services need the same change to work. The generator does+ not write drop-ins for them.++:doc:`/operate/boot-integration` sets these up. After the reboot,+``shirudo status`` on the target shows ``Status: ok``, ``Mode:+production`` and ``Bound in: initrd``.++Next steps+----------++- :doc:`/operate/boot-integration` brings an installed target up.+- :doc:`/operate/deployment-checklist` lists every step of a rollout.+- :doc:`/operate/keys` creates the signing key on the operator host.+- :doc:`quickstart` tries everything in a test VM first.diff --git a/Documentation/start/quickstart.rst b/Documentation/start/quickstart.rstnew file mode 100644index 00000000..d01e10d5--- /dev/null+++ b/Documentation/start/quickstart.rst@@ -0,0 +1,539 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Tutorial+:audience: First-time users++Quickstart+==========++In this tutorial you build shirudo from a checkout, boot a protected test+target in a virtual machine and take one upatch through its whole life:+you sign it on the operator side, load it on the target, check with the+target's TPM what the target runs, and unload it again.++Your host plays the operator. The test VM plays the target: it boots the+way a production target does and enforces the same policy.++Before you begin+----------------++- A Linux host on x86-64 or arm64 with KVM. ``/dev/kvm`` must be readable+ and writable.+- Root on that host. The test VM builds its initrd with dracut, which needs+ root, and the signing key it generates for the VM belongs to root. Run+ every host command on this page as root.+- Network access. The first boot clones the bpf-next kernel tree and+ downloads an Ubuntu cloud image.+- To build shirudo: a C toolchain with ``make`` and ``pkg-config``, a+ current clang and LLVM with the BPF target, installed as+ ``/usr/bin/clang``, and the development files of OpenSSL 3.5 or later,+ libelf, zlib, libcurl 7.75 or later, tpm2-tss (``tss2-esys`` 4.0 or later+ and ``tss2-tctildr``) and LuaJIT.+- For the test VM, with their Debian and Ubuntu names: QEMU+ (``qemu-system-x86`` or ``qemu-system-arm``), ``qemu-utils``, ``swtpm``,+ ``cloud-image-utils``, ``libguestfs-tools``, ``dracut-core``,+ ``cryptsetup-bin``, ``e2fsprogs``, ``openssh-client``, ``iproute2``,+ ``isc-dhcp-client``, ``curl``, ``kmod`` and ``file``, and the static+ archives the target binary links: libelf, zlib, zstd, LuaJIT and a static+ glibc. The VM scripts stop at the first missing command and print the+ command that installs it. The kernel build installs its own build+ dependencies.+- ``jq`` and the ``openssl`` command, for the attestation step.++:doc:`/operate/system-requirements` lists the requirements in full.++Build shirudo+-------------++1. In the root of your checkout, build the ``shirudo`` binary:++ .. code-block:: console++ operator$ make++2. Build the operator helper:++ .. code-block:: console++ operator$ make shirudo-build++ ``shirudo`` is the command you run on both sides. Operator commands+ such as ``shirudo build`` hand their work to the helper+ ``tools/shirudo-build/shirudo-build``, which compiles and signs. The+ signing code lives only in the helper, so it never reaches a target.++3. Put both on your ``PATH`` for this shell:++ .. code-block:: console++ operator$ export PATH="$PWD:$PWD/tools/shirudo-build:$PATH"++ When no helper is installed, ``shirudo`` finds it on ``PATH``.++Boot a test target+------------------++1. Boot a test VM named ``quickstart``:++ .. code-block:: console++ operator$ make -C testing vm VM_NAME=quickstart+ ...+ [test-vm] building an initrd with shirudo for 7.3.0-bpf-next++ [test-vm] booting bzImage with 4 CPUs and 4G memory+ [test-vm] VM ready: name=quickstart state=.../build/test-vm/vms/quickstart qemu_pid=... swtpm_pid=...+ ...+ [test-vm] console: make -C testing vm-console VM_NAME=quickstart+ [test-vm] ssh: make -C testing vm-ssh++ The first run takes a while. It builds a bpf-next kernel with the+ patches under ``kernel/``, an Ubuntu disk image and a bundle: the static+ target binary, a dm-verity runtime image, signed config images and a+ throwaway signing key. Later runs reuse them.++ The VM boots the way a production target does. The kernel starts with+ the BPF LSM and with the ``.bpf`` and ``.dm-verity`` keyrings open for+ enrollment. ``shirudo init`` runs from the initrd: it mounts the runtime+ image and the signed config image, enrolls the bundle's certificates in+ the ``.bpf`` keyring and seals it, attaches its LSM programs and binds+ the measurement register in the TPM, here a software TPM (``swtpm``).+ The root file system then runs ``init`` a second time and takes over.+ One thing differs from production: QEMU starts the kernel and initrd+ directly, not from a signed unified kernel image, so nothing measures+ the boot phases into PCR 11.++2. Open a root shell on the target:++ .. code-block:: console++ operator$ make -C testing vm-ssh VM_NAME=quickstart++ Commands with the ``target#`` prompt run in this shell.++3. Make ``shirudo`` name the trusted binary in this shell:++ .. code-block:: console++ target# alias shirudo=shirudo-runtime++ On a target, the trusted ``shirudo`` is the binary on the runtime image,+ ``/run/shirudo/runtime/usr/bin/shirudo``, and the test VM wraps it as+ ``shirudo-runtime``. The LSM gives access to shirudo's state only to+ tasks that executed that binary from the runtime image. The test VM+ keeps an identical copy under ``/usr/local/bin``. That copy prints its+ version, but every command that reads shirudo's state stops:++ .. code-block:: console++ target# /usr/local/bin/shirudo status+ shirudo: image state: Permission denied++4. Change to your checkout inside the guest:++ .. code-block:: console++ target# cd /workspace/shirudo++ The test VM shares your checkout with the guest, which sees it at+ ``/workspace/shirudo``. A file you build under the checkout on the host+ shows up there. Files you change in the guest stay in the guest.++Check enforcement+-----------------++1. Read the status report:++ .. code-block:: console++ target# shirudo status+ Host: quickstart+ Roles: target+ Mode: production+ Status: ok+ Version-ID: 58b05ab35a2bcefaa649faf15f8c6be0211e24cea710450c1a29298c3b5c7de0++ Conditions:+ TYPE STATUS DETAIL+ LsmAttached OK lsm/bpf link present and pinned+ KeyringSealed OK serial=531121468 in the BPF keyring, pin matches+ ChainIntact OK live register == eventlog replay+ TpmMeasured OK NV index 0x01818E00 readable+ ConfigActive OK config 12dbf3c75083.. is active++ Tamper attempts (refused this boot):+ LoadNotLoader 15 program load that is not a signed loader+ MapCreate 1 map creation by another executable+ BpfCommand 8 detach, update, delete or unclassified bpf() command+ SealPtrace 6 ptrace of a shirudo task++ Keyring (.bpf):+ Serial: 531121468+ Frozen serial: 531121468 (matches)+ Certificates: 2 trusted, 0 revoked, 0 unvouched, 2 in the bpf keyring+ 2edb279c05efee6b489a65ae07fd6d402a54b6e495be68f6d364544e9b5a37e2+ d1dc6624ee6bd0c277864fab0a8a15f8509308aa2338768cb772117c157f8d61 (primary)++ upatches loaded (0):++ TPM Measurement:+ TPM: reachable (device:/dev/tpmrm0)+ NV index: 0x01818E00 (anchored in PCR 9)+ Chain: d1bdb80f7c0cfc1560f0a5a0b974d282bfd05fc95852b7649d59a054b450aa51+ Register name: 000ba2eb9b8bacc4945436016666062d11be813365bf252841e557b34d5fe3ffae1a+ Anchored: yes (name on record)+ PCR before init: 0000000000000000000000000000000000000000000000000000000000000000+ Phase at init: 0000000000000000000000000000000000000000000000000000000000000000 (PCR 11)+ Bound in: initrd+ Chain vs eventlog: matches+ Eventlog: /var/lib/shirudo/eventlog (1 entries, 1975 bytes)++ Assets (/var/lib/shirudo):+ keys/cert.der present+ keys/signing_key.pem absent+ eventlog present (1975 bytes)+ upatches/ absent+ incoming/ absent+ bpffs/ mounted++ Your serials, digests and counts differ: the bundle generates its own+ keys, and the TPM and the guest are your own. Look at these parts:++ - ``Status: ok`` with every condition ``OK``. Scripts read the verdict+ from ``shirudo status --json``, because the command exits with 0+ whatever the verdict is.+ - ``Mode: production``: the LSM link is pinned.+ - The keyring: the frozen serial matches the live one, and the ``.bpf``+ keyring holds two certificates. The primary one belongs to the+ bundle's signing key. The other is a second certificate, vouched for+ by the first, which the test VM enrolls to exercise a set of keys.+ - The TPM measurement: ``Bound in: initrd`` and ``Chain vs eventlog:+ matches``. ``Chain`` is the register's value, and the eventlog holds+ one entry, the boot event.+ - The tamper attempts: calls the policy refused since boot. Other+ software on the guest has already made some.++2. Try to read one of shirudo's pins as root:++ .. code-block:: console++ target# cat /run/shirudo/bpffs/tamper+ cat: /run/shirudo/bpffs/tamper: Permission denied++ Root without runtime authority cannot open shirudo's maps and links.+ The next status report counts the attempt under ``ObjGet``.++Build and sign an upatch+------------------------++The test VM's bundle generated an ML-DSA-87 key pair for this VM, and the+VM enrolled its certificate. You sign with that key on the host.++1. Name the key directory, here for the default bpf-next kernel:++ .. code-block:: console++ operator$ KEYS=$PWD/build/test-vm/host-bundle-bpf-next-verity.operator/keys++2. Look at the upatch you are going to sign,+ ``testing/fixtures/basic.bpf.c``:++ .. code-block:: c++ // SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause+ #include "vmlinux.h"+ #include <bpf/bpf_helpers.h>+ #include <bpf/bpf_tracing.h>++ char _license[] SEC("license") = "Dual BSD/GPL";++ SEC("fentry/do_nanosleep")+ int BPF_PROG(shirudo_test_basic)+ {+ return 0;+ }++ It attaches to the kernel function ``do_nanosleep()`` and does nothing,+ which makes it a safe first load.++3. Build and sign it:++ .. code-block:: console++ operator$ shirudo build testing/fixtures/basic.bpf.c --keys-dir "$KEYS" --vmlinux vendor/linux/vmlinux.h -o basic.upatch+ wrote basic.upatch (insns=992 sig=4853 data=2456 sections=2 maps=0 progs=1 decoders=0 name=basic)++ The helper compiles the program with clang against the kernel types in+ ``vendor/linux/vmlinux.h``, turns the object into a loader program that+ performs the load on the target, and signs the loader and its data with+ your key. The upatch takes its name, ``basic``, from the file name.+ The sizes and the digests on this page depend on your toolchain and on+ the path of the source, so yours differ.++4. Inspect the artifact:++ .. code-block:: console++ operator$ shirudo upatch info basic.upatch+ File: basic.upatch+ Name: basic+ Type: LOAD+ Payload type: bpf+ Version: 1+ Payload SHA256: 46f3d9f5f6568bddb7692cad28e99a86a3104192d8a2251f9ef9ec6d593c2035+ File size: 8661 bytes++ Loader:+ Instructions: off=360 len=992+ Log buffer size: 1048576+ Metadata: (none)+ Data: off=6205 len=2456++ Signature:+ Offset: 1352+ Length: 4853 bytes++ Signed sections:+ Name: basic+ Attach metadata: 176 bytes+ Unload payload: (none)++ Decoders:+ (none)++ ``Payload SHA256`` identifies what the upatch loads. The target records+ it with the load, and the register measures it.++5. Keep the payload digest:++ .. code-block:: console++ operator$ PAYLOAD=$(shirudo upatch info --json basic.upatch | jq -r .payload_sha256)++6. Build the unload directive for this payload:++ .. code-block:: console++ operator$ shirudo build --unload basic --payload-sha256 "$PAYLOAD" --keys-dir "$KEYS" -o basic.unload.upatch+ wrote basic.unload.upatch (insns=1320 sig=4853 data=2808 sections=2 maps=1 progs=1 decoders=0 name=basic UNLOAD)++ An unload is a signed artifact too, and the target runs it through the+ same signature check as a load. The directive names the upatch and the+ payload it removes: if another payload is loaded under the name+ ``basic``, the target refuses it with ``payload_mismatch``.++Load it+-------++1. Load the upatch on the target:++ .. code-block:: console++ target# shirudo upatch load basic.upatch+ loaded signed loader: prog_fd=10 keyring=531121468 sig=4853B insns=124 data=2456B+ loader ok, retval=0 (maps=0 progs=1)+ attached + pinned prog 0 (raw_tracepoint) -> /run/shirudo/bpffs/upatches/basic/link+ upatch load: name=basic keyring=531121468 progs=1+ upatch load: chain extended, value=ff0eb201e073fdeeba80a4b268f039bea58ec6dd2998e6651c4834ee99f3e103+ upatch load measured: name=basic chain=ff0eb201e073fdeeba80a4b268f039bea58ec6dd2998e6651c4834ee99f3e103++ The kernel checked the loader's signature against the ``.bpf`` keyring+ (the serial from the status report) before it accepted the load. The+ loader then ran in the kernel and created the program, and shirudo+ attached it and pinned the link in its private bpffs. Last, shirudo+ extended the measurement register with the load and appended the event+ to the eventlog.++2. List the upatches:++ .. code-block:: console++ target# shirudo upatch list+ upatches (/var/lib/shirudo/upatches):+ loaded type kind payload-sha256 name+ yes load bpf 46f3d9f5f6568bdd.. basic++ The target keeps a copy of the artifact and loads it again at the next+ boot.++3. Read the status report again:++ .. code-block:: console++ target# shirudo status+ ...+ upatches loaded (1):+ NAME LOCATION MAPS STATUS AGE+ basic fentry/do_nanosleep 0 success 0s++ TPM Measurement:+ ...+ Chain: ff0eb201e073fdeeba80a4b268f039bea58ec6dd2998e6651c4834ee99f3e103+ ...+ Eventlog: /var/lib/shirudo/eventlog (2 entries, 2311 bytes)+ ...++ The register moved from its boot value to the value the load printed,+ and the eventlog holds the boot event and the load.++Verify with the TPM+-------------------++The status report is what the target says about itself. Evidence signed+by its TPM lets you check the same facts on the operator side, with+nothing but the evidence, your certificates and your artifacts.++1. Make a fresh nonce on the operator host:++ .. code-block:: console++ operator$ NONCE=$(openssl rand -hex 32)+ operator$ echo "$NONCE"+ 407c16fda5701c6159662135fb40979a44f7e3b048fef2b73f84fff83ff91083++2. Ask the target for evidence that answers this nonce:++ .. code-block:: console++ target# shirudo attest --nonce=<nonce> --out=/mnt/shirudo-out/ev.json++ ``<nonce>`` is the value you printed. The TPM signs a quote over the+ PCRs and a certification of the register with its attestation key, and+ the document adds this boot's eventlog. ``/mnt/shirudo-out`` is a+ directory the test VM shares with the host, as+ ``build/test-vm/vms/quickstart/result``.++3. Name the evidence and the second enrolled certificate on the host:++ .. code-block:: console++ operator$ EV=build/test-vm/vms/quickstart/result/ev.json+ operator$ OWN=build/test-vm/host-bundle-bpf-next-verity/fixtures/own.der++4. Predict the register from what you know:++ .. code-block:: console++ operator$ shirudo attest predict --cert="$KEYS/cert.der" --cert="$OWN" --event=load:basic="$PAYLOAD"+ set_digest: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855+ init_event: cb206abf8e514bc714fc69f372d464d2c7512f1489431aed2319551c5ed34b9a+ register_at_boot: d1bdb80f7c0cfc1560f0a5a0b974d282bfd05fc95852b7649d59a054b450aa51+ register_after_events: ff0eb201e073fdeeba80a4b268f039bea58ec6dd2998e6651c4834ee99f3e103++ ``register_at_boot`` is the ``Chain`` of the first status report and+ ``register_after_events`` the ``Chain`` after the load. The boot event+ covers the set of certificates ``init`` enrolled, so the prediction+ takes every enrolled certificate: the test VM enrolls two, the bundle's+ ``cert.der`` and ``own.der``. It also covers the upatches restored at+ boot, none here, which is why ``set_digest`` is the SHA-256 of empty+ input.++5. Verify the evidence against the prediction:++ .. code-block:: console++ operator$ shirudo attest verify --evidence="$EV" --nonce="$NONCE" --ak-name="$(jq -r .ak.name "$EV")" --expect-chain=<register-after-events>+ ok: nonce matches the request+ ok: attestation key: restricted, fixed to this TPM+ ok: attestation key: name matches its public area+ ok: attestation key: the pinned key+ ...+ ok: quote: ECDSA signature by the attestation key+ ...+ ok: register: certified contents match the listed value+ ok: quote and certification are of one TPM reset+ ok: config: config root history matches the quoted PCR+ note: config root has no operator approval; use --expect-config-root with --expect-config-pcr+ note: config records a selection; direct TPM writer protection is deferred+ ok: eventlog: this boot has an init record+ ...+ ok: eventlog: 2 records replay to the certified value+ ok: anchor: record digest matches the index name+ ok: anchor: PCR 9 equals the recorded value extended by the anchor+ ok: state: register equals the expected value+ note: event after boot: upatch_load basic+ verdict: ok++ ``<register-after-events>`` is the last line of the prediction. The+ checks prove that the target's TPM signed the evidence for your nonce,+ that the eventlog replays to the register value the TPM certified, and+ that this value is the one you predicted. The command exits with 0 on+ ``verdict: ok`` and with 1 on ``verdict: FAIL``. The notes name checks+ this page leaves out, such as the approved config image.+ :doc:`/operate/attest` covers them.++ Here you took the attestation key's name from the evidence itself,+ which proves nothing about which TPM signed it. :doc:`guides/attest-target`+ shows how to pin the key once, with a challenge only the target's TPM+ can answer.++Unload it+---------++1. Unload the upatch:++ .. code-block:: console++ target# shirudo upatch unload basic.unload.upatch+ loaded signed loader: prog_fd=10 keyring=531121468 sig=4853B insns=165 data=2808B+ upatch unload: payload matches for 'basic'+ upatch unload: chain extended, value=fe7bd139c02aca0d6e5efc3940c1cd902adbe676b7875be4c73c878b3f5212b8+ upatch unload measured: name=basic chain=fe7bd139c02aca0d6e5efc3940c1cd902adbe676b7875be4c73c878b3f5212b8+ upatch unload: detached + unpinned basic++ The target ran the signed directive, checked that the loaded payload is+ the one it names, measured the unload, then detached the program.++2. List the upatches:++ .. code-block:: console++ target# shirudo upatch list+ upatches (/var/lib/shirudo/upatches):+ (none persisted)++ The register did not return to its boot value. It moved forward to a+ third value, and the eventlog records the boot, the load and the+ unload. The register only starts over when the TPM resets, at the next+ boot. To predict it now, give ``attest predict`` both events:+ ``--event=load:basic="$PAYLOAD" --event=unload:basic="$PAYLOAD"``.++Stop the VM+-----------++The quick guides continue with this VM. Keep it running if you go on with+them.++1. Leave the target shell:++ .. code-block:: console++ target# exit++2. Stop the VM:++ .. code-block:: console++ operator$ make -C testing vm-stop VM_NAME=quickstart++ The VM's disk, TPM state and logs stay under+ ``build/test-vm/vms/quickstart``. A stopped VM does not boot again under+ the same name.++3. Remove its state when you no longer need it:++ .. code-block:: console++ operator$ make -C testing vm-clean VM_NAME=quickstart++Next steps+----------++- :doc:`guides/first-upatch` writes an upatch of your own.+- :doc:`guides/publish-package` ships an upatch through an OCI registry.+- :doc:`guides/attest-target` enrolls the target's TPM and verifies its+ evidence.+- :doc:`how-it-works` explains each step of this page.+- :doc:`install` installs shirudo on real hosts, and+ :doc:`/operate/boot-integration` brings a target up.diff --git a/Documentation/start/what-is-shirudo.rst b/Documentation/start/what-is-shirudo.rstnew file mode 100644index 00000000..52400929--- /dev/null+++ b/Documentation/start/what-is-shirudo.rst@@ -0,0 +1,111 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: All readers++What is shirudo+===============++shirudo is a BPF security platform for Linux. It delivers BPF programs,+called upatches, to running machines without a reboot, and it restricts the+``bpf()`` system call so that the kernel accepts BPF from userspace only+inside a loader signed with the operator's key. Every change to the loaded+set is measured into a TPM register, and the TPM signs that record on+request.++Problem+-------++A kernel fix reaches a fleet only when every machine has booted a kernel+that carries it. The fix is often public long before that, and for a fleet+with a reboot cycle of days or weeks, that gap is when an attacker who reads+the fix can use the bug.++BPF can close the gap. A BPF program attached to an LSM hook or to the+vulnerable function can refuse the dangerous call in the running kernel,+and it can be loaded and removed without a reboot.++The same capability is a risk. If root can load BPF, an attacker who gains+root can load BPF too: to hide, to read kernel memory through tracing, or+to detach the mitigation. A mechanism that patches the kernel at runtime+has to keep everyone else from doing the same. On a shirudo target, root+without the operator's signing key must not be able to run BPF that the+operator did not ship.++What shirudo does+-----------------++- It locks down ``bpf()``. After ``shirudo init``, the kernel admits a+ program load from userspace only for a signed loader whose signature it+ verifies against the certificates in its sealed ``.bpf`` keyring. BPF LSM+ programs refuse the commands that detach or replace loaded programs, and+ keep every process without shirudo's runtime authority from opening+ their links and maps.+- It delivers upatches. The operator publishes signed packages to an OCI+ registry, and targets pull them on a systemd timer, by default about once+ a minute. A single ``.upatch`` file copied to the target by any other+ means loads through the same signature check.+- It measures. Every load, unload, upatch tree operation and key+ revocation extends a per-boot register in the TPM. The operator verifies+ TPM-signed evidence offline against the artifacts it shipped.+- It protects its own state. The binary and its settings come from+ dm-verity images, its writable state under ``/var/lib/shirudo`` carries+ labels that BPF LSM programs enforce, and its pins live in a private BPF+ file system whose unlink, rename and unmount the same programs refuse.+- It exports what upatches observe. When an endpoint is configured, map+ contents and status keepalives go to an OpenTelemetry collector over+ OTLP.++What shirudo does not do+------------------------++- It does not judge what an upatch does. The signature proves who built+ the code and that it was not changed. The kernel's BPF verifier still+ checks memory safety, but whether the program is a correct mitigation is+ the author's responsibility.+- It does not replace kernel updates. An upatch covers the time until the+ machine runs a fixed kernel.+- It has no daemon, no listening socket, no push channel, no SSH+ integration and no fleet inventory. Every target operation is a one-shot+ command, run by hand or by a timer.+- It does not defend against a compromised kernel, BPF verifier, TPM or+ hardware, and it does not harden the kernel. The kernel and shirudo form+ the target's trusted computing base.+- It does not retain logs. Its commands log through ``syslog(3)``, and+ retention is the job of journald and the systems behind it.+- It protects a target only from the moment ``shirudo init`` has attached+ its enforcement. Production targets run ``init`` from the initrd, before+ other workloads start. If ``init`` fails there, the boot continues+ without enforcement, and only ``shirudo status`` and attestation show+ it.++The :doc:`/security/threat-model` states each of these limits with the+mechanism behind it.++Two roles+---------++One binary serves two roles. The operator holds the private ML-DSA-87+signing key, builds and signs upatches, publishes packages and verifies+evidence. The operator-only commands run in a separate helper,+``shirudo-build``, which is not installed on targets. A target holds only+public certificates, enforces the signatures and keeps the measurement in+its TPM. :doc:`/concepts/operator-and-target` explains what each side holds+and why.++A target needs a bpf-next development kernel with the signed BPF loader+interface and the BPF LSM, the kernel patches listed in+:doc:`/internals/kernel-patches`, and a TPM 2.0. The operator host needs+current clang. Both run on x86-64, arm64 and riscv64.+:doc:`/operate/system-requirements` lists the details.++Next steps+----------++- :doc:`how-it-works` follows one upatch from a kernel fix to a measured+ load and back.+- :doc:`quickstart` takes an upatch through its whole life on a test VM.+- :doc:`/security/security-model` summarizes what shirudo protects and+ where each mechanism stops.diff --git a/Documentation/telemetry.rst b/Documentation/telemetry.rstdeleted file mode 100644index 91df42bc..00000000--- a/Documentation/telemetry.rst+++ /dev/null@@ -1,475 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--Telemetry export-================--shirudo pushes what it knows about a target to a collector; nothing-connects in. Two things are exported: snapshots of the maps the loaded-upatches maintain, as OTLP logs and metrics, and a periodic status-keepalive, as an OTLP log. Both leave the target as OTLP/HTTP JSON-documents, POSTed by a one-shot command that a systemd timer runs, so-the target keeps its agentless shape: no exporter daemon, no listening-port, nothing to connect to.--This document describes how a BPF map becomes a record, the decoders-that give a record its shape, the documents on the wire, the transport-and its configuration, and how to land the data in the OpenTelemetry-Collector, ClickHouse, Splunk or a collector of your own.--Persistent ``map_export.*`` settings belong in ``etc/shirudo/shirudo.conf``-inside the signed config image. Activate that config with ``shirudo image-update``; editing the host's copy does not change the effective settings.-Services invoke the runtime interpreter and binary with image libraries.-Bootstrap TPM and trust-path environment overrides are refused; export command-options do not authorize changes to those inputs.--1) The pipeline------------------::-- BPF map (arena, hash, array, per-CPU, ...)- |- | serializer under BPF_PROG_TEST_RUN (serializer-backed maps)- | or a direct read of the pinned map (other map types)- v- 4 KiB pages of serialized records, or the raw entries- |- | signed Lua decoder in LuaJIT, or the automatic classifier- v- OTLP log record or metric- |- | OTLP/HTTP JSON: POST /v1/logs, POST /v1/metrics- v- collector --> ClickHouse, Splunk, a database, a custom sink--Every stage runs inside ``shirudo upatch map``. The command reads the-pins under ``/run/shirudo/bpffs/upatches/<name>/maps/``, uses only-the ``bpf()`` commands the LSM allows from userspace (``OBJ_GET``,-``OBJ_GET_INFO_BY_FD``, ``MAP_LOOKUP_ELEM``, ``MAP_GET_NEXT_KEY``,-``PROG_TEST_RUN``), decodes, and then prints, appends JSON lines to a-file, or exports. Decoders travel inside the signed ``.upatch``; the-exporter is part of the ``shirudo`` binary. A snapshot therefore has-the same provenance as the program that produced it. Reading a serializer-backed map drains-it, exactly as the timer does, because the serializer hands over what-it collected since the previous read; ``upatch map --peek`` asks for-the interval still being collected and leaves it for the exporter.--2) From a map to a record----------------------------Serializer-backed maps. A structure that lives in a BPF arena or-spans several maps (a tree, a ring, a hash of lists) cannot be read-consistently from userspace one element at a time. An upatch that-owns such a structure also ships a serializer: a ``SEC("syscall")``-program named ``shirudo_serialize__<map>`` that walks the structure in-kernel context, with the ordering and locking the structure needs, and-writes fixed-size records into 4096-byte chunks of a reserved output-map. ``upatch map`` runs it under ``BPF_PROG_TEST_RUN`` with a cursor,-repeatedly until the program reports ``done``, and collects the pages.-A serializer is an ordinary program in the signed ``.upatch``; the-attach metadata marks it with role ``1`` and names its target map.--Direct readers. Plain hash, array and per-CPU maps are read with-``MAP_GET_NEXT_KEY`` and ``MAP_LOOKUP_ELEM`` and presented as a list of-entries with hex keys and values.--Decoders. The pages or entries are handed to the Lua decoder the-upatch declared for that map, which returns the record to export. A-map without a decoder goes through the automatic classifier: an-unsigned per-CPU BTF integer scalar map becomes a metric named-``shirudo.<upatch>.<map>``, a monotonic cumulative sum with one-``asInt`` data point per key and the key as the ``shirudo.map.key``-attribute; every other map becomes a log record whose body carries the-entries.--3) Decoders--------------A decoder is a Lua function shipped inside the upatch. The BPF source-declares it in ``.rodata`` with a ``struct shirudo_decoder_manifest``:-a magic and version, ``language`` (``1`` is Lua), ``api_version``,-``input_format`` (``1`` is serializer pages), ``export_signal`` (``1``-log, ``2`` metric), and the fixed-size strings ``upatch``, ``map``,-``source`` (the ``.lua`` path, relative to the BPF source) and-``entrypoint`` (``decode``). At build time ``shirudo-build`` resolves-``source`` and embeds the file in the ``data`` section ahead of the-signature (the decoder trailer in `upatch-spec <upatch-spec.rst>`__), so-a decoder is covered by the same ML-DSA signature as the program whose-data it interprets. A target runs only decoders that arrived this way;-there is no decoder search path and nothing to drop in.--The decoder runs under LuaJIT with the standard library and an-instruction budget, and is loaded as source text alone: LuaJIT verifies-no bytecode it loads, so a bytecode chunk is refused. The archived-artifact it is read from is opened as sealed state, so an entry under-the archive that is not shirudo's own is refused rather than run. Its entry point receives one table::-- input.schema, input.upatch, input.map- input.startTimeUnixNano, input.timeUnixNano- input.data.name, input.data.type, input.data.max_entries,- input.data.n_entries, input.data.key_size, input.data.value_size,- input.data.n_cpus, input.data.truncated- input.data.entries[i].key_hex, .value_hex -- direct reads- input.data.serialized, input.data.serialized_pages,- input.data.serialized_bytes- input.data.pages[i].page_index, .cursor, .next_cursor, .done,- .flags, .chunks, .bytes, .data_hex -- serializer--and a host API for the common case of fixed-size records::-- local slots = shirudo.page_slots(page, slot_size)- slots[1]:u32(0) -- every slot of one page in order, the- slots[2]:u64(16) -- page header first; u8, u16, u32, u64- slots[2]:cstring(96, 32) -- and cstring read at an offset- local records = shirudo.fixed_records(input.data.pages, slot_size)- records[2]:u64(0) -- the older flat view across pages,- -- indexed by page cursor plus slot- shirudo.u64_add(a, b) -- exact arithmetic on the decimal u64- shirudo.u64_sub(a, b) -- strings u64() returns; Lua numbers- shirudo.hex_u64(hex, off) -- lose nanoseconds; little-endian u64- -- at a byte offset of a hex string--``u64()`` and the arithmetic helpers exchange decimal strings because a-Lua number cannot hold a nanosecond timestamp. A serializer stamps the-page header with the boot-time clock at the moment it ran, so a decoder-turns a record's boot-time timestamp ``ts`` into wall clock with-``shirudo.u64_sub(input.timeUnixNano, shirudo.u64_sub(boot_now, ts))``.--Return contract. A log decoder returns a table; it becomes the-``body`` of the log record as an OTLP key-value list, nested tables-becoming nested lists and arrays becoming arrays. A metric decoder-returns a list of OTLP ``Metric`` objects, exactly as they appear in-the ``metrics`` array of a ``scopeMetrics`` entry, so the decoder-decides the name, unit, description, aggregation and data points. An-error raised in the decoder drops that snapshot with a diagnostic; it-never produces a partial record. Strings go out as UTF-8, with U+FFFD-in place of a byte sequence that is not, such as a name the kernel-cut mid-character. The shipped-``upatches/kernel-obs/decoders/watch_stat.lua`` turns a per-CPU-counter pair into one monotonic sum with two labelled points::-- local function metric_point(input, value, outcome)- return {- startTimeUnixNano = input.startTimeUnixNano,- timeUnixNano = input.timeUnixNano,- asInt = value,- attributes = {- {key = "outcome", value = {stringValue = outcome}},- },- }- end-- function decode(input)- local data = input.data- local entry = data.entries and data.entries[1]- if not entry then- error("missing watch counter entry")- end- local stride = math.ceil((data.value_size or 16) / 8) * 8- local checked, matched = "0", "0"- for cpu = 0, (data.n_cpus or 1) - 1 do- local base = cpu * stride- checked = shirudo.u64_add(checked,- shirudo.hex_u64(entry.value_hex, base))- matched = shirudo.u64_add(matched,- shirudo.hex_u64(entry.value_hex, base + 8))- end- return {- {name = "kernel_obs.watch_attempts", unit = "1",- description = "socket-level destination checks against the watch list",- sum = {- aggregationTemporality = 2,- isMonotonic = true,- dataPoints = {- metric_point(input, checked, "checked"),- metric_point(input, matched, "matched"),- },- }},- }- end--The ``kernel-obs`` package carries decoders for its exec, net, listen,-watch, dns, priv and file tables; they are the reference for writing new-ones, the timestamp conversion included.--4) The documents on the wire-------------------------------Every export is an OTLP/HTTP JSON document (``application/json``,-gzip-compressed when enabled). The resource carries-``service.name = shirudo`` and ``host.name``; the instrumentation scope-is ``shirudo.upatch.maps`` with the shirudo version.--Map snapshot log, one ``logRecord`` per map::-- eventName shirudo.bpf.map.snapshot- severityNumber/Text 9 / INFO- body the decoder's table, or the entries- attributes shirudo.upatch.name, shirudo.upatch.location,- shirudo.map.name, shirudo.map.type,- shirudo.map.max_entries, shirudo.map.n_entries,- shirudo.map.n_cpus, shirudo.map.serialized,- shirudo.map.truncated--Map metric, one ``Metric`` per map or per decoder entry under the same-resource and scope.--Keepalive, one log record from ``shirudo status --otel``::-- eventName shirudo.keepalive- severityNumber/Text 9 / INFO status ok- 13 / WARN degraded, init-pending,- reboot-pending- 17 / ERROR lsm-off, tampered- body the status --json document as a key-value- list (schema, status, conditions, tpm,- tamper_attempts, system, ...)- attributes shirudo.status, shirudo.version_id,- shirudo.tamper_attempts (the total of the- refusals the guards counted this boot)--The keepalive is sent only when an endpoint is configured explicitly,-through ``map_export.otel_endpoint`` or the-``OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`` or ``OTEL_EXPORTER_OTLP_ENDPOINT``-variables; it never falls back to localhost. A collector that stops-receiving keepalives from a host, or receives one at ERROR, has the two-signals an operator needs most.--S3 reference. With ``--s3-uri`` (or ``map_export.s3_uri``) the-snapshot itself is uploaded and the log record becomes a pointer::-- eventName shirudo.bpf.map.snapshot.reference- attributes shirudo.map.snapshot.uri, .size_bytes,- .uncompressed_size_bytes, .format,- .content_type, .content_encoding,- plus the map attributes above--The object key is ``<prefix>/<hostname>/<upatch>/<map>/<sha256>.json.gz``-with ``x-amz-meta-shirudo-schema``, ``-upatch`` and ``-map`` metadata,-signed with SigV4 from ``AWS_ACCESS_KEY_ID``, ``AWS_SECRET_ACCESS_KEY``,-``AWS_SESSION_TOKEN``, ``AWS_REGION`` or ``AWS_DEFAULT_REGION``, and-``AWS_CA_BUNDLE``. Large snapshots bypass the collector's record size-limits this way while the collector still learns that they exist.--JSON lines. ``--json`` prints the map listing or decoded records to-stdout. ``--json=<path>`` (or ``map_export.json_path``) appends them-as JSON lines to a file for a log shipper that tails files.--5) Transport---------------Endpoint. ``--otel-endpoint=<base>`` sends logs to ``<base>/v1/logs``-and metrics to ``<base>/v1/metrics``. Without it the standard-variables apply: ``OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`` and-``OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`` are used verbatim,-``OTEL_EXPORTER_OTLP_ENDPOINT`` gets the path appended, and the default-is ``http://localhost:4318``. For every setting below the-signal-specific variable (``_LOGS_`` or ``_METRICS_``) wins over the-generic one. ``OTEL_EXPORTER_OTLP_PROTOCOL`` may be set to-``http/json``; any other value is refused, shirudo speaks nothing else.--Headers. ``OTEL_EXPORTER_OTLP_HEADERS`` (``key=value,key=value``) adds-headers to every request, which is how an ingest token reaches a hosted-collector. ``--tenant-id`` or ``map_export.tenant_id`` sets-``X-Tenant-ID``; a tenant id is 1 to 128 characters of letters, digits,-``.``, ``_`` and ``-``. ``OTEL_EXPORTER_OTLP_COMPRESSION=gzip``-compresses the body.--TLS. Like every libcurl client in shirudo, the exporter speaks TLS 1.3-with a hybrid ML-KEM key exchange only (X25519MLKEM768,-SecP256r1MLKEM768) by default; a collector that offers only classical-groups is refused unless its exact DNS hostname is listed in-``tls.classical_hosts`` in the immutable runtime config. See the BPM-transport notes for the format and scope of that opt-in.-``OTEL_EXPORTER_OTLP_CERTIFICATE``-names a CA bundle; ``OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`` and-``OTEL_EXPORTER_OTLP_CLIENT_KEY`` a client certificate for mutual TLS.-Cleartext ``http://`` is allowed only to loopback. ``--otel-insecure``-(``map_export.otel_insecure``) permits cleartext to other hosts and-disables certificate verification for ``https://``, with a warning each-time; it exists for test rigs.--Retries. ``OTEL_EXPORTER_OTLP_TIMEOUT`` (milliseconds, default 10000,-from 1 to 120000) bounds each attempt. A transport error and the responses OTLP calls-retryable, 429, 502, 503 and 504, are retried with exponential backoff-from 250 ms, honouring ``Retry-After`` up to 30 s, for-``--otel-retries`` attempts (``map_export.otel_retries``, default 3,-at most 10). Any other 4xx or 5xx response is not retried. A 200-whose ``partialSuccess`` rejected records is a non-retryable failure,-so a collector that drops records is reported rather than silently-accepted; one that rejected none only carries a warning.--Limits. A record larger than ``map_export.log_record_max_bytes``-(default 1 MiB) and a request larger than ``map_export.otlp_max_bytes``-(default 4 MiB) are refused with a diagnostic, never truncated; the S3-path exists for snapshots that are legitimately larger.--6) Configuration and timers------------------------------``/etc/shirudo/shirudo.conf``::-- map_export.json_path = /var/log/shirudo/maps.ndjson- map_export.otel_endpoint = https://collector.example:4318- map_export.tenant_id = fleet-eu-1- map_export.otel_insecure = false- map_export.otel_retries = 3- map_export.s3_uri = s3://bucket/prefix- map_export.log_record_max_bytes = 1048576- map_export.otlp_max_bytes = 4194304--Command-line options override the file; ``shirudo config`` prints the-effective values. Headers, TLS material and credentials are-environment, not configuration: the timers read-``/etc/shirudo/map-export.env`` for the ``OTEL_EXPORTER_OTLP_*`` and-``AWS_*`` variables.--``shirudo-map-export.timer`` runs ``shirudo upatch map --all`` five-seconds after the previous run finished, and that command exports to-whatever ``map_export`` names: JSON lines, OTLP, S3, any combination,-or nothing. ``shirudo-keepalive.timer`` runs ``shirudo status --otel---include-system`` on the same cadence. Both are-ordinary one-shot services; disable a timer to stop an export, and-nothing else changes.--7) Integrating with collectors---------------------------------The OpenTelemetry Collector. shirudo speaks standard OTLP/HTTP, so the-``otlp`` receiver accepts it unchanged and any exporter can follow. A-pipeline that lands logs and metrics in ClickHouse and Splunk::-- receivers:- otlp:- protocols:- http:- endpoint: 0.0.0.0:4318- tls:- cert_file: /etc/otelcol/collector.crt- key_file: /etc/otelcol/collector.key- min_version: "1.3"-- processors:- batch:-- exporters:- clickhouse:- endpoint: tcp://clickhouse:9000- database: shirudo- logs_table_name: upatch_logs- metrics_table_name: upatch_metrics- splunk_hec:- token: "${env:SPLUNK_HEC_TOKEN}"- endpoint: https://splunk.example:8088/services/collector- source: shirudo- sourcetype: otel- index: shirudo-- service:- pipelines:- logs:- receivers: [otlp]- processors: [batch]- exporters: [clickhouse, splunk_hec]- metrics:- receivers: [otlp]- processors: [batch]- exporters: [clickhouse, splunk_hec]--Go's TLS stack, which the collector uses, enables X25519MLKEM768 by-default since Go 1.24. If using the classical-host setting, the-collector hostname must be listed explicitly in the runtime image; the-transport then lacks-post-quantum confidentiality. Otherwise, terminate TLS in a proxy that-offers a hybrid group if a build cannot.--ClickHouse. The ``clickhouse`` exporter stores each log record with-its ``Body``, ``SeverityNumber``, ``ResourceAttributes`` and-``LogAttributes`` maps, so the ``shirudo.*`` attributes are map keys::-- -- hosts whose last keepalive is older than a minute- SELECT ResourceAttributes['host.name'] AS host, max(Timestamp) AS last- FROM shirudo.upatch_logs- WHERE LogAttributes['shirudo.status'] != ''- GROUP BY host HAVING last < now() - INTERVAL 60 SECOND;-- -- hosts that are not ok right now- SELECT ResourceAttributes['host.name'], LogAttributes['shirudo.status'],- LogAttributes['shirudo.version_id']- FROM shirudo.upatch_logs- WHERE SeverityNumber >= 13 AND Timestamp > now() - INTERVAL 5 MINUTE;-- -- hosts where a guard refused something this boot- SELECT ResourceAttributes['host.name'] AS host,- max(toInt64(LogAttributes['shirudo.tamper_attempts'])) AS refused- FROM shirudo.upatch_logs- WHERE LogAttributes['shirudo.tamper_attempts'] != ''- GROUP BY host HAVING refused > 0;-- -- the latest snapshot of one map on one host- SELECT Body FROM shirudo.upatch_logs- WHERE LogAttributes['shirudo.upatch.name'] = 'kernel-obs'- AND LogAttributes['shirudo.map.name'] = 'exec'- AND ResourceAttributes['host.name'] = 'node-17'- ORDER BY Timestamp DESC LIMIT 1;--Metrics land in the exporter's sum and gauge tables, keyed by the-metric name (``shirudo.<upatch>.<map>`` or the decoder's) and its-attributes.--Splunk. The ``splunk_hec`` exporter turns each log record into an HEC-event with the body as the event and the attributes as fields, so-``shirudo.status``, ``shirudo.upatch.name`` and ``shirudo.map.name``-are searchable, ``index=shirudo shirudo.status!=ok`` lists the-unhealthy hosts and ``index=shirudo shirudo.tamper_attempts>0`` the-hosts where a guard refused something. Metrics go to a metrics index through the same-exporter. An HEC endpoint can also be the direct target of a custom-sink as described below.--A collector of your own. shirudo needs nothing collector-specific.-Any HTTPS server that accepts two requests is a valid destination::-- POST <base>/v1/logs Content-Type: application/json- POST <base>/v1/metrics Content-Encoding: gzip (when enabled)- X-Tenant-ID: <tenant> (when set)- plus OTEL_EXPORTER_OTLP_HEADERS-- 200 {} accepted- 200 {"partialSuccess": {...}} rejected, not retried, when- it rejected records- 429, 502, 503, 504, timeout, retried with backoff;- connection error Retry-After honoured- other 4xx and 5xx rejected, not retried--The body is the OTLP ``ExportLogsServiceRequest`` or-``ExportMetricsServiceRequest`` in its JSON encoding:-``resourceLogs[].scopeLogs[].logRecords[]`` and-``resourceMetrics[].scopeMetrics[].metrics[]``. A sink is a few dozen-lines in any language; ``testing/helper/otel-mock.py`` in the tree is one,-used by the exporter tests, and shows the three response modes above.-Point shirudo at it with ``--otel-endpoint`` and watch the documents-arrive.--Without a network. ``map_export.json_path`` appends JSON lines that-any file-tailing shipper picks up (the collector's ``filelog``-receiver, Vector, Fluent Bit, a Splunk forwarder), and ``shirudo status---json`` and ``--report=<path>`` produce files the same way.-Air-gapped fleets use this path.--8) Checking a pipeline-------------------------On a target::-- sudo shirudo upatch map --all # decoded, to stdout- sudo shirudo upatch map --all --json # decoded NDJSON- sudo shirudo upatch map --all --json=/tmp/maps.ndjson # JSON lines- sudo shirudo upatch map --all --otel --otel-endpoint=http://127.0.0.1:4318- sudo shirudo status --otel --include-system--Every refusal is logged to syslog under the ``shirudo`` tag with the-HTTP status or curl error, the attempt count and the endpoint. On the-collector side, the ``debug`` exporter prints what arrived.diff --git a/Documentation/threat-model.rst b/Documentation/threat-model.rstdeleted file mode 100644index 9d49b791..00000000--- a/Documentation/threat-model.rst+++ /dev/null@@ -1,673 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--shirudo threat model-====================--This is the security design document. It says what shirudo protects,-against whom, by which mechanism, and where each mechanism stops. Read-it before changing anything on a security-relevant path: the-`architecture <architecture.rst>`__ says how the pieces fit, this-document says why they must. A change that keeps the code's shape but-breaks one of the properties below is worse than no change, because it-ships a false sense of safety to fleets and devices that are hard to-patch.--1) Scope and assets----------------------shirudo protects a Linux target after ``shirudo init`` has attached its-enforcement programs. The property it provides: from that point on,-the BPF programs running in the target kernel are exactly the set the-holder of the signing key authorised, every change to that set is-recorded in a TPM measurement an operator can check from one value, and-labelled target files receive the access checks described below.-Writable-state protection has the directory-entry and existing-reference-limits recorded in T11.--The assets, in the order an attacker would want them:--- the private signing key on the operator;-- the certificate on the target and the sealed bpf keyring it is- enrolled in;-- the enforcement links and the identity map pinned in the private- bpffs: losing them means losing enforcement;-- the loaded upatches, their pins and the payload xattrs that bind a- pin to its artifact;-- the TPM measurement register and the eventlog that explains it;-- the installed artifacts and the configuration under- ``/var/lib/shirudo`` and ``/etc/shirudo``;-- the status, reports and exported telemetry an operator acts on.--2) Trust boundaries----------------------The target trusted computing base is the kernel, with the BPF LSM-active and the signed-BPF verification path compiled in, plus shirudo:-the binary, its two embedded enforcement programs, the certificate in-the keyring, and the initrd that runs ``init`` before anything else,-which the measured boot records in PCRs 9 and 11. Every other process-on the target, including root with every capability, is outside the-TCB and constrained by it.--Every target boots with authenticated runtime and config images. The initrd-initializes enforcement before untrusted workloads, enrolls its trust anchors-and seals the kernel BPF and dm-verity keyrings. Missing image settings or a-sealed empty BPF keyring stop initialization. There is no user-keyring staging-or executable-inode fallback.--Authenticated images are part of this boundary. The UKI supplies the runtime root hash, and the runtime image-supplies the config verification certificate, initial BPF anchors and TPM-settings. The config signature authorizes that image's contents; it does not-replace BPF signatures or vouch requirements. Every executable on the runtime-image has equal authority eligibility. The operator must keep general shells-and debuggers off that image unless their authority is intended. Host root-content and executable paths do not authenticate a caller.--The operator TCB is the operator host, clang/LLVM, libbpf and the-signing key. Image generation and offline verification additionally use-the standard ``veritysetup`` executable; generating an ext4 filesystem-uses ``mkfs.ext4``. These are operator tools, not target dependencies.-An upatch does what its author wrote; shirudo guarantees provenance,-not correctness.--Outside both: the OCI registry, the network, the TLS certificates of-registries and collectors, and whatever remote access an administrator-uses. A registry can withhold or replay signed content; it cannot-forge any, because every package index, tree publication and loader is-authenticated on the target by its ML-DSA signature.--The kernel is trusted. shirudo does not defend against a compromised-kernel, verifier, TPM or hardware, and it does not harden the kernel.--3) Adversaries-----------------A. Unprivileged local code. Constrained by the kernel already;- shirudo adds nothing it needs.--B. Root on the target without the signing key. The main adversary: a- compromised administrator account, a container escape, a- persistence implant. It can issue any syscall, write any file,- ptrace whatever the kernel lets it, and load modules where that is- allowed. shirudo must keep this adversary from loading BPF, from- detaching or replacing shirudo's BPF, from altering shirudo's state- unnoticed, and from making a tampered target look healthy.--C. A network adversary between registry and target, or a hostile- registry. Can observe, drop, delay and replay.--D. An adversary holding the operator's signing key. Out of scope:- that adversary is the operator.--4) Threats addressed-----------------------T1 Loading unsigned BPF- ``lsm/bpf`` admits a userspace ``BPF_PROG_LOAD`` only for a- ``BPF_PROG_TYPE_SYSCALL`` program that carries a signature. The- kernel verifies that signature against the sealed bpf keyring- named as ``attr.keyring_id = KEY_SPEC_BPF_KEYRING`` before the verifier- runs. ``lsm/bpf_prog_load`` requires ``BPF_SIG_VERIFIED`` from that kernel- keyring. Userspace map creation requires task authority committed after- successful exec from the runtime device; the authenticated bootstrap- task has temporary authority during initialization. Signed loader map- creation runs in kernel context. The payload is hash-locked to the loader by- ``excl_prog_hash``. Root without the key gets ``-EACCES`` or- ``-ENOKEY``; a certificate planted in any other keyring is ignored,- and a foreign-signed artifact fails with ``ENOKEY``.--T2 Detaching or replacing enforcement- ``lsm/bpf`` denies ``LINK_DETACH``, ``LINK_UPDATE``,- ``PROG_ATTACH``, ``PROG_DETACH`` and ``BTF_LOAD`` from userspace,- and leaves ``LINK_CREATE``, ``RAW_TRACEPOINT_OPEN`` and ``OBJ_PIN``- to a task authorized by successful runtime exec. The one attach that- never passes through ``bpf()``, ``PERF_EVENT_IOC_SET_BPF`` on a perf- event, which would bind a kprobe program reached by id to a probe of- the caller's own, is kept to the same task by ``file_ioctl`` and- ``file_ioctl_compat``. Root cannot re-attach a vetted program- at a site its signer never meant it for, nor pin objects of its own,- nor make a directory or a link in the private bpffs, which bpffs- would otherwise let it: a symbolic link in place of a pin directory- would send the next load's pins into a bpffs of root's own, and a- hard link to a pin would keep a link alive past its unlink- (``inode_mkdir``, ``inode_symlink``, ``inode_link``).- The site a load attaches at is partly the caller's to arrange, and- root runs ``shirudo upatch load``: a cgroup_skb program under a- cgroup namespace root or a bind mount of a subtree, a netfilter- program in a network namespace of the caller's own and a kprobe- opened through a sysfs that names another PMU would each be- measured as loaded while guarding nothing or the wrong thing, so- the load compares the link the kernel reports with the attach- metadata before pinning it and refuses ``attach_scope_mismatch``.- The links are kept alive by pins in the private bpffs;- ``inode_unlink`` and ``inode_rename`` there require that authority.- The VFS unlinks a rename's victim without ``inode_unlink``, so both- hooks are needed. ``sb_umount``, ``move_mount``, ``sb_mount`` and- ``sb_remount`` deny direct operations against that superblock, and- ``sb_umount`` refuses an unmount that would take the bpffs mount- init made with it, by subtree or by propagation. Legacy mount moves- remain a gap, described in residual risk 3. Infrastructure maps are- frozen at creation, so even with the LSM gone userspace could not- rewrite the identity map. ``lsm/bpf_map`` denies writable map fds- to every process except shirudo; map updates and freezes have the- same authority check. Userspace ``BPF_PROG_TEST_RUN`` requires that- authority too; 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.--T3 Tampering with shirudo's files and process- Initialization labels existing files under ``/var/lib/shirudo`` with- ``security.bpf.shirudo``. For labelled targets, the seal checks write- open, unlink, both ends of rename, attribute and xattr changes.- The trusted task mark authorizes the caller.- Only an authorized caller may set the exact label, including on an- unlabelled inode. A copied label marks a target, not caller authority.- Any label size or read error requires authority except ``ENODATA``,- ``EOPNOTSUPP``, ``EACCES`` and ``EPERM``; the permission exceptions- preserve operations on files the caller cannot read. Scratch allocation- failure also requires authority.- New inodes inherit their parent's label in the creation transaction- when the parent has a cached seal mark, and a marked directory takes- new entries from shirudo alone: ``inode_create``, ``inode_mkdir``,- ``inode_symlink``, ``inode_mknod``, ``inode_link`` and a rename into- it require the caller's authority, so root brings in neither an- inode with contents nor a link for shirudo to follow. Shirudo's- writers hold the parent directory open to populate and retain that- mark, open nothing in sealed state through a symbolic link, and take- no entry without the label for shirudo's own: ``init`` labels the- tree on the run that brings enforcement up and afterwards ignores a- foreign entry rather than labelling, following, restoring or- failing on it, and refuses a state root without the label once- enforcement is live, since root could bind a tree of its own over- the path in a mount namespace and have it labelled. An overlay- root mounts over sealed state in a mount namespace of its own- copies a lower inode up into root's upper directory before the- first write reaches it, as the writer, so the copy carried the- label and a write shirudo made through it landed in root's- directory: the seal refuses the copy-up of a marked inode- (``SealCopyUp``) and such a write fails instead. Directory- eviction remains subject to residual risk 15; existing writable- references are not revoked.- The authority the seal grants shirudo is not root's to aim: a path- root names for shirudo to write, a report, an export, evidence or- a download, is opened as output, never a labelled inode, never- created under a labelled directory and never through a symbolic- link, and a registry download goes into the descriptor shirudo- opened rather than a name reopened later. What the verified- runtime and config images hold, settings, keys, registries and- labels, is read from the descriptor of the verified root, never by- a path: ``/proc/<pid>/fd`` is a directory root can mount over- before the exec that grants the mark, and a command whose- configuration came through such a path took root's settings for the- image's on the test target.- Ptrace and perf allocation checks deny against tasks already marked- when those hooks run. Concurrent perf attachment and exec remain a- separate, untested `race investigation <https://github.com/shirudo-dev/shirudo/issues/11>`__.- Runtime executables reject traced callers and run in- secure-exec mode, so the loader ignores unsafe environment variables.- The process drops dumpability, forbids new privileges and locks- all current and future process mappings against swapping before command- dispatch, refusing startup if locking fails. The bpf keyring is sealed with- ``KEYCTL_RESTRICT_KEYRING`` so no key can be linked into it for the- rest of the boot, ``lsm/key_permission`` leaves writing, unlinking,- revoking, invalidating and re-permissioning it and the keys it- holds to tasks with runtime authority. Once sealed it must hold exactly- the trusted certificates: init refuses a keyring holding any other link,- including a nested keyring the kernel's signature search would enter or- a key it cannot describe, and one restricted by another task. The kernel refuses caller-supplied- keyrings for signature verification. The BPF ring serial and enrolled key- serials are frozen into the pinned identity map and checked by later loads.--T4 Substituting artifacts- The signature covers the loader instructions and data, so the kernel- refuses a modified loader. The name an artifact loads under, the- sites its programs attach at and the target an unload directive- names and the payload it expects there ride in signed sections of- the data, so the kernel refuses an edited one and the target- refuses a header that disagrees with them; a load takes its attach- sites from nowhere else. An unload directive is itself a signed- loader and goes through the same ``BPF_PROG_LOAD``. Before- detaching, shirudo compares the live pin's payload xattr, which only- shirudo can write, against the directive's signed expected payload,- and refuses ``payload_mismatch`` on disagreement or when the xattr- is unreadable, so a directive detaches the upatch its signer made- it for and no other.--T5 Silent state change- Every init, load, unload and tree operation extends this boot's- measurement register with a domain-separated digest and appends- the event to the eventlog. The register is an NV extend index- that clears at TPM reset and is written only under its policy: the- first write of a boot needs PCRs 9 and 11 to hold the values the- policy was computed from, which ``init`` performs from the initrd- before ``leave-initrd`` moves PCR 11, and ``init`` extends PCR 9- with the index name right after that write, so nothing that runs- later can bind, an index undefined and recreated at runtime cannot- be written again, and one recreated under another policy has a name- the eventlog does not know. A load whose archive copy or- whose extension fails is undone, pins and archive, and reports the- failure rather than running unmeasured; an unload or purge is measured before it- detaches, so a process stopped between the two, or a TPM made- unreachable for the moment, leaves a register that claims more- than happened and never a detach it does not know; a re-run of- ``init`` restores nothing once this boot's init event is on- record, refuses ``tampered`` for an archived artifact that carries- the label but is not loaded, and ignores one without the label,- which someone else brought in and nothing would measure. An eventlog- that would overflow refuses ``eventlog_full`` before anything- happens. Every state-changing command reads the register first and- refuses ``tampered`` when ``--expect-chain`` disagrees or the index- is not the one ``init`` recorded, which also serialises concurrent- operators. A measuring command holds a lock beside the eventlog from- its extend to its append, so the register and the log advance in one- order even where the lock on whole commands is not taken: ``init``- adopts the initrd's record without it, and two adopters both found- the record missing and appended it twice. ``shirudo status`` replays this boot's records and flags- a register it cannot explain. There is no unmeasured mode: a target- without a TPM 2.0 does not initialise. Root can replace the TPM- device path in its own mount namespace. Shirudo compares the- attestation key Name returned by that device with the one frozen at- init. This rejects a different Name but cannot authenticate the- device by itself: a fake transport can replay the public Name.- A remote verifier requires evidence signed by the pinned TPM key;- an emulator alone cannot produce that signature. An init run from- the initrd- leaves its record under ``/run``, labelled, until the root's run- appends it; a record forged or altered there fails the replay like- any other. The init record carries- the TPM's reset count: ``init`` binds one register per reset,- refuses ``tampered`` when the one it recorded is gone, and- ``status`` and ``attest verify`` reject a boot with two init- records for one reset, so the history a register holds cannot be- restarted by rebinding it.-- Both policy branches require a signature over the exact- ``TPM2_NV_Extend`` command from a TPM-held boot writer. Its private- key never leaves the TPM, but the input used to recreate it is not- secret. Root may recreate the writer and obtain a signature. A- signature alone cannot alter the register: the TPM must receive an- ``NV_Extend`` for Shirudo's index.-- The companion kernel passes copied command bytes and their declared- length to ``tpm_command`` before submission. Shirudo's BPF program- compares the ``NV_Extend`` index with the selected index frozen at- init, and refuses that command unless the caller has the committed- runtime task mark. It checks both TPM device nodes, including- inherited descriptors. Other signing, extensions to other NV- indices, and systemd's PCR extension remain available. Under the- process-integrity assumptions below, root cannot append an- expected positive event to Shirudo's register without doing the- operation, even with a fabricated exported eventlog.- `The TPM design <tpm.rst#write-policy>`__ gives the command checks.-- The NV Name commits to the writer's public key, not proof of TPM- custody. Owner authorization may be configured for primary- creation, but it is not a substitute for the LSM index check.- Kernel memory disclosure alone does not reveal the writer private- key. Injected code in an authorized task can still extend the- register. Kernel code execution and direct TPM access that bypasses- the kernel driver remain trusted-kernel failures. RSA- authorization is classical. Existing process and executable- integrity assumptions, including residual risks 2 and 5, still- apply.--T6 The boot window- Enforcement is BPF and does not survive a reboot by itself.- ``shirudo-initrd.service`` runs ``init`` from the initrd, after the- ``enter-initrd`` phase is measured and before the switch to the- root file system, where it enrols the initrd's measured copy of the- certificate in the still open bpf keyring and seals it, attaches- the LSM with its pins under ``/run``, which systemd carries across- the switch, re-applies the installed set all or nothing, binds the- register and extends it by exactly one event an operator predicts- from the certificate and the set. ``shirudo.service`` then finishes- from the root file system: labels and the eventlog record. Until- the initrd run has happened the target is unprotected; see residual- risk 7. A kexec would open that window again without closing this- boot: it hands the machine to a kernel and an initrd of root's- choosing with the TPM as it is, PCRs 9 and 11 at this boot's values- and the register with this boot's history, so the evidence of this- boot would vouch for whatever ran after. ``kernel_load_data`` and- ``kernel_read_file`` refuse a kexec image or initramfs to every- task, by either system call (``Kexec``).--T7 The delivery path- The registry index is a detached CMS signature by the operator's- key, checked against the certificate registered with the repository;- a package installed from a repository is checked against the digests- in that signed index; a tree publication is signed, carries- per-operation digests and sequence continuity, and a ``delete`` is- accepted only for an id loaded from the same tree. TLS is 1.3 with- hybrid ML-KEM by default. ``tls.classical_hosts`` in operator or- immutable target runtime config can opt exact HTTPS DNS hosts into- classical key exchange; for those hosts,- transport confidentiality is not post-quantum. Certificate checks- and signed artifact verification remain in force, but a registry can- still withhold or replay signed data.--T8 Quantum-capable adversaries against the trust anchor- Signing is ML-DSA-87 (FIPS 204) only: ``genkey`` makes nothing else,- the builder refuses a classical key, and the pre-flight refuses a- classical certificate, so a fleet cannot drift back by- misconfiguration. Digests are SHA-256 and SHA-512, which stay well- above a 128-bit margin against Grover-style search. Long-lived- embedded fleets are the reason: a forgeable signature would let a- future adversary install BPF on every device that still trusts the- old certificate.--T9 A target lying about its state- ``shirudo status`` is the target's own account and proves nothing- by itself. ``shirudo attest`` makes the TPM speak: a quote over- the firmware, boot loader, kernel, initrd and systemd PCRs and a- certification of the register, both signed by an attestation key- the operator pinned by name and carrying the operator's nonce. A- challenge the operator made under the target's endorsement key- (``shirudo attest challenge``) and the target activated while- attesting proves that the attestation key sits in the TPM whose- endorsement key and certificate the evidence carries.- ``shirudo attest verify`` ties the certified index to the recorded- PCR binding, replays the eventlog to the certified value and- compares it with the value predicted from the certificate and the- installed artifacts, so a substituted binary, a recreated index or- an unexpected set is a failed check, not a healthy report. Which- firmware, kernel and initrd values are acceptable is the platform- owner's policy; ``--expect-pcr`` pins them and the logs in the- evidence explain them.--T10 An attempt that leaves no trace- The named guard points count their refusals (a- load that is no signed loader, one without a signature, one whose- signature was verified against the wrong kind of keyring or the- wrong keyring, a writable map descriptor, a rename of a pin, an- unmount of the bpffs, a write to a sealed file, a ptrace of a- shirudo task, a program bound to a perf event, and so on), in a- map ``init`` pins and freezes, so- that no task, shirudo included, can reset it from userspace while- the hooks still add to it. ``shirudo status`` lists the counters- that are not zero with what each means, ``status --json`` carries- them all, and the keepalive takes them to the collector with the- total as the ``shirudo.tamper_attempts`` attribute, so an attempt- is seen where it was made and not only where it failed. A counter- is evidence of an attempt, not of a compromise: the refusal is what- moved it. Image-only device, parent-mount and process refusals do not- yet have counters. An earlier image guard may refuse an operation- before it reaches a shared counter; zero does not mean no attempts.---T11 Image-mode config and executable substitution- dm-verity checks the runtime and config backing blocks. Runtime- acceptance requires the exact root authenticated by the UKI. Config- roots carry a detached ML-DSA signature over their 64 lowercase ASCII- hex bytes, verified by the kernel's dm-verity trust path, including- built-in trusted keys. The initrd enrolls its config certificate and- seals the dedicated ``.dm-verity`` keyring, which must then hold exactly- that certificate, and ``lsm/key_permission`` guards the keyring and its- key as it guards the bpf keyring. A signed config never grants- runtime executable authority. Shirudo validates the standard superblock,- fixed format and exact backing-file sizes, creates or validates a strict- read-only mapping and reads every data block before parsing contents or- measuring activation. Reused mappings undergo the same read. A signature- alone does not authenticate backing bytes: corruption or incomplete reads- refuse preparation. The target neither reconstructs the hash tree nor- invokes ``veritysetup``. Shirudo observes the mapping- metadata exposed by existing upstream hooks. The native ioctl hook restricts DM-control mutations to trusted- image tasks, including through old or inherited FDs; this restriction- applies to unrelated DM devices too. Config device classification also- requires the root expected by the trusted task creating that mapping.- Image mode requires 32-bit compatibility disabled in the kernel; the- device-mapper and perf event ioctl checks hook the native and the- compat path alike.- Enforcement uses existing LSM hooks; direct access to the dm-verity- keyring requires the upstream keyring-ID API. The mount hooks do not- cover every mount attribute change or- unmount of a parent mount above the image mounts. A- candidate config cannot supply bootstrap keys or TPM settings, and config symlinks and special- files are refused. Repository certificate paths resolve inside the held- config root. Complete settings validation precedes activation measurement;- local key and repository mutations cannot override that signed config.-- Successful exec commits task authority; fork inherits it, failed exec- preserves it and successful outside-image exec clears it. Memory checks- remain necessary because dm-verity does not protect anonymous memory- or permit untrusted executable libraries. Writable state retains its- seal, enforced using this task authority. Initial sealing occurs in- the authenticated initrd before hostile tasks. New inodes inherit a- cached parent label during creation, subject to residual risk 15.- The seal does not exclude every foreign directory entry or revoke- existing writable descriptors or mappings. The historical- `directory-entry investigation <https://github.com/shirudo-dev/shirudo/issues/13>`__- describes the earlier baseline; the current cached-parent behavior is- described in T3 and residual risk 15.--T12 Interrupted image activation- The candidate and pending selection are durable before PCR extension.- Validation failures before that point leave the active config usable.- An interruption after it, including an ambiguous TPM response, requires- manual reboot. The node keeps running; Shirudo does not initiate that- reboot. Further state changes and config attestation refuse; no same-boot- recovery or extension retry is attempted. ``status`` still runs and- reports the activation as ``reboot-pending``; it uses the pending- config's export settings only when that config is the one mounted,- since the record vouches for no other. Trusted startup re-verifies the- selected image, reads its entire verified mapping, emits a fresh BOOT- event and applies revocations before restoring upatches. Completion is- recorded only after startup succeeds. Missing or invalid selected images- fail initialization rather than silently choosing an older config.--5) Residual risks--------------------Each of these is known, documented and bounded; none is silent.--1. The detach runs in userspace: the kernel's ``bpf_sys_bpf()`` cannot- detach or unlink. The directive's target name and expected payload- are signed, so root cannot repoint a directive at another upatch;- what root keeps is the moment, since every directive the operator- published, in a package beside its load, is root's to apply at any- time, and the register records each application. An in-kernel- detach would make the whole lifecycle signed BPF.--2. ``CAP_SYS_RESOURCE`` can rewrite ``mm->exe_file``. The task mark is- independent of that field, and ``task_prctl`` denies those operations to- untrusted callers. Successful runtime exec grants authority; failed exec- preserves the old mark and outside-image exec clears it. Runtime programs- run with secure-exec, reject tracing and existing seccomp, and cannot map- executable host or anonymous pages. Their command interface remains the- authorization boundary. The authenticated initrd bootstrap binary and- trusted runtime process memory remain in the TCB.--3. The pins hold the enforcement links through the bpffs superblock,- which goes with its last mount. The kernel calls ``sb_umount`` for- the requested mount alone, so a lazy unmount of a mount above- ``/run/shirudo/bpffs``, ``umount -l /run`` say, took the bpffs with- it, and so did one of a copy of ``/run`` in a mount namespace whose- mounts still propagated to init's, since systemd makes the whole- tree shared again after the switch to the root file system. The- guard now walks what an unmount would take, the subtree and what- propagation carries to peers and slaves, from the bpffs mount init- recorded in its own namespace, and refuses one that reaches it- (``BpffsUmountAbove``); a private copy in a namespace of its own is- any process's to drop. The walk runs without the namespace lock and- within fixed bounds, and refuses a tree it cannot finish, so an- unmount of a very large subtree is refused rather than taken for- safe. The pins still depend on the mount tree;- `issue 22 <https://github.com/shirudo-dev/shirudo/issues/22>`__- tracks keeping them alive without it. Mounting over- ``/run/shirudo`` only hides the pins; it does not release them.- Enforcement continues, but state-changing commands refuse- ``lsm_detached`` while their pins are hidden.-- Legacy ``mount(MS_MOVE)`` bypasses the source check used by- ``move_mount``. Runtime-image relocation succeeded in an isolated- VM namespace; the corresponding baseline bpffs gap is source-derived.- Relocation alone preserves device identity and does not detach pins- or grant authority to host files. The separate `mount-move- investigation <https://github.com/shirudo-dev/shirudo/issues/12>`__ records the evidence.--4. Config PCR writers are not yet bound to completed Shirudo- operations. A caller with direct TPM-command access can append to the- config PCR. Garbage makes replay fail and- can deny service. A public digest of a valid operation can instead- record a claim that the operation happened when it did not. A fresh- nonce, a genuine TPM quote and replay of an externally supplied log do- not prove who appended the digest or that the operation completed.- The separate measurement-spoofing investigation is not fixed by image- mode. Static PCRs prevent runtime reset, not unauthorized extends.- The upatch NV register has its own extension guard, but owner- undefinition and PCR interference can still deny service. Restricting- config PCR writers and handling operation/measurement ordering remain- separate work; no IMA integration is added.--5. Authenticated boot must verify the expected runtime root. dm-verity- verifies runtime files but still trusts the UKI, kernel and trusted process- memory. ``SHIRUDO_VERSION_ID`` is a skew guard, not authentication.--6. There is no user-keyring staging fallback. Boot without the required- enrollment parameters, authenticated settings or valid images fails- initialization. A failed init does not create a protected target.--7. The boot window before ``init`` has run. Run from the initrd it- is the initrd itself, which the measured boot records in PCRs 9 and- 11 and the verifier pins; PCR 11 carries the initrd phases only on- a measured UKI boot, and without them the verifier has PCR 9 alone- to tell the initrd binding from a later one. Started from the root- file system- instead, every process that runs before it is unconstrained, the- certificate is only staged, and the binding carries the- post-``leave-initrd`` PCR 11 value, which ``--expect-bind-pcr=11``- and ``--require-initrd`` reject.--8. Registry withholding and replay. A hostile registry can serve an- old signed index, or none; it cannot serve a forged one. Operators- who need freshness compare the versions ``shirudo bpm list``- reports and the register ``attest`` certifies against what they- published.--9. Classical pieces outside the boundary: WebPKI server certificates- on registries and collectors (they authenticate the transport, not- the artifacts); transport confidentiality for any host opted into- ``tls.classical_hosts``; and the attestation key, which is- ECDSA P-256 because TPMs sign with nothing post-quantum today. For- an opted-in host, recorded traffic may be exposed to a future- quantum-capable adversary. The evidence is therefore classical- even though the artifacts it describes are not.--10. Endorsement key trust. Credential activation ties the attestation- key to the endorsement key in the evidence, and the endorsement- certificate ties that key to a manufacturer. ``challenge`` makes- no challenge unless the certificate chains to the issuers given- with ``--ek-ca``, the key is pinned with ``--ek-name`` from an- inventory or a platform's API, or the operator waives the check- with ``--trust-presented-ek``, which proves only that the same- party answers each time; a TPM without a certificate, as virtual- TPMs usually are, needs one of the latter two. Which issuers to- trust is the operator's decision.--11. The anchor shares PCR 9 with the initrd measurements and with- systemd's ``nvpcr-init`` events and their separator, so ``attest- verify`` proves the anchor exactly only when nothing is measured- into PCR 9 after ``init``, which holds when it runs after- ``systemd-pcrnvdone.service``; otherwise it says so and leaves the- replay of the systemd measurement log, which the evidence carries,- to the verifier's tooling. ``--strict-anchor`` turns the note into- a failure.--12. A root process that runs before ``init`` in the same boot phase- can bind and write the register first, and a record it forges- before the eventlog is sealed is indistinguishable from ``init``'s.- From the initrd that phase is the initrd itself, measured and- pinned; from the root file system it is the window of residual risk- 7, and the binding then carries a PCR 11 value the verifier can- reject.--13. Revocation reaches a target only when its signed config is delivered- and activated. A node that has not received it can still verify BPF signed- by the old key. The config PCR records activation, and revoked signers'- upatches receive unload events in the NV register. There is no local- ``keys revoke`` override or push channel.--14. Shirudo accepts an older config when its signature is valid. A- config PCR extension records the selection but does not enforce- freshness. Replaying an older config can restore its older trust and- revocation settings. Rollback prevention is deferred. The config- verification certificate itself can change only with the authenticated- runtime image and a reboot.--15. The label at creation follows a mark the seal keeps on a directory- it has seen since the inode came into memory: one opened, one- relabelled, or one created under a marked parent. shirudo opens a- directory before creating in it and puts the label on afterwards- where the kernel could not. While the mark is absent another process- can create under a labelled directory, or rename or link an inode- with its contents into it, and the entry carries no label: shirudo- opens sealed state without following a symbolic link, refuses an- entry under a labelled directory that lacks the label, and ``init``- ignores it rather than labelling it, so such an entry is inert until- root removes it.--Deferred mitigations-~~~~~~~~~~~~~~~~~~~~--In scope and not yet built: restricting TPM measurement writers and binding-measurements to completed operations (residual risk 4); config rollback-prevention (residual risk 14); registering the register as a systemd-NvPCR, so that its name follows the UKI signing key instead of the PCR-values of each boot and systemd-aware verifiers find it in PCR 9 before-the separator, and measuring the anchor through ``systemd-pcrextend`` so-systemd's measurement log explains it (residual risk 11); signed PCR-policies for the kernel and initrd PCRs so a verifier needs no golden-values; an in-kernel detach so the pin removal is signed BPF rather-than userspace (residual risk 1); and a ``d_instantiate`` hook the BPF-LSM can sleep in, which would mark a directory the moment its dentry is-bound and close the eviction gap (residual risk 15).--6) Out of scope------------------- Compromise of the operator host or the signing key.-- A malicious or buggy kernel, verifier, TPM or hardware. A kernel- that loads an unsigned module hands root the kernel itself; the- kernel's own policy, ``CONFIG_MODULE_SIG_FORCE`` or lockdown in- integrity mode, has to refuse it. shirudo stands in for that policy- only where it leaves a hole it cannot close, kexec of a signed- kernel with an initrd of root's (T6), and ``status- --include-modules`` lists what is loaded for the operator to compare.-- Denial of service: removing the binary, cutting the network, filling- the disk. shirudo fails closed and loud; it does not fail over.-- Correctness or safety of an upatch an authorised signer built.-- Fleet inventory, rollout ordering, retries, scheduling and- cross-target consistency. shirudo reports one machine; aggregation- is the collector's job.-- SSH, remote access and audit retention. Those belong to the- infrastructure the operator already runs.--7) Operational guidance--------------------------Keep the signing key on a host with the controls of a certificate-authority and never on a target. Boot targets with-``bpf.keyring_unsealed=1 dm_verity.keyring_unsealed=1`` and run ``init``-from the authenticated initrd with valid runtime and config images. Check-``--require-initrd`` and ``--expect-bind-pcr=11`` against the UKI's measured-``enter-initrd`` value. Give ``challenge``-the manufacturer's issuers with ``--ek-ca`` wherever the TPM has a-certificate. Treat ``tampered`` as an incident to understand, not a-condition to retry. Verify ``shirudo status`` after-every boot and every load; a target whose register the eventlog cannot-explain is not healthy just because it is still running. Record the-attestation key name when a target is enrolled (``shirudo attest``-once, keep ``ak.name``), and let the fleet's health be ``shirudo attest-verify`` against a fresh nonce and the values ``shirudo attest-predict`` computes from what you installed, not a status the target-wrote about itself. Build-upatches against the target kernel's BTF and read verifier logs from-the structured report. Restrict who can register repositories and who-can run state-changing commands, and drop ``CAP_SYS_RESOURCE`` from-anything that does not need it. Rotate the signing key in the order-the `key-lifecycle <key-lifecycle.rst>`__ guide gives, rebuild the-initrd after every change of binary or certificate, and reboot after-upgrading shirudo; the `operations <operations.rst>`__ guide has the-procedures.diff --git a/Documentation/tpm.rst b/Documentation/tpm.rstdeleted file mode 100644index cfa79581..00000000--- a/Documentation/tpm.rst+++ /dev/null@@ -1,789 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--The TPM: measurement register and attestation-=============================================--shirudo uses the target's TPM 2.0 for two things. A per-boot-measurement register records every change to the BPF state in a form-nobody on the target can rewrite, and on request the TPM signs that-register together with the platform PCRs so an operator can check a-target without believing anything the target says about itself. This-document describes both as implemented, how they relate to systemd's-NvPCRs, which the register is modelled on, and what they do not yet-do. The code is authoritative: ``util/chain.c`` (register and event-digests), ``util/nv_writer.c`` (writer identity),-``util/tpm.c`` (libtss2 calls), ``util/tpm_wire.c`` (policy-digests, names and the TPM wire structures, used by both sides),-``util/eventlog.c``, ``util/attest.c`` and ``builtin-attest.c``.-`threat-model <threat-model.rst>`__ states what the design defends-against; `architecture <architecture.rst>`__ places it in the whole.--A TPM 2.0 is mandatory on a target. There is no unmeasured mode: a-target that cannot bind its register does not initialise, and a load-whose extension fails refuses with ``tpm_error`` rather than succeed-unmeasured. The operator side never touches a TPM.--1) The register------------------The register is an NV index, ``0x01818E00`` by default-(``SHIRUDO_NV_INDEX``), holding one SHA-256 digest. Its attributes-are ``0x0E060048``:--``TPM2_NT_EXTEND``- The index is extended, never overwritten: a write of ``d`` sets- it to ``SHA256(old || d)``, the same operation a PCR performs.--``TPMA_NV_CLEAR_STCLEAR``- The contents and the ``TPMA_NV_WRITTEN`` attribute clear at every- TPM reset, so the register starts from 32 zero bytes at every- boot, like a PCR, and holds this boot's history only.--``TPMA_NV_POLICYWRITE``- The only way to write is a policy session that satisfies the- index's write policy below. Neither owner-write nor auth-write- supplies an alternative write route.--``TPMA_NV_OWNERREAD`` and ``TPMA_NV_AUTHREAD``- Reads and certification use an empty password. Owner-authorized- reads are also supported.--``TPMA_NV_NO_DA`` and ``TPMA_NV_ORDERLY``- Failed authorisations do not count towards dictionary-attack- lockout, and the index is written back to NV memory only at an- orderly shutdown, which spares that memory for an index that- changes with every event and is cleared at reset anyway.--Write policy-~~~~~~~~~~~~--The write policy is ``PolicyOR(written, init)``, followed by-``PolicySigned`` and ``PolicyCommandCode(NV_Extend)``. Its branches:--* ``written`` is ``PolicyNvWritten(YES)``: later writes cannot- initialize a recreated, unwritten index.--* ``init`` is ``PolicyNvWritten(NO)`` followed by ``PolicyPCR`` over- PCRs 9 and 11 at the values they hold when ``init`` binds the- register. It admits the first write of a boot, and only while both- still hold those values. PCR 9 carries the initrd measurements and- takes the anchor; PCR 11 carries systemd's boot phase and moves at- ``leave-initrd``, so a register bound from the initrd can be bound by- nothing that runs after it.--Both branches require an RSA-3072 RSASSA-PKCS1-v1_5 signature with-SHA-256 from this boot's TPM-held NV writer key. The signature-covers the live session's nonempty TPM nonce, a zero expiration,-the SHA-256 command hash and the fixed reference-``shirudo-nv-writer-v1``. The command hash covers ``NV_Extend``, both-handle Names and the marshalled event. The first write uses the-unwritten Name; subsequent writes use the written Name. The TPM-checks that exact command hash when executing the extend. A signature-alone does not change the register. A caller must also submit-``TPM2_NV_Extend`` to Shirudo's index, which the BPF LSM guard restricts.-Public appends would permit fabricated positive events: measuring an-expected load is not proof that the load happened.--Trusted initialization creates an RSA-3072 primary key in the local-TPM's owner hierarchy. It gives ``CreatePrimary`` a random 32-byte-input and freezes that input and the resulting public modulus in the-identity map. The private key never leaves the TPM. The fixed public-template requires ``fixedTPM``, ``fixedParent``,-``sensitiveDataOrigin``, ``userWithAuth`` and ``sign``, with-RSASSA/SHA-256 and exponent 65537. The public area and Name must-match that template and modulus. The initrd freezes this identity-before attaching the TPM command guard. The input is not secret:-another process may recreate the same key and ask the TPM to sign.-Shirudo protects the extension command, not access to the signer.--Each later one-shot invocation recreates the primary from the frozen-input, checks its public area and Name, asks the TPM to sign the-command-bound authorization, and flushes the handle. The owner hierarchy-authorization comes from authenticated ``tpm.owner_auth`` when it is-set. The same input recreates the same key after a TPM reset in the same-host boot. A new host boot chooses a new input. A TPM Clear changes the-owner seed and makes the old identity unusable, so Shirudo fails closed.-No persistent TPM slot or private-key file is needed.--The companion kernel's ``tpm_command`` LSM hook passes a copy of-each userspace TPM command and its declared header length before the-command is sent or queued. It covers writes to ``/dev/tpm0`` and-``/dev/tpmrm0``, including a descriptor opened before enforcement or-inherited by another process. Shirudo's BPF program checks the index-handle in ``TPM2_NV_Extend`` against the selected NV index frozen at-init. It refuses that command to a task without authenticated runtime-authority, including a command too short to identify its index.-The default index is ``SHIRUDO_NV_INDEX``; a build may select another,-and the guard reads the selected value from the frozen identity map.-Extensions to other NV indices, TPM signing, and systemd's PCR-extensions remain available. A signature made with Shirudo's writer-key is therefore not enough to change its register. The guard must-be attached and pinned before untrusted workloads start.--Every executable intentionally added to the verified runtime image gets-the same task authority. Code running in such a task can extend-Shirudo's register, so ``--extra-binary`` adds an authorized writer.-The static target does not load host libraries or OpenSSL provider-configuration, and runtime exec rejects traced callers. A kernel memory-read alone cannot extract the TPM private key. Kernel code execution,-direct hardware access around the TPM driver, and compromise of an-authorized task remain outside this guard. The eventlog's public key-does not by itself prove TPM custody to a remote verifier. RSA-authorization is classical, unlike the operator's ML-DSA-87 artifact-signatures. A live session nonce and exact command hash prevent reuse-of an old authorization for a different extension.--The index's TPM name is the SHA-256 of its public area (handle, name-algorithm, attributes, policy digest, size), prefixed with the-algorithm identifier ``000b``. Because ``TPMA_NV_WRITTEN`` is part of-the attributes, the index has one name before its first write and-another after it; the written name is the one ``init`` records, the-anchor carries and every later comparison uses.--Binding at boot-~~~~~~~~~~~~~~~--``shirudo init`` is meant to run from the initrd, after-``systemd-pcrphase-initrd.service`` has measured ``enter-initrd`` into-PCR 11 and before the switch to the root file system, which is how-``shirudo-initrd.service`` orders itself (the ``initrd`` document);-it binds the register after it has re-applied the installed set, in-this order:--1. Read PCRs 9 and 11; the values are ``pcr_before`` and- ``phase_before``. Read the writer's public key from the frozen- identity map and reconstruct its fixed TPMT_PUBLIC template, with- exponent 65537. Compute both policy branches, the policy digest- and the two NV Names.--2. Define the index, replacing a prior written or mismatching index.- Defining and- undefining need the owner hierarchy; when the TPM has an owner- password, ``tpm.owner_auth`` in ``/etc/shirudo/shirudo.conf``- supplies it. The name the TPM reports is compared with the one- computed in software; a mismatch is ``EPROTO``, not a retry.- The index receives no secret writer authorization; its policy names- the public signing key. Provisioning still uses the existing owner- authorization over the trusted local TPM channel.--3. Extend the index with the init event through the signed ``init`` branch.- The session walks the branch on the TPM and its digest is read back- with ``PolicyGetDigest`` and compared with the software policy, so- a drift between ``util/tpm_wire.c`` and the TPM fails with a clear- message instead of ``TPM2_RC_POLICY_FAIL``.--4. Anchor: extend PCR 9 with ``SHA256(anchor)`` where the anchor is- the string ``nvpcr-init:shirudo:0x1818e00:<written name hex>``,- systemd's ``nvpcr-init`` event format. From this moment the- ``init`` branch cannot be satisfied again until the next TPM- reset, because PCR 9 no longer holds ``pcr_before``; once systemd- measures ``leave-initrd``, PCR 11 does not hold ``phase_before``- either.--5. Append the ``init`` record to the eventlog (section 3) with both- PCR values, whether the initrd was running, the written name, the- anchor and its digest, the register value, the TPM's reset- count and ``nv_writer_public``: the writer's public key, encoded as- the 384-byte, big-endian RSA modulus in 768 hex digits, without a TPM- header. The exponent is fixed at 65537 and is not stored.--The phase measurements are ``systemd-pcrphase-initrd.service``'s,-which systemd runs only for a measured UKI boot; without them PCR 11-never moves, the binding is only as strong as the anchor in PCR 9 and-``init`` says so. Run from the root file system instead, ``init``-binds all the same,-with the post-initrd PCR 11 value and ``bound_in: root`` on the-record, and warns; a verifier that pins the ``enter-initrd`` value or-requires the initrd binding rejects such evidence, which is what tells-a late binding, by ``init`` or by anyone else, from the real one.--The reset count, read with ``TPM2_ReadClock``, changes at every TPM-reset and nowhere else, so a record of this boot for the current count-means this register period already has its binding. A re-run of-``init`` then finds the index written with the recorded name, reuses-it and adds no event; finds it gone, unwritten or renamed, it refuses-with ``tampered`` and binds nothing before the next TPM reset, because-a second binding would restart the history the record vouches for.-An absent or unreadable writer identity refuses as well. A re-run-with a complete binding reuses the same writer.-Without a record for the current count, whether the boot is new or-the TPM was reset without a reboot, the index is bound; one found-written by someone else first is undefined and bound again, with a-warning, and PCR 9 then carries both anchors.--Extending later-~~~~~~~~~~~~~~~--Every load, unload and tree operation extends the register through-the authenticated ``written`` branch, with the policy recomputed from the-``pcr_before`` on this boot's init record, and only after checking-that the live index carries the recorded name. No register this boot-is ``tpm_error``; a live index whose name is not the recorded one is-``tampered``. Every state-changing command also reads the register-first and refuses ``tampered`` when ``--expect-chain`` disagrees, which-serialises concurrent operators.--Consequences: an index undefined and recreated at runtime under the-same policy cannot be written, because PCRs 9 and 11 have moved; one-recreated-under another policy has a name the record does not know; and the-register value at any time is a pure function of the certificate, the-installed set, the tree root and the events since boot, so the-operator computes it with ``shirudo attest predict`` and never needs-history.--TPM access-~~~~~~~~~~--An authenticated-image target takes the TCTI from ``tpm.tcti``-in authenticated configuration, or defaults to ``device:/dev/tpmrm0``,-the kernel resource manager. It accepts only a device TCTI so-commands pass through the kernel guard, and refuses environment-overrides. Host-side tests without an active target image may use-``SHIRUDO_TPM_TCTI`` to select a software TPM. Register writes-send command-bound signatures, not private-key bytes.--The device path alone does not authenticate the TPM behind it. Before-reading or writing the register, Shirudo recreates the attestation key-and compares its Name with the one ``init`` froze in the identity map.-This rejects a different reported Name, but the Name is public: a fake-transport could replay it. Remote verification requires signed evidence-from the pinned attestation key. The selected transport implementation-remains part of Shirudo's trusted process code.--Migration requires an updated target and initrd, a-trusted reboot, and the updated operator verifier. The new policy-changes the NV Name; old public-write-policy evidence is-rejected, not accepted through a compatibility branch. The Name-commits to the writer's public key and policy reference. It does not-prove private-key custody: verification still requires trusted TPM-identity and approved boot measurements covering initialization.--2) Events------------Every extension is a 32-byte digest with a domain-separating tag.-``\0`` marks the NUL that terminates the tag inside the hashed bytes.--init- ``SHA256("shirudo-init\0" || cert_sha256 || set_digest ||- tree_root)``. ``cert_sha256`` covers the certificates ``init``- enrolled: the digest of the one certificate's DER when the set has- one member, else the SHA-256 over the members' DER digests sorted,- which ``shirudo attest predict --cert=... --cert=...`` computes- from the same files in any order. ``set_digest`` is the SHA-256 of- the listing of the re-applied set, one line ``<payload_sha256 hex>- <name>\n`` per- upatch, sorted by name. ``tree_root`` is the upatch tree's- projection root at boot, or 32 zero bytes without a tree.--upatch load- ``SHA256("shirudo-upatch\0" || payload_sha256 || name)``.--upatch unload- ``SHA256("shirudo-unload\0" || payload_sha256 || name)``.--tree operation- ``SHA256("shirudo-tree\0" || seq || operation_digest)`` with- ``seq`` as eight big-endian bytes and ``operation_digest`` the- publication's digest of the operation.--key revocation- ``SHA256("shirudo-key-revoke\0" || cert_sha256)`` with the revoked- certificate's DER digest. ``shirudo keys revoke`` extends it right- after unlinking the key and before purging what the key signed,- each loaded upatch of which then follows as its own unload event.--The register after an event is ``SHA256(register || event)``, starting-from zeros; ``chain_fold()`` and the eventlog replay use the-same fold. Boot restore is exactly one init event however many-upatches it re-applies.--3) The eventlog------------------``/var/lib/shirudo/eventlog`` (``SHIRUDO_EVENTLOG_PATH`` overrides it-for the host-side tests) is append-only JSON lines, one per-extension, written with ``fsync`` and sealed like everything under-``/var/lib/shirudo``. Every record carries ``schema`` (2), ``ts``,-``nv_index``, ``alg``, ``digest`` (the event), ``type`` and-``boot_id``. By type:--``init``- ``tpm_reset_count``, ``cert_sha256``, ``certs`` (the enrolled- certificates' DER digests), ``set_digest``,- ``tree_root``, ``set`` (the listing as ``name`` and- ``payload_sha256`` pairs), ``pcr`` (9), ``pcr_before``,- ``phase_pcr`` (11), ``phase_before``, ``bound_in`` (``initrd`` or- ``root``), ``nv_name`` (the written name), ``anchor``,- ``anchor_digest`` and ``chain`` (the register after the event).--``upatch_load`` and ``upatch_unload``- ``upatch`` with ``name`` and ``payload_sha256``; an unload a- revocation caused carries ``reason`` (``key_revoke``).--``tree_op``- ``tree`` with ``seq``, ``op``, ``id`` and ``operation_digest``,- and ``chain``.--``key_revoke``- ``key`` with ``fingerprint`` (of the public key) and- ``cert_sha256`` (of the DER, the value the event hashes).--"This boot" is every line with the running ``boot_id`` from its last-``init`` record on. Replaying those lines from zeros must reproduce-the live register; ``shirudo status`` does that replay, checks that-the live index carries the recorded name and that the record is of-the TPM's current reset count, and reports ``register_bound``,-``register_anchored``, ``init_records``, ``register_rebound``,-``nv_name``, ``pcr``, ``pcr_before``, ``phase_pcr``, ``phase_before``,-``bound_in``, ``chain`` and ``chain_matches_eventlog``. A register that exists without a record-of this boot, that the records do not explain, or that a second init-record for one reset count shows was bound again, is reported as a-mismatch. An operation that would push the eventlog past-``eventlog.max_bytes`` refuses with ``eventlog_full`` before it-touches the TPM, so register and log never diverge.--4) Attestation-----------------``shirudo attest`` makes the TPM speak. It needs no enrolment state-on the target and leaves none behind.--The attestation key-~~~~~~~~~~~~~~~~~~~--The key is a primary object under the endorsement hierarchy created-from a fixed template: ECC NIST P-256, ECDSA with SHA-256, attributes-``fixedTPM``, ``fixedParent``, ``sensitiveDataOrigin``,-``userWithAuth``, ``restricted`` and ``sign``, no authorisation value-and no policy. A primary with a fixed template is derived from the-TPM's endorsement seed, so the same TPM always yields the same key;-it is created for each run and flushed afterwards. ``restricted``-means the TPM signs only structures it generated itself, so the key-cannot be used to sign arbitrary data. Its name is the SHA-256 of its-marshalled public area, which ``attest`` recomputes and compares with-the name the TPM reports. In the signed structures the signer appears-as the qualified name, ``SHA256(0x4000000B || name)``, the endorsement-hierarchy's handle followed by the key name.--The evidence-~~~~~~~~~~~~--``shirudo attest --nonce=<hex> [--pcrs=<list>] [--out=<path>]`` emits-one JSON document, ``kind`` ``shirudo-attestation``, ``schema`` 1:--``nonce``, ``pcr_bank``, ``pcr_mask``, ``pcrs``- The nonce the verifier chose (up to 64 bytes), the SHA-256 bank,- and the values of the selected PCRs, by default 0-7, 9 and 11-15.--``ak``- ``public`` (the marshalled ``TPMT_PUBLIC``) and ``name``.--``ek``- ``type`` (``ecc`` or ``rsa``), ``public`` and ``name`` of the- endorsement key, created from the TCG default template of the type- the endorsement certificate describes, the ECC one on a TPM that- holds no certificate. Section "Binding the key to the TPM" below- says what it is for.--``quote``- ``attest`` and ``signature``: ``TPM2_Quote`` over the selection- with the nonce as qualifying data. The PCRs are read beside the- quote and the quote is kept only when its digest covers exactly- those values; otherwise both are taken again, up to three times.--``register``- ``nv_index``, ``pcr`` (9), ``name`` (the live index name),- ``value``, and ``attest`` and ``signature`` from- ``TPM2_NV_Certify`` of the index's 32 bytes at offset 0 with the- same nonce. The certification names the index, so it binds the- value to the public area it was produced under.--``eventlog``- This boot's records, verbatim.--``credential``- ``value``, the credential recovered from the verifier's challenge- when the evidence was requested with ``--challenge``, else- ``null``.--``ek_certificate``- The endorsement key certificate from NV ``0x01C0000A`` (ECC) or- ``0x01C00002`` (RSA), base64, or ``null`` when the TPM holds none.- It is carried for the operator's tooling; see section 7.--``logs``- ``firmware`` (``/sys/kernel/security/tpm0/binary_bios_measurements``)- and ``systemd`` (``/run/log/systemd/tpm2-measure.log``), base64 or- ``null``, so the verifier can replay the PCRs it pins.--``version_id``, ``ts`` and ``boot_id`` describe the producer and are-not TPM-backed. Without ``--nonce`` the document proves no freshness-and says so.--Binding the key to the TPM-~~~~~~~~~~~~~~~~~~~~~~~~~~--A signature by a key named ``000b...`` proves nothing about where that-key lives until the name is tied to a TPM. The endorsement key does-that: it is derived from the TPM's endorsement seed by a template the-TCG fixes, and the endorsement certificate the manufacturer put in NV-describes exactly that key. Credential activation makes the two keys-vouch for each other without ever exposing either.--On the operator, ``shirudo attest challenge --evidence=<path>---out=<challenge> [--ek-ca=<bundle>]`` takes the endorsement key and-the attestation key name from an evidence document and checks that-the endorsement key's name matches its public area and that the area-is the TCG default template under the endorsement policy, so no-ordinary decryption key can pose as one. When the evidence carries-an endorsement certificate, the certificate's key must be that key,-and with ``--ek-ca`` the certificate must chain to the PEM bundle of-issuers given. The endorsement key has to be vouched for: by that-chain, by ``--ek-name`` from an inventory or a platform's API, or-explicitly waived with ``--trust-presented-ek``, which proves only that-the same party answers each time; the command makes no challenge-otherwise. ``--ak-name`` makes the challenge for the pinned-attestation key rather than the one the document names. It then draws-a random 32-byte credential and-protects it the way ``TPM2_MakeCredential`` does (Part 1, 24.4): a-seed only the endorsement key can recover, wrapped with RSA-OAEP under-the label ``IDENTITY`` for an RSA key or derived by KDFe from an-ephemeral P-256 ECDH agreement for an ECC key; a symmetric key from-``KDFa(seed, "STORAGE", name)`` that encrypts the credential with-AES-128-CFB; and an HMAC under ``KDFa(seed, "INTEGRITY")`` over the-encrypted credential and the attestation key name. The challenge-document carries the blob and the wrapped seed; the credential itself-is printed once for the operator to keep and stored nowhere.--On the target, ``shirudo attest --nonce=<hex> --challenge=<path>``-loads the endorsement key of the challenge's type, refuses a challenge-made for another attestation key name, and has the TPM run-``TPM2_ActivateCredential`` under a ``PolicySecret`` session on the-endorsement hierarchy. The TPM recovers the seed with the endorsement-key, recomputes the HMAC over the name of the loaded attestation key,-and decrypts the credential only when it matches; the value goes into-the evidence as ``credential``. A blob made for another key or-another TPM is refused and the command fails rather than emit evidence-without the proof.--``shirudo attest verify ... --expect-credential=<hex>`` then checks the-recovered value. Together with the signature checks this proves that-the key which signed the quote and the certification is a restricted-key inside the TPM that holds the endorsement key, and, through the-certificate, inside the TPM the manufacturer certified. Everything-here is classical: TPMs hold RSA and P-256 endorsement keys and sign-with ECDSA, and no post-quantum algorithm is implemented by a TPM one-can buy or emulate, so the evidence stays classical even though the-artifacts it describes are not (residual risk 9). The RSA branch-exists because many TPMs carry only an RSA endorsement certificate.--5) Verification and prediction---------------------------------Both run on the operator and touch no TPM.--``shirudo attest verify --evidence=<path> --nonce=<hex> --ak-name=<hex>-[--ek-name=<hex>] [--cert=<cert.der> --upatch=<file>...---expect=<name>=<hex>... --tree-root=<hex>] [--expect-chain=<hex>]-[--expect-pcr=<n>=<hex>...] [--expect-bind-pcr=<n>=<hex>...]-[--require-initrd] [--expect-credential=<hex>] [--allow-runtime-events]-[--strict-anchor]`` prints one line per check and a verdict. The-checks, in order:--1. The nonce in the document is the one given.-2. The attestation key's public area is a P-256 ECDSA key with- ``restricted``, ``sign``, ``fixedTPM``, ``fixedParent`` and- ``sensitiveDataOrigin`` set; its name matches that public area; and- it is the pinned name. Without ``--ak-name`` the signer is only- noted, and the command warns. The endorsement key's name matches- its public area and that area is the TCG default template under- the endorsement policy; with ``--ek-name`` it is the pinned key;- with ``--expect-credential`` the document's ``credential`` equals- the value the challenge carried, which needs ``--ak-name``: the- credential proves where the pinned key lives, not which key signed.-3. The quote: ECDSA signature by that key over the ``TPMS_ATTEST``,- signer equal to the key's qualified name under the endorsement- hierarchy, the nonce as extra data, the selection equal to- ``pcr_mask``, every selected PCR listed, and the listed values- hashing to the quoted digest.-4. The register certification: the same signature, signer and nonce- checks, the certified index name equal to the listed name, and the- certified 32 bytes at offset 0 equal to the listed value.-5. The binding: this boot has an ``init`` record; the document names- the register's handle and PCRs 9 and 11, the verifier's own- constants and never the record's, since a target can define an- index of its own under a policy over PCRs it extends and resets at- will; the name a register bound to that record's ``pcr_before`` and- ``phase_before`` must have, computed in software from the handle,- the attributes with ``TPMA_NV_WRITTEN``, the policy including the- fixed RSA-3072 template, ``nv_writer_public`` public key and reference,- and the size, equals both the certified name and the recorded one.- Every ``--expect-bind-pcr`` value equals the recorded one for that PCR,- so the operator pins the ``enter-initrd`` phase value from the UKI, and- ``--require-initrd`` fails unless the record says the binding was- made while the initrd ran; the record is the target's word, so- ``--expect-bind-pcr=11`` is what proves it.-6. The reset: the boot holds one init record for the reset count the- last one names, that count is the one the certification carries,- and the quote and the certification carry the same reset count and- firmware version, so a register bound again after boot cannot pass- as the boot's.-7. The replay: this boot's records fold from zeros to the certified- value, and every event after the ``init`` record carries the digest- its own fields produce: the name and payload of a load or unload,- the sequence number and operation digest of a tree operation, the- certificate digest of a revocation. A record relabelled after the- fact still replays, since the digest is what was measured, and- fails here.-8. The anchor: the record's anchor digest is the digest of the anchor- string for the recorded name, and the quoted PCR 9 equals- ``pcr_before`` extended by it. When PCR 9 holds further- measurements the check is a note unless ``--strict-anchor`` makes- it a failure.-9. The expected state: with ``--cert`` the init event equals the one- computed from the certificate, the ``--upatch`` and ``--expect``- members and ``--tree-root``; the register equals ``--expect-chain``- when given, else the value predicted for the set at boot, else,- with events after boot, ``--allow-runtime-events`` decides; every- ``--expect-pcr`` value matches the quote. Events after boot are- listed.--The verdict is ``ok`` only when every check passed; a document that is-not shirudo evidence exits 2.--``shirudo attest predict --cert=<cert.der> [--upatch=<file>...---expect=<name>=<hex>... --tree-root=<hex>]-[--event=load|unload:<name>=<payload_sha256>...---event=tree:<seq>=<operation_digest>...]`` prints ``set_digest``,-``init_event``, ``register_at_boot`` and, with events,-``register_after_events``, from the same functions the target uses.-With ``--bind-pcr=9=<hex> --bind-pcr=11=<hex>---writer-public=<384-byte public-key hex>`` it also prints-``register_name``, the anchor string and ``pcr9_after_anchor``, so the-name and PCR 9 can be pinned from values the operator knows. A fresh-boot's writer public key is an additional input; it cannot be predicted-from artifacts and PCR binding values alone.--``shirudo attest challenge --evidence=<path> --out=<path>-[--ek-ca=<bundle>]`` is described in section 4; it prints its checks,-the path of the challenge it wrote and the credential to expect.--6) Relation to systemd's NvPCRs----------------------------------The register follows systemd's NvPCR construction (``*.nvpcr``-definitions, ``systemd-tpm2-setup-early``, ``systemd-pcrextend``;-see `TPM2 PCR Measurements Made by systemd-<https://systemd.io/TPM2_PCR_MEASUREMENTS/>`__), introduced in-systemd v259 and reworked in v262. Shared with it:--* the index type and attributes, in particular ``TPM2_NT_EXTEND`` and- ``TPMA_NV_CLEAR_STCLEAR``, so the register is a per-boot PCR in NV;-* the two-branch policy shape, ``PolicyOR`` of a ``PolicyNvWritten(YES)``- branch and an initialisation branch that only- a particular boot state satisfies;-* the index name as the anchor, certified by ``TPM2_NV_Certify``, and- the ``nvpcr-init:<name>:0x<handle>:<tpm name>`` event string.--Different from it, and why it matters:--* **Authenticated writers.** Unlike systemd's public-append NvPCRs,- shirudo requires ``PolicySigned`` and ``NV_Extend`` command- restriction after the OR. Its runtime events assert successful- operations, not merely a history that cannot be erased. Native- systemd registration must preserve that authorization; adopting a- public-append policy would reintroduce false positive measurements.--* **The initialisation branch.** systemd v262 binds it with- ``PolicyAuthorize`` to the UKI's PCR signing key (policy reference- ``initrd``) and satisfies it with the signed ``PolicyPCR`` for PCR 11- at ``enter-initrd``; the index is initialised in the initrd and the- branch closes when ``leave-initrd`` is measured. The name is then- stable across kernel updates, and it is unsatisfiable at runtime- whatever an attacker does. v263 adds a plain ``PolicyPCR`` fallback- where no signed policy exists, and that is shirudo's construction:- a plain ``PolicyPCR`` over PCRs 9 and 11, bound from the initrd at- ``enter-initrd`` and closed by ``leave-initrd`` and by the anchor.- The name therefore changes with the initrd and the phase value, so- the record carries both and the operator pins them from the UKI with- ``--expect-bind-pcr``.--* **The anchor's PCR.** Both measure the ``nvpcr-init`` event into PCR- 9. systemd does so through ``systemd-pcrextend`` before- ``nvpcr-separator``, and its verifiers trust a certified name only if- it appears in the PCR 9 log before the separator; shirudo extends PCR- 9 itself, after the separator when ordered after- ``systemd-pcrnvdone.service``, and keeps the anchor in its own- eventlog, so the extension does not appear in systemd's measurement- log and systemd-aware tooling has to take it from the evidence.--* **Registration.** The register is not a ``*.nvpcr`` definition and- has a handle of its own, so systemd neither initialises nor extends- it, and systemd-aware verifiers do not know it.--Registering the register as a systemd NvPCR, so that its name follows-the UKI signing key and systemd anchors it before the separator while-shirudo only extends it, is the deferred step that would remove the-boot-integration differences; it must retain authenticated writers.-Until then the two coexist without interfering.--7) Limits------------These are the known limits of the design as implemented; the-`threat-model <threat-model.rst>`__ residual risks give the full-context and the deferred mitigations the plan.--* **The binding values come from the record unless pinned.**- ``verify`` recomputes the index name from the ``pcr_before`` and- ``phase_before`` the init record claims; ``--expect-bind-pcr`` makes- them values the operator knows, and ``predict --bind-pcr`` with the- writer public key turns those into the expected name and PCR 9. Root with the owner- authorisation (empty on most TPMs) can still undefine the written- index at runtime; from then on every extension and ``init`` itself- refuse ``tampered`` until the next TPM reset, a denial of service and- not an erasure.--* **The endorsement key's trust is the certificate's.** Credential- activation proves the attestation key sits beside the endorsement- key in the evidence; whether that endorsement key belongs to a- genuine TPM is what the endorsement certificate says, and only- ``--ek-ca`` with the manufacturer's issuers checks it. A TPM- without a certificate, as virtual TPMs usually are, leaves the- endorsement key pinned by its name as presented at enrolment.--* **PCR 9 after the anchor.** The exact anchor check holds while- nothing is measured into PCR 9 after ``init``; systemd's- ``nvpcr-separator`` lands there, so ``init`` orders after- ``systemd-pcrnvdone.service``.--* **The boot window.** Run from the initrd, ``init`` can be preceded- only by what the initrd runs before it, which the measured boot- records; a binding made from the root file system is one the- verifier can reject, not one it can prevent.--* **PCR 11 needs a UKI.** systemd measures the initrd phases only on- a measured UKI boot; a kernel and initrd loaded by grub or passed to- QEMU directly leave PCR 11 at its boot value, ``init`` warns, and- the verifier has PCR 9 alone to tell an initrd binding from a later- one.--* **A TPM reset without a reboot.** Resuming from hibernation resets- the TPM but keeps the kernel's boot ID, so the register is gone while- the record of this boot stands; every extension then fails- ``tpm_error`` until ``init`` is run again, which the reset count on- the record lets it do.--* **The evidence is classical.** TPMs sign with ECDSA P-256; the- artifacts the evidence describes are ML-DSA-87.--8) Testing-------------``make -C testing functional/tpm`` runs-``testing/functional/tpm/t4003-register.sh`` in a dedicated pre-init KVM-guest. It creates the TPM-held writer-and freezes its nonsecret input and public modulus in a BPF identity-map. The libtpms command transport controls PCR phases and TPM resets-while the guest kernel and writer-survive. This preserves lifecycle, attestation and credential-activation-coverage, including index recreation, the closed first-write window,-reset recovery and late binding. It is a protocol test before the LSM-attaches, not evidence of guard enforcement. The operator tests skip it;-``make -C testing functional/tpm`` runs it in a VM of its own before the-tpm family's.-The same guest runs ``testing/functional/tpm/t4004-config-attest.sh``-with a fresh native writer to cover config-PCR evidence alongside the-signed NV register.-The test-only ``test-register-cli`` invokes the attestation and status-commands before enforcement, without entering an authenticated runtime.-The production CLI rejects that synthetic identity map; protected-target-tests continue to invoke the installed runtime binary.--``testing/functional/tamperproof/t6006-harden.sh`` checks process-wide-locking, fail-closed startup and the memory-lock limits of every shipped-service.--``testing/functional/tpm/t4001-tpm-wire.sh`` checks the policy digests,-names, wire parsers, the key derivations, the endorsement policy and the-credential blob against known vectors and an independent-implementation, without a TPM.--Post-init integration tests run only against a real kernel in the KVM-guest with swtpm attached through ``/dev/tpmrm0``-(``make -C testing functional``). There is no software signing fixture:-the guest uses the production TPM-held writer and installed-``shirudo`` binary. ``testing/functional/tpm/t4102-tpm-chain.sh``-exercises measured loads and unloads, initialization reuse, prediction, attestation,-credential activation and rejection of forged writer evidence.-Prediction uses the offline command fixture rather than overriding the-production runtime's certificate selection.-``make -C testing functional`` also exercises the production initrd and-switch-root path in ``testing/functional/tpm/t4101-initrd.sh``.--``testing/helper/test-nv-cphash`` creates a separate TPM-resident writer-with the production provisioning function. It tests nonce and command-binding directly through ESYS on a scratch NV index. Both the pre-init-and protected target VMs run it; the guard allows this separate index.-Replayed and corrupted signatures must fail without changing NV. ``PolicySigned`` accepts an authorization for event A; extending-event B must fail without changing the value. A fresh session then-extends A and the test checks the exact result and removes the scratch-index. No software private-key file or production fault-injection hook-is used.--``testing/functional/tpm/t4103-nv-writer.sh`` compares the writer's-public modulus with the init record. It checks that untrusted root cannot directly-extend Shirudo's register through either TPM device, whether the write-blocks, is nonblocking, or uses an inherited connection. A short-``NV_Extend`` command is also refused. Unrelated TPM signing, another-NV index and PCR extension remain available. The test verifies that-trusted loads and unloads still change the register, while a denied-extension leaves it unchanged.--``testing/helper/test-tpm-preopened`` opens a TPM connection after-initialization and forks an unrelated process which inherits it.-The child submits a direct ``NV_Extend`` for Shirudo's index.-The LSM must refuse the command with ``EACCES``, and reads before and-after must return the same register value. A TPM policy error or-transport failure does not pass this test. The connection is inherited-after LSM attachment; this test does not open a descriptor before-attachment.--Configuration image measurements-================================--Image mode adds a reserved static SHA-256 PCR for config selections. It does-not replace the upatch NV register or its PCR 9/11 bootstrap binding. The-PCR number and config verification certificate come from authenticated-runtime bootstrap settings; config images cannot override either.--Each BOOT or UPDATE event hashes ``"shirudo-config-root-v1\0"``, the-big-endian 32-bit event kind and the 32-byte binary root hash, then extends-this PCR before config effects. BOOT is 1 and UPDATE is 2. The durable-selection records TPM reset and restart counts. Once pending, an interrupted-activation blocks further state changes and config attestation until a-manual reboot; no same-boot retry is attempted. The node keeps running and-Shirudo never initiates the reboot. The-`config-images <config-images.rst>`__ guide gives the pending-selection rules.--``shirudo attest`` automatically includes this PCR and emits the current-boot's config history: schema, PCR index, reset/restart counts, initial PCR-and events containing sequence, kind and root hash. The quote binds PCR-values and TPM boot identity. Verify the intended config with both-``--expect-config-root=<64 hex>`` and ``--expect-config-pcr=<number>``.-The verifier derives each event digest and rejects malformed roots,-discontinuous sequences, incorrect boot identity, a mismatching selected-root or a replay that does not reach the quoted PCR. Pending activations-cannot produce healthy evidence through the normal CLI.--Without an expected config root, successful replay is reported as-consistency without operator approval. Neither this replay nor a static-PCR proves that only the trusted updater issued the TPM command: direct-measurement writers can record a selection without the corresponding-operation. Restricting writers remains separate work for the config PCR;-the upatch NV register has the extension guard described above.-No IMA integration is added.diff --git a/Documentation/upatch-spec.rst b/Documentation/upatch-spec.rstdeleted file mode 100644index cfaa7249..00000000--- a/Documentation/upatch-spec.rst+++ /dev/null@@ -1,426 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--The .upatch container format-============================--This document specifies the on-disk ``.upatch`` container: the portable,-signed unit the operator produces with ``shirudo build`` and the target-consumes with ``shirudo upatch load`` and ``unload``. It is the-byte-level reference. The structures live in-``include/shirudo/upatch.h``, the writer in-``tools/shirudo-build/package.c``, the reader in ``util/upatch.c``.--A ``.upatch`` carries everything a signed ``BPF_PROG_LOAD`` needs to-install a BPF program on a machine other than the one that built it:-the gen_loader "light skeleton" instructions, the data those-instructions reference, a detached CMS signature, and a small amount of-metadata. There is exactly one container shape for both LOAD artifacts-and UNLOAD directives; a flag bit distinguishes them.--1) Conventions-----------------Every multi-byte integer is little-endian on every supported-architecture. Operator and target may differ in architecture; the-wire format does not.--The file begins with a 360-byte header of naturally aligned fields-with no padding. All other content is referenced by-``*_off``/``*_len`` pairs in the header, as byte offsets from the start-of the file. Sections do not overlap the header and must lie within-the file.--Sizes are bounded: a reader rejects a file larger than 16 MiB.-Artifacts are small in practice.--2) File layout-----------------::-- offset 0 +-------------------------------------------+- | header (360 bytes, fixed) |- 360 +-------------------------------------------+- | loader_insns (signature-covered) |- +-------------------------------------------+- | signature (CMS/PKCS#7, detached) |- +-------------------------------------------+- | data (signature-covered) |- | loader data |- | signed sections, directory, trailer |- +-------------------------------------------+- | metadata | optional- +-------------------------------------------+--The writer emits the sections in this order, but a reader must rely-only on the header offsets, never on adjacency. ``loader_insns``-begins at offset 360, immediately after the header. ``metadata`` is-optional and the writer no longer emits it; an absent section has its-``*_off`` set to 0. ``data`` always ends with the signed sections.--3) Header------------``struct shirudo_upatch_header``, 360 bytes, little-endian, no padding:--========== ==== ====== ===================== ===========================================-offset size type field meaning-========== ==== ====== ===================== ===========================================-0 8 u64 magic ``0x53485244554E4150`` (see below)-8 4 u32 version ``1``-12 4 u32 flags bit 0 = ``DIRECTIVE_UNLOAD``; bits 1-31 zero-16 256 char[] name upatch name; NUL-padded, not guaranteed- NUL-terminated on disk-272 32 u8[] payload_sha256 SHA-256 of ``loader_insns || data``-304 4 u32 loader_insns_off file offset of the loader instructions-308 4 u32 loader_insns_len length in bytes (multiple of 8)-312 4 u32 signature_off file offset of the CMS signature-316 4 u32 signature_len length in bytes-320 4 u32 metadata_off file offset of metadata, or 0-324 4 u32 metadata_len length in bytes, or 0-328 4 u32 data_off file offset of the loader data, or 0-332 4 u32 data_len length in bytes, or 0-336 4 u32 log_buf_sz verifier-log buffer size to allocate at load-340 4 u32 nr_maps gen_loader bpf_map_desc count-344 4 u32 nr_progs gen_loader bpf_prog_desc count-348 4 u32 rodata_data_off ``.rodata`` initial value offset in ``data``-352 4 u32 type ``1`` = BPF-356 4 u32 reserved1 zero-========== ==== ====== ===================== ===========================================--magic-~~~~~--``magic`` is the u64 ``0x53485244554E4150`` stored little-endian; its-bytes spell ``SHRDUNAP`` when read most-significant-first. A reader-that sees any other value rejects the file.--log_buf_sz-~~~~~~~~~~--There is no log-buffer section in the file. ``log_buf_sz`` (typically-1 MiB) records the size of the verifier-log buffer the target allocates-in memory at load, so a verifier rejection can be captured in full and-surfaced in the failure report. Only the size travels in the artifact.--nr_maps and nr_progs-~~~~~~~~~~~~~~~~~~~~--After the signed loader runs under ``BPF_PROG_TEST_RUN``, it writes the-created map and program fds into descriptor arrays trailing its-context, in libbpf's object-iteration order. The target has only the-``.upatch``, not the original object, so these counts tell it where to-find the resulting ``prog_fd`` to attach and pin. They mirror-gen_loader's own iteration.--4) Sections--------------loader_insns-~~~~~~~~~~~~--The bytes of ``gen_loader_opts.insns`` after ``bpf_object__gen_loader()``-and ``bpf_object__load()`` on the operator. This is a-``BPF_PROG_TYPE_SYSCALL`` "light skeleton" loader: run via-``BPF_PROG_TEST_RUN`` on the target, it issues the ``bpf()`` calls-(``BPF_BTF_LOAD``, ``BPF_MAP_CREATE``, ``BPF_PROG_LOAD``, ...) that-install the payload. The signature covers this section concatenated-with ``data``.--For an UNLOAD directive (``flags & DIRECTIVE_UNLOAD``) the loader is not-a gen_loader output but the compiled bytes of the small hand-written-``bpf/unload.c`` template, parameterised through its ``.rodata`` with-the target name and the expected ``payload_sha256``; the target reads-both from the signed ``NAME`` and ``UNLD`` sections instead.--signature-~~~~~~~~~--A detached CMS/PKCS#7 signature over ``loader_insns || data``, produced-by the vendored ``util/sign.c`` on the operator. On the target, the-kernel's ``bpf_prog_verify_signature()`` checks it against the-certificate in the sealed bpf keyring, named as ``attr.keyring_id``-(``KEY_SPEC_BPF_KEYRING``), before the-verifier and the LSM hooks run.--The container is algorithm-agnostic: the SignerInfo names the key-algorithm, the signer is identified by subjectKeyIdentifier, and no-certificate is embedded. shirudo's writer signs with ML-DSA-87 only-(it refuses other keys) and emits one of two kernel-accepted forms,-depending on the OpenSSL it links: signed attributes (contentType and-messageDigest only, no signingTime, so the bytes are reproducible) with-a SHA-512 message digest on OpenSSL 3.x, or a signature over the-content itself with no attributes on OpenSSL 4. An ML-DSA-87-SignerInfo is about 4.9 KiB. The writer caps ``signature_len`` at-16 KiB and the kernel at 64 KiB.--data-~~~~--The bytes of ``gen_loader_opts.data``: the blob the loader instructions-reference (the program BTF, ``.rodata`` and map initial values,-relocation inputs, ...), followed by the signed sections. The loader-is parameterised by its data, so it must travel with the instructions;-it ignores the bytes behind it because all its offsets refer to the-original prefix, and the kernel signs the whole section, so what the-target needs beyond the loader rides there, covered.--Signed sections. Each section is placed at an 8-byte boundary after-the loader data, then a directory of 16-byte entries, then a 16-byte-trailer that ends ``data``:--========== ==== ===================== ====================================-offset size field meaning-========== ==== ===================== ====================================-+0 4 magic ``0x52544753`` (``"SGTR"`` LE)-+4 4 version ``1``-+8 4 dir_off directory offset from the start of ``data``-+12 4 nr_sections directory entries, 1 to 8-========== ==== ===================== ====================================--Each directory entry:--========== ==== ===================== ====================================-offset size field meaning-========== ==== ===================== ====================================-+0 4 tag ``"NAME"``, ``"UPGM"``, ``"UNLD"`` or- ``"DCDB"`` as little-endian u32-+4 4 reserved zero-+8 4 off section offset from the start of ``data``-+12 4 len section length-========== ==== ===================== ====================================--Every section lies before the directory, and every tag appears at most-once. ``NAME`` (256 bytes, NUL-padded) is the upatch name of a LOAD-and the target name of an UNLOAD directive; the header's ``name`` must-equal it. ``UPGM`` is the attach metadata of a LOAD, described below.-``UNLD`` (32 bytes) is the ``payload_sha256`` an UNLOAD directive-expects the loaded upatch to carry. ``DCDB`` is the decoder blob. A-reader takes a directory that breaks any of this for none, and a load-or unload then refuses for what it lacks.--Decoders. A BPF source declares ``struct shirudo_decoder_manifest`` in-``.rodata``. At build time shirudo resolves and embeds each referenced-decoder source in the ``DCDB`` section before signing-``loader_insns || data``, so the decoders are signature-covered.-The blob starts with magic ``0x42444344`` (``"DCDB"`` LE), a version, a-decoder count and a reserved word. Each 200-byte entry holds the-language, API version, input format, fixed-size upatch, map, source-and entrypoint strings, and the source offset and length within the-blob. Version 1 defines language ``1`` as Lua and input format ``1``-as serializer pages v2. The decoder API itself is described in-`telemetry <telemetry.rst>`__.--metadata-~~~~~~~~--Optional auxiliary bytes, not signature-covered. An UNLOAD directive-carries its expected ``payload_sha256`` here so the target can compute-the unload chain event without parsing the loader data.--A LOAD upatch produced by ``shirudo build`` carries attach metadata:--========== ==== ===================== ====================================-offset size field meaning-========== ==== ===================== ====================================-+0 4 magic ``0x4D475055`` (``"UPGM"`` LE)-+4 4 version ``1``-+8 4 nr_progs number of program entries-+12 4 reserved zero-+16 var progs one entry per program-========== ==== ===================== ====================================--Each program entry is 160 bytes:--========== ==== ===================== ====================================-offset size field meaning-========== ==== ===================== ====================================-+0 4 role ``0`` attach program, ``1`` serializer-+4 4 kind ``0`` raw tracepoint, ``1`` kprobe,- ``2`` kretprobe,- ``3`` cgroup_skb ingress,- ``4`` cgroup_skb egress,- ``5`` fmod_ret,- ``6`` netfilter IPv6 pre-routing,- ``7`` uprobe.multi entry probe-+8 8 offset kprobe offset; otherwise zero-+16 128 target NUL-terminated kprobe symbol or- uprobe function glob-+144 16 map NUL-terminated serializer target map-========== ==== ===================== ====================================--Version 1 optionally appends one ``UPUT`` target block after the fixed-program entries when any entry has attach kind 7. Without uprobe-programs, version 1 ends after the fixed entries:--========== ==== ===================== ====================================-offset size field meaning-========== ==== ===================== ====================================-+0 4 magic ``0x54555055`` (``"UPUT"`` LE)-+4 4 version ``1``-+8 4 nr_targets number of variable target records-+12 4 reserved zero-+16 var targets one record per uprobe program-========== ==== ===================== ====================================--Each target record begins with four little-endian ``u32`` values:-``prog_idx``, ``path_len``, ``build_id_len`` and ``nr_offsets``. They-are followed immediately, without padding, by ``path_len`` path bytes-(no NUL), ``build_id_len`` raw GNU build-ID bytes, and ``nr_offsets``-little-endian ``u64`` ELF file offsets. Paths are absolute and shorter-than 4096 bytes; build IDs are 1 to 64 bytes; offset arrays are-non-empty, sorted, unique and limited to 1,048,576 entries. The target-count must equal the number of kind-7 program entries, each program-index appearing once.--Attach metadata is advisory in the container integrity model because-metadata is not CMS-signed in v1. The loaded program bytes remain-hash-locked by the signed loader; the target validates this blob before-creating links. ``cgroup_skb`` support is limited to-``cgroup_skb/ingress`` and ``cgroup_skb/egress`` sections, attached to-the cgroup v2 root through a pinned ``bpf_link``. ``netfilter``-sections attach as ``BPF_NETFILTER`` at IPv6 ``NF_INET_PRE_ROUTING``-with ``NF_IP6_PRI_RAW_BEFORE_DEFRAG`` priority, an early IPv6 ingress-hook before extension-header protocol delivery. ``sk_skb`` and socket-filter sections are rejected by ``shirudo build``. ``fmod_ret/<symbol>``-and ``fmod_ret.s/<symbol>`` sections attach as ``BPF_MODIFY_RETURN`` so-a return-value override can reject a call before the hooked function-body runs. Kprobe return override uses a normal ``kprobe/<symbol>``-section plus the program's ``bpf_override_return()`` call; the attach-metadata remains ``kprobe``.--Uprobe authoring uses the entry-only section form-``SEC("uprobe.multi//absolute/path:function_glob")``. The glob has-libbpf's semantics: ``*`` matches any sequence and ``?`` one character,-so ``*Func`` selects both ``fooFunc`` and ``barFunc`` in one ELF.-Comma and ``|`` alternation, return probes and session probes are not-supported. At build time shirudo resolves the glob against ``STT_FUNC``-symbols, converts matches to ELF file offsets, sorts and de-duplicates-them, and records the target's GNU build ID. A zero-match glob or a-missing build ID is a build error.--Before any BPF load, the target opens the recorded ELF, verifies that-its GNU build ID is unchanged, and keeps the descriptor open through-link creation. It creates a system-wide ``BPF_TRACE_UPROBE_MULTI``-entry link with ``BPF_F_UPROBE_MULTI_PATH_FD``. ``shirudo status``-renders such a link as ``uprobe.multi/<path> (<count> funcs)``.--5) flags-----------``flags`` bit 0 is ``SHIRUDO_DIRECTIVE_UNLOAD``. Clear, the artifact is-a LOAD (install a program); set, it is a signed UNLOAD directive-(authorise removing a named, previously loaded upatch). Bits 1-31 are-reserved and must be zero. The flag changes the loader program and the-metadata semantics but nothing about the layout, the signed-content-digest or the kernel verification: both kinds load through the same-``BPF_PROG_LOAD`` + signature + ``keyring_id`` check.--6) payload_sha256--------------------For LOAD artifacts and UNLOAD directives alike this is the SHA-256 of-``loader_insns || data``, the exact bytes the detached CMS signature-covers. At load, shirudo recomputes it. For a loaded upatch it is also-recorded as the ``security.bpf.shirudo.payload`` xattr on the pin-directory. An UNLOAD directive's expected target digest is carried-separately in its ``UNLD`` section, and in its loader ``.rodata``.--It also lets ``shirudo upatch list`` and ``status`` identify an artifact-without parsing the instruction stream.--7) What is signed--------------------The CMS signature covers ``loader_insns || data``, the signed sections-included. The header and ``metadata`` are not signed. The integrity-model is therefore:--- the loader instructions and loader data are signature-verified by- the kernel before anything runs;-- the payload program is separately hash-locked by the loader's- ``excl_prog_hash`` and checked by the kernel at ``BPF_PROG_LOAD``;-- the name, the attach metadata, the unload target and the decoder- sources are signature-covered because they are appended inside- ``data`` before signing. A load takes the attach sites from the- signed ``UPGM`` section and refuses an artifact without one; an- unload takes the target name and expected payload from the signed- ``NAME`` and ``UNLD`` sections, so a directive detaches the upatch- its signer made it for and no other. Both refuse a header whose- ``name`` differs from the signed one, since the pin directory, the- archive copy, ``status`` and the package tooling read the header;-- the rest of the header is advisory. Its ``payload_sha256`` must- equal the digest of the signed bytes, which the target recomputes;- ``nr_maps`` and ``nr_progs`` must agree with the attach metadata, and- a loader whose descriptors disagree fails at attach.--8) Versioning and compatibility----------------------------------``version`` is ``1``. The header's ``rodata_data_off`` field gives the-offset within ``data`` of the initial ``.rodata`` value. Writers derive-it from the generated loader and readers check it against the BTF section-size and data bounds. The field is outside the loader signature and-serves as a location hint for offline rewriting; the signed BTF remains-authoritative for symbol offsets and sizes.--- a signed decoder blob may be appended inside ``data`` and located by- the trailer at its end. Loaders ignore the additional bytes;- readers treat them as opaque loader data;-- the signed sections are appended inside ``data`` and located by the- trailer at its end. Loaders ignore the additional bytes; a new tag- is a new section, and a reader refuses a tag it does not know;-- the 360-byte header includes ``rodata_data_off``, ``type`` and- ``reserved1`` after ``reserved0``;-- ``reserved0`` and ``reserved1`` are zero in every file a writer- emits; a reader rejects a file in which ``reserved0`` is not, so the- slot can be given a meaning later without a flag day.--A reader must reject a file whose ``magic`` or ``version`` does not-match, before trusting any offset.--9) Reader validation rules-----------------------------``util/upatch.c`` enforces, in order:--1. the file is a regular file, non-empty, and at most 16 MiB;-2. ``magic`` and ``version`` match;-3. each section ``(off, len)`` lies within the file, and any non-empty- section starts at or after the 360-byte header;-4. ``loader_insns_len`` and ``signature_len`` are non-zero,- ``rodata_data_off`` is within ``data``, and ``reserved1`` is zero;-5. the signed sections are parsed only if ``data`` ends with a matching- trailer, the directory and every section lie within ``data`` in that- order, every tag is known and appears once, ``NAME`` is 256 bytes- and ``UNLD`` 32, and the decoder blob's entry bounds fit, its fixed- strings are NUL-terminated and every source range stays inside it.- A directory that fails any of this is treated as absent by offline- inspection, and a load or unload refuses the artifact.--10) Production and consumption---------------------------------Produced by ``shirudo build``, which dispatches to the operator-only-``shirudo-build``: compile ``.bpf.c`` with ``clang -target bpf -O2 -g``-(or accept a ``.bpf.o``), run ``bpf_object__gen_loader()`` and-``bpf_object__load()``, CMS-sign the loader and data bytes, embed the-signed decoder sources, and serialise the container. ``--unload-<name>`` emits an UNLOAD directive instead.--Inspected by ``shirudo upatch info <file>`` (offline: header, sections,-attach metadata, signed decoders) and listed by ``shirudo upatch list``.--Consumed by ``shirudo upatch load`` and ``unload`` on the target through-the signature-gated ``BPF_PROG_LOAD`` naming the sealed keyring.-Artifacts reach the target inside a ``.bee`` package pulled from an OCI-registry, as an upatch-tree artifact, or as a file the administrator-copied there.--Introspected after load by ``shirudo upatch get <name>``, which reads-the loaded program's ``line_info`` and BTF from the kernel.--See `architecture <architecture.rst>`__ for the surrounding design and-`threat-model <threat-model.rst>`__ for the trust boundaries.diff --git a/Documentation/upatch.rst b/Documentation/upatch.rstdeleted file mode 100644index 43f7fca4..00000000--- a/Documentation/upatch.rst+++ /dev/null@@ -1,580 +0,0 @@-..- SPDX-License-Identifier: BSD-2-Clause- Copyright (c) 2026 Authors of shirudo--Writing, building and shipping upatches-=======================================--This is the author's and operator's guide to upatches: how a BPF-program becomes a signed ``.upatch``, how upatches are tested, bundled-into a BPM package, published to an OCI registry, and how a target pulls-them, by package or through the signed upatch tree. The-`upatch-spec <upatch-spec.rst>`__ is the byte-level reference for the-artifact, the `architecture <architecture.rst>`__ explains the signed-load path and the registry formats, and the `telemetry-<telemetry.rst>`__ document covers decoders and the export pipeline in-depth. This guide is the workflow that ties them together.--Operator build, sign and publish commands prepare artifacts on the operator.-Targets receive repository definitions, public verification certificates, tree-subscriptions and node labels in a signed config image. Local repository and-key mutations are refused. Examples that prepare these files belong on the-operator before image generation; target package and tree commands read the-selected config. BPF programs still require signed loaders and vouched boot-enrollment. See `config-images <config-images.rst>`__.--1) What an upatch is-----------------------A upatch is one BPF object, signed. The signature covers the loader-instructions and the frozen data they load, so the kernel refuses any-byte that changed between the operator's build and the target's load.-Two kinds exist:--load directive- Carries one or more programs and their maps. ``shirudo upatch- load`` verifies it, lets the signed loader install the payload,- attaches each program at the point its section name says, pins- the links and maps under ``/run/shirudo/bpffs/upatches/<name>/``,- archives the file under ``/var/lib/shirudo/upatches/`` so that- ``init`` restores it on the next boot, and extends the measurement- register.--unload directive- Carries no payload of its own, only the name of the upatch it- detaches and the payload hash it expects to find on that upatch's- pin. It is signed like any other loader and goes through the same- ``BPF_PROG_LOAD``; the detach happens only when the pin's recorded- payload matches (``payload_mismatch`` otherwise).--Every upatch has a name, by default the source file's base name, that-becomes the pin directory and the eventlog's ``name``; it is sanitised-to what bpffs accepts.--2) Writing the BPF side--------------------------A upatch is ordinary libbpf-style BPF C. The smallest possible one::-- // SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause- #include "vmlinux.h"- #include <bpf/bpf_helpers.h>- #include <bpf/bpf_tracing.h>-- char _license[] SEC("license") = "Dual BSD/GPL";-- SEC("fentry/do_nanosleep")- int BPF_PROG(shield_nanosleep)- {- return 0;- }--The licence must be GPL-compatible (``Dual BSD/GPL`` is the project's-choice) because the kernel's LSM and tracing hooks refuse anything-else. The section name picks the attach point; the loader reads it-from the object's metadata at build time and attaches the program-there, nowhere else. The kinds a target supports depend on its kernel-configuration, listed under *Attach points for upatches* in the-`requirements <requirements.rst>`__:--* ``fentry/<fn>``, ``fexit/<fn>``, ``fmod_ret/<fn>`` on kernel- functions, the last one rejecting a call before its body runs;-* ``lsm/<hook>`` and ``tp_btf/<tracepoint>``;-* ``kprobe/<fn>`` and ``kretprobe/<fn>``;-* ``uprobe.multi/<path>:<pattern>`` on userspace binaries, for example- ``SEC("uprobe.multi//usr/bin/example:*Func")``;-* ``cgroup_skb`` on the cgroup v2 root and ``netfilter`` at IPv6- pre-routing.--A upatch may hold several programs; each gets its own link, pinned as-``link_0``, ``link_1`` and so on (a single program pins as ``link``).--CO-RE and the kernel-~~~~~~~~~~~~~~~~~~~~--Include the ``vmlinux.h`` of the kernel generation the upatch is for.-CO-RE relocations make the artifact portable across builds of the same-kernel, not across kernels that renamed or moved a field: a load on-the wrong kernel fails with ``btf_mismatch`` or ``verifier_rejected``-and the verifier log in the report says which access. A hard-coded-struct offset signs fine and fails on the wrong kernel in the same-way; there is no runtime probing. When a fleet runs several kernel-generations, build one upatch per generation and let the tree's-selectors pick (section 7).--Maps and their export-~~~~~~~~~~~~~~~~~~~~~--Maps are declared as usual in ``SEC(".maps")``. Every map a upatch-creates is pinned under ``upatches/<name>/maps/`` in the private bpffs-and can be read with ``shirudo upatch map <name> <map>``, exported by-the map-export timer and shipped to a collector as described in the-telemetry document. A map whose name starts with ``obs_i_`` is-private to the upatch and is neither pinned for the operator nor-exported. The metadata the loader needs rides in frozen, exclusive-array maps the builder creates; an author never sees them.--Decoders-~~~~~~~~--A map becomes a log record or a metric through a decoder: a Lua-function shipped inside the upatch, signed with it, that turns a map-snapshot into OTLP attributes. The author declares one per exported-map with a manifest in ``.rodata``::-- #include "shirudo_decoder.h"-- const struct shirudo_decoder_manifest counters_decoder SEC(".rodata") = {- .magic = SHIRUDO_DECODER_MANIFEST_MAGIC,- .version = SHIRUDO_UPATCH_DECODER_VERSION,- .language = SHIRUDO_UPATCH_DECODER_LANG_LUA,- .api_version = 1,- .input_format = SHIRUDO_UPATCH_DECODER_INPUT_MAP_V1,- .export_signal = SHIRUDO_UPATCH_DECODER_EXPORT_METRIC,- .upatch = "my-shield",- .map = "counters",- .source = "decoders/counters.lua",- .entrypoint = "decode",- };--``export_signal`` is ``EXPORT_LOG`` or ``EXPORT_METRIC``; ``source``-is the Lua file relative to the build context, which the builder-embeds; ``upatch`` must be the upatch's name. The Lua API, the-snapshot layout the function receives and the records it must return-are in the telemetry document's *Decoders* section. ``shirudo upatch-info`` lists the decoders a built upatch carries.--Serializers and test programs-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--Two further program roles are recognised by name. A program named-``shirudo_serialize__<map>`` in ``SEC("syscall")`` is a serializer: the-exporter runs it on the target to render ``<map>`` into the-``shirudo_ser`` output map (``struct shirudo_serial_chunk`` from-``shirudo_serializer.h``) instead of reading the map directly, which-is how a map of structs or a per-CPU map becomes a flat record stream-(``testing/fixtures/serialized-metric.bpf.c`` is a complete example).-A program named ``shirudo_test__*`` in ``SEC("syscall")`` is a-test-run program: it is pinned but never attached, and exists for the-author's own checks. The builder refuses a serializer without the-output map, one that targets a reserved or missing map, and two for-the same map.--What a upatch cannot do-~~~~~~~~~~~~~~~~~~~~~~~--Nothing a upatch loads can introduce unsigned code, and nothing it does-is hidden from the operator: every load and unload is measured. A-upatch does what its author wrote, within the kernel's verifier;-shirudo guarantees provenance, not correctness. Test on a kernel like-the target's before signing for a fleet.--3) Building and signing--------------------------On the operator::-- shirudo build shield.bpf.c- shirudo build shield.bpf.o -o shield.upatch- shirudo build --unload shield --payload-sha256 <64 hex>--``shirudo build`` dispatches to ``shirudo-build``, which compiles with-``clang -target bpf -O2 -g`` when given a ``.bpf.c``, generates the-signed loader, signs it with the operator key and writes the-container. The output defaults to the input name with ``.c`` or ``.o``-replaced by ``.upatch``, next to the input; ``--unload`` writes-``<name>.unload.upatch`` in the current directory. Options:--``--name <name>``- The upatch name when it is not the file's base name.--``--keys-dir <dir>``, ``--key <pem>``, ``--cert <der>``- Where the signing material is; the default is- ``/var/lib/shirudo/keys`` or ``SHIRUDO_KEYS_DIR``. The- `key-lifecycle <key-lifecycle.rst>`__ guide covers the keys.--``--vmlinux <vmlinux.h>``- The kernel headers to compile against when the default- ``vendor/linux/vmlinux.h`` is not the target kernel's.--``--extra-cflags '<flags>'``- Passed to clang.--``--emit-artifacts``- Keeps the compiled ``.bpf.o`` next to the ``.upatch``.--``--payload-sha256 <hex>`` (``--unload`` only)- The payload hash the unload directive must find on the pin. When- omitted it is read from the local archive- ``/var/lib/shirudo/upatches/<name>.upatch`` and, failing that, left- all-zero, which makes the target skip the payload check. Always- give it when the directive leaves the operator.--Review the result before it leaves the operator::-- shirudo upatch info shield.upatch- shirudo upatch info --json shield.upatch--``info`` is an offline view: header, sections, attach metadata and the-signed decoders. The signing key is never needed on a target, and the-operator never touches a keyring or a TPM.--4) Testing on a target-------------------------A target that ran ``shirudo init`` loads a local file with::-- sudo shirudo upatch load shield.upatch --report=-- sudo shirudo upatch get shield- sudo shirudo upatch map shield counters- sudo shirudo upatch unload shield.unload.upatch --report=---``--report=<path>`` (``-`` for stdout) writes the JSON report the-architecture document describes under *Failure reporting*: the phase-reached, the category, the verifier log when the verifier spoke, and-the register value after the operation. ``upatch get`` shows the-program as the kernel loaded it, which is the thing to compare with-the source. Two options matter when scripting against a target:--``--expect-chain <hex>``- The register value the operation must find first, from ``shirudo- attest predict`` or the last report; a disagreement refuses- ``tampered`` without loading anything.--``--expect-version-id <id>``- The target's ``SHIRUDO_VERSION_ID`` (``shirudo version- --version-id``), to catch an operator and a target of different- builds.--``--no-precheck`` skips the state check that guards a load; it exists-for tests and ``init``'s own boot-restore, not for operation.--5) Packaging---------------A package is a directory with a ``<name>.bee`` Beefile next to the sources::-- example-shields/- ├── example-shields.bee- └── shield.bpf.c--The ``.bee`` suffix names the package definition. ``bpm build`` writes-the versioned package archive as ``<name>-<version>.bee`` and stores the-definition inside that archive under the member name ``Beefile``. Pass-the local definition with ``-f``; the legacy default filename-``Beefile`` remains accepted when ``-f`` is omitted.--Example ``example-shields.bee``::-- [package]- name = "example-shields"- description = "Example shields for the fleet"- license = "GPL-2.0 OR BSD-2-Clause"- authors = ["Example Org"]-- [[files]]- source = "decoders/counters.lua"- target = "decoders/counters.lua"-- [[upatches]]- source = "shield.bpf.c"- load_target = "upatches/shield.upatch"- unload_target = "upatches/shield.unload.upatch"-- [upatches.tree]- id = "shield"- load_artifact = "upatches/shield.upatch"- unload_artifact = "upatches/shield.unload.upatch"-- [upatches.tree.selector]- kernel_release_prefix = ["7.3.0-rc5"]- kernel_build_id = ["534043106db415bc0a983a3393e06c81b431bd39"]- architecture = ["x86_64"]-- [upatches.tree.selector.kconfig]- CONFIG_E1000 = ["y", "m"]-- [upatches.tree.selector.labels]- env = ["prod", "canary"]--``[package]``- ``name`` (also the package file's base name), ``description``,- ``license`` and ``authors``, which document the Beefile and are- not copied into the package; its README is the ``README.md``- beside the Beefile, when there is one.--``[[files]]``- Files copied into the package as they are: headers, decoders,- reproducers, generated tables. ``target`` defaults to ``source``.--``[[upatches]]``- One entry per upatch to build and sign. ``source`` is the BPF- source or object; ``load_target`` and ``unload_target`` name the- artifacts inside the package (the defaults derive from the- source name). The unload directive is generated with the built- artifact's payload hash, so a package always ships both halves.--``[upatches.tree]`` and its selector- Optional; present when the entry is to be published to a upatch- tree. ``id`` is the operation's identity across generations, the- two artifact fields name the package members, and the selector- says where the entry applies: kernel release prefixes, kernel- build IDs (``/sys/kernel/notes``), architectures, Kconfig values- and node labels, all as lists of accepted values; a node matches- when it satisfies every key given. An entry without a selector- applies everywhere.--``upatches/kernel-cve/kernel-cve.bee`` in the tree is a worked example-with one entry per CVE shield, and-``upatches/kernel-obs/Beefile`` one with-decoders and shared headers. Build and inspect::-- shirudo bpm build ./example-shields --version 1.0.0 \- -f ./example-shields/example-shields.bee \- --keys-dir /var/lib/shirudo/keys- shirudo bpm info ./example-shields-1.0.0.bee--``bpm build`` is an operator-only command. ``shirudo`` exposes it only-when it can resolve ``shirudo-build``; an installed operator package-provides the helper. From a checkout, set ``SHIRUDO_BUILD`` to-``tools/shirudo-build/shirudo-build`` or put both that directory and the-checkout root on ``PATH``. If ``shirudo bpm --help`` shows only target-commands, the helper was not found.--``bpm build [context] --version <v> [-f <name>.bee] [--keys-dir <dir>]``-``[--vmlinux <vmlinux.h>]``-builds and signs every entry through ``shirudo-build`` and writes-``<name>-<version>.bee``: a gzip tarball with the ``Beefile``, the-``upatches/*.upatch`` and ``*.unload.upatch`` artifacts, the-``README.md`` when there is one, the signing ``cert.der`` and a-``build-environment.json`` recording the toolchain. Versions are what-the registry index orders by and are immutable once published, so a-rebuilt package gets a new version.--``--vmlinux`` selects the BTF header used to compile BPF C entries. Its-path is resolved before the builder changes to the package directory.-Without it, ``bpm build`` checks ``./vmlinux.h`` and-``./vendor/linux/vmlinux.h`` from the command's working directory first,-then checks those paths from the package directory and the installed-shared header path.--Generated rodata-~~~~~~~~~~~~~~~~--An upatch may declare repeated ``[[upatches.rodata]]`` entries. Each-entry names a BTF variable, a default input file, and a ``generator`` and-``update`` command array. The generator runs during ``bpm build``; the-updater runs during ``bpm config update``. Commands are executed without-a shell from the Beefile's directory. Shirudo appends ``--input <path>---symbol <name> --output <path>``. The program writes the raw bytes for-that BTF variable to the output file, and the builder rejects a value-whose length differs from the BTF variable size.--The default input path is relative to the Beefile. Its override name is-the input basename up to its first dot: ``watch.list`` is named-``watch``. Multiple entries can share that input and one command-line-override. An override path is resolved relative to the caller's working-directory::-- shirudo bpm build ./upatches/kernel-obs --version 0.1.1 \- --rodata-input watch=./customer/watch.list--To change data without compiling BPF again, ``bpm config update`` takes-a previously built package. By default, it reads the Beefile, updater-programs, and declared input files from that package. This runs code-from the package on the operator, so omitting ``-f`` explicitly trusts-those packaged files. The upatch CMS signature does not authenticate the-Beefile or updater files. Pass ``-f`` to use a locally selected Beefile-and its updater files instead. It re-signs the changed upatches,-regenerates their unload directives, and writes a new package version::-- shirudo bpm config update \- --base-package oci://registry.example.com/shirudo/kernel-obs:0.1.0 \- --version 0.1.1 \- --rodata-input watch=./customer/watch.list--To use a local Beefile instead of trusting the packaged updater, pass-``-f`` explicitly::-- shirudo bpm config update \- --base-package ./kernel-obs-0.1.0.bee \- --version 0.1.1 -f ./upatches/kernel-obs/Beefile \- --rodata-input watch=./customer/watch.list--Generator and updater programs execute on the operator and must be-trusted. Include their source and any default input needed later with-``[[files]]`` entries in the Beefile. The target receives the signed-upatch and never executes these programs.--6) Publishing----------------Packages go to an OCI registry; the registry is untrusted and only-transports them. ``bpm push`` uploads the package and its certificate-and, given the signing material, adds the version to the registry's-signed index::-- shirudo bpm push ./example-shields-1.0.0.bee \- oci://registry.example.com/shirudo/example-shields \- --keys-dir /var/lib/shirudo/keys--The repository is ``oci://host/namespace/name`` without a tag. The-index lives at ``shirudo/bpm-index:stable`` in the same registry and-is a detached CMS signature by the operator key over the list of-packages and versions with their digests; a target verifies it against-the certificate it registered with the repository, and a package-against the digests the index records. An index that already lists-the version with other digests is refused, so a published version-cannot be replaced. Credentials and transport come from-``BPM_OCI_USERNAME`` and ``BPM_OCI_PASSWORD``, ``REGISTRY_AUTH_FILE``-or ``DOCKER_CONFIG``, ``BPM_OCI_CA_FILE`` for a private CA and-``BPM_OCI_SCHEME=http`` for a cleartext local registry. HTTPS uses TLS-1.3 and hybrid ML-KEM key exchange by default. To use a registry that-does not support hybrid groups, set ``tls.classical_hosts`` to an exact,-comma-separated DNS hostname list in the operator's root-managed-``/etc/shirudo/shirudo.conf``. For target pulls, put the key in the-immutable runtime image's ``etc/shirudo/shirudo.conf``; updateable config-images cannot set it. For example::-- tls.classical_hosts = ghcr.io,quay.io--Wildcards and IP addresses are rejected, and each redirect destination-must be listed separately. This setting does not change certificate-verification; shirudo warns if the negotiated group is not one of the-advertised hybrid groups. It applies to all shirudo libcurl clients,-including OTLP and S3. Classical key exchange does not provide-post-quantum transport confidentiality.--The upatch tree-~~~~~~~~~~~~~~~--A package is the unit an administrator installs by name. The tree is-the unit a fleet follows without naming anything: an append-only,-globally ordered sequence of ``add`` and ``delete`` operations, each-with a selector, published as one signed JSON document whose format-the architecture document gives under *Tree publication format*.-Appending a package's ``[upatches.tree]`` entries::-- shirudo bpm tree append ./example-shields-1.0.0.bee \- oci://registry.example.com/shirudo/tree --keys-dir /var/lib/shirudo/keys- shirudo bpm tree append ./example-shields-1.0.0.bee \- oci://registry.example.com/shirudo/tree --keys-dir /var/lib/shirudo/keys \- --op delete--``tree append`` fetches and verifies the current publication at-``<repository>:<reference>`` (``stable`` by default; a missing one-starts generation 1 with the package name as tree id, ``--tree-id``-overrides), pushes each artifact as an immutable manifest, appends one-operation per entry and republishes the next generation with the-previous manifest's digest as its parent. ``--op delete`` publishes-the entries' unload directives instead; a target accepts a delete only-for an id it loaded from the same tree. To withdraw a shield from the-fleet, append a delete; to replace it, append a delete and then an add-of the new version. Nothing is ever removed from the sequence, which-is what lets a verifier replay a node's projection.--7) On the target-------------------Packages by name-~~~~~~~~~~~~~~~~--Register the repository once with the certificate that must sign its-index, then install, upgrade and remove by name::-- sudo shirudo bpm config register add example oci://registry.example.com \- --key-file cert.der- sudo shirudo bpm repo update- sudo shirudo bpm install example/example-shields- sudo shirudo bpm install example/[email protected]- sudo shirudo bpm install oci://registry.example.com/shirudo/example-shields:1.0.0- sudo shirudo bpm list- sudo shirudo bpm upgrade- sudo shirudo bpm uninstall example-shields--``register add`` writes ``/etc/shirudo/bpm/registries.d/<name>`` with-``endpoint`` and ``key_file`` lines. ``repo update`` fetches and-verifies the index; ``shirudo-bpm-repo-update.timer`` runs it at boot-and ``shirudo-bpm-tree-sync.timer`` every minute, and they are the-only pull mechanism there is. ``install`` pulls, verifies, unpacks-and loads every upatch in the package, each load measured; ``upgrade``-moves installed packages to the newest indexed version; ``uninstall``-loads the package's unload directives, so a package can only be-removed through artifacts its operator signed. ``bpm info`` prints a-package's README from a local file or a reference before installing-it. ``bpm info upatches`` lists the package's load upatches, while-``--all`` includes unload directives. ``bpm info data`` decodes the-selected upatch's ``.rodata`` initial value and prints BTF-variable names, types and values with offsets into both the loader data-and the upatch file. It reads the packaged artifact without running its-loader. Add ``--json`` to emit the same information as JSON; integer-values remain JSON numbers, enums include their name and numeric value,-and values without a supported BTF representation are shown as hex.-The member path is relative to the package root, for example::-- shirudo bpm info upatches ./kernel-obs-0.1.bee- shirudo bpm info upatches ./kernel-obs-0.1.bee --all- shirudo bpm info data ./kernel-obs-0.1.bee upatches/kernel-obs.upatch- shirudo bpm info data ./kernel-obs-0.1.bee upatches/kernel-obs.upatch --json--The tree-~~~~~~~~--A target follows a tree when ``/etc/shirudo/bpm/upatch-tree.conf``-names it::-- endpoint = oci://registry.example.com/shirudo/tree- reference = stable--and ``/etc/shirudo/node.labels`` holds the node's labels, one-``key=value`` per line, for the selectors to match. Then::-- sudo shirudo bpm tree sync --dry-run- sudo shirudo bpm tree sync --report=---``tree sync`` fetches the publication, verifies the signature and the-sequence continuity against the state it kept under-``/var/lib/shirudo/bpm/upatch-tree/``, evaluates every unseen-operation's selector against ``uname``, the kernel build ID,-``/proc/config.gz`` and the node labels, and applies the matching ones-in sequence order: an ``add`` fetches the artifact (once; the cache is-keyed by layer digest) and loads it, a ``delete`` fetches the unload-directive and unloads. Each applied operation is measured as a-``tree_op`` event, and the node's projection root enters the next-boot's ``init`` event, so ``shirudo attest predict`` can be given the-tree state to predict the register. ``--dry-run`` shows what would-apply; the timer runs the real thing every minute. A node that stops-matching an operation it applied does not unload it: removal is always-an explicit ``delete``.--Verifying what landed-~~~~~~~~~~~~~~~~~~~~~--``shirudo status`` lists the loaded set with the hook each upatch-attached to and ``shirudo upatch list`` flags drift between the-archive and the live pins. The operator's view is ``shirudo attest``-on the target and ``shirudo attest verify`` against ``shirudo attest-predict``, which takes the installed artifacts and the tree state and-computes the register value a healthy target must certify; the-`tpm <tpm.rst>`__ document describes both.--8) Releasing a mitigation----------------------------In order, for a fix the fleet should carry within the hour:--1. Write the shield against the fix, build it against the BTF of each- kernel generation in the fleet, load it on a test target of each- and read ``upatch get`` and the report.-2. Give every entry a selector that names the kernel generation and- the Kconfig the shield depends on; a shield that attaches to a- function the kernel does not have fails at load, so narrow- selectors are cheaper than failing nodes.-3. ``bpm build`` with a new version, ``bpm info`` to read the README- a target will show, ``bpm push`` so that named installation works,- ``bpm tree append`` so that the fleet pulls it on the next sync.-4. Record the expected register with ``shirudo attest predict`` for- each kernel generation's installed set and verify a sample of- targets with ``shirudo attest verify``.-5. To withdraw, ``bpm tree append --op delete``; the fleet unloads on- its next sync, every unload measured.diff --git a/Documentation/upatches/attach-kinds.rst b/Documentation/upatches/attach-kinds.rstnew file mode 100644index 00000000..56052a88--- /dev/null+++ b/Documentation/upatches/attach-kinds.rst@@ -0,0 +1,355 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: upatch authors++Attach kinds+============++The section name of a program decides where it attaches. ``shirudo build``+reads it, refuses the sections below the table, and records the attach+kind and target in the signed attach metadata. After the signed loader+has created the programs, ``shirudo upatch load`` attaches each one, checks+the link against the metadata and pins it.++.. list-table::+ :header-rows: 1+ :widths: 27 18 33 22++ * - Section+ - Program type+ - Attached by+ - Target kernel needs+ * - ``fentry/<function>``, ``fentry.s/<function>``+ - tracing+ - ``BPF_RAW_TRACEPOINT_OPEN``+ - the base requirements+ * - ``fexit/<function>``, ``fexit.s/<function>``+ - tracing+ - ``BPF_RAW_TRACEPOINT_OPEN``+ - the base requirements+ * - ``fmod_ret/<function>``, ``fmod_ret.s/<function>``+ - tracing+ - ``BPF_LINK_CREATE``, ``BPF_MODIFY_RETURN``+ - ``CONFIG_FUNCTION_ERROR_INJECTION`` for functions marked for error+ injection+ * - ``lsm/<hook>``, ``lsm.s/<hook>``+ - LSM+ - ``BPF_LINK_CREATE``, ``BPF_LSM_MAC``+ - the base requirements+ * - ``tp_btf/<tracepoint>``+ - tracing+ - ``BPF_RAW_TRACEPOINT_OPEN``+ - the base requirements+ * - ``kprobe/<symbol>``, ``kprobe/<symbol>+<offset>``+ - kprobe+ - ``perf_event_open`` on the kprobe PMU, ``BPF_LINK_CREATE``,+ ``BPF_PERF_EVENT``+ - ``CONFIG_KPROBES``, ``CONFIG_KPROBE_EVENTS``+ * - ``kretprobe/<symbol>``+ - kprobe+ - as ``kprobe``, with the return-probe bit set+ - ``CONFIG_KPROBES``, ``CONFIG_KPROBE_EVENTS``+ * - ``uprobe.multi/<path>:<glob>``+ - kprobe+ - ``BPF_LINK_CREATE``, ``BPF_TRACE_UPROBE_MULTI``,+ ``BPF_F_UPROBE_MULTI_PATH_FD``+ - ``CONFIG_UPROBE_EVENTS``+ * - ``cgroup_skb/ingress``, ``cgroup_skb/egress``+ - cgroup skb+ - ``BPF_LINK_CREATE`` on ``/sys/fs/cgroup``,+ ``BPF_CGROUP_INET_INGRESS`` or ``BPF_CGROUP_INET_EGRESS``+ - ``CONFIG_CGROUP_BPF``, cgroup v2 at ``/sys/fs/cgroup``+ * - ``netfilter``+ - netfilter+ - ``BPF_LINK_CREATE``, ``BPF_NETFILTER``, IPv6 pre-routing+ - ``CONFIG_NETFILTER``, ``CONFIG_NETFILTER_BPF_LINK``+ * - ``syscall``, named ``shirudo_serialize__<map>``+ - syscall+ - not attached, run by ``shirudo upatch map``+ - the base requirements+ * - ``syscall``, named ``shirudo_test__<id>``+ - syscall+ - not attached, run once at load+ - the base requirements++The base requirements are the kernel options shirudo itself needs, listed+in :doc:`/operate/system-requirements`. They include BPF trampolines, BTF+and the BPF LSM, which is why the BTF-based kinds need nothing more.++Every attached program becomes one link pinned at+``/run/shirudo/bpffs/upatches/<name>/link`` when the upatch has one attach+program, and at ``link_0``, ``link_1`` and so on, in the order of the+object, when it has several. ``<name>`` has every ``.`` written as ``~d``.++fentry and fexit+----------------++``fentry`` runs at the entry of a kernel function with its arguments,+``fexit`` at its return with the arguments and the return value. Write+the program with ``BPF_PROG()`` and the function's parameters. The+verifier checks the prototype against the kernel's BTF.++The signed loader looks the function up in the target's BTF and loads the+program with that BTF id as its attach target. shirudo then calls+``BPF_RAW_TRACEPOINT_OPEN`` with no name, so the kernel attaches at the+BTF id the program carries. A function that is not in the target's BTF,+often because the compiler inlined it, fails inside the loader, as+``verifier_rejected`` in phase ``payload_load``, and never reaches the+attach step.++``fentry.s`` and ``fexit.s`` declare sleepable programs. The kernel admits+them only on functions it allows to sleep in, such as those on its+error-injection list.++fmod_ret+--------++``fmod_ret`` runs at the entry of a function. A non-zero return skips the+function body, and the caller receives that value. This is the kind for a+shield that refuses a call before the vulnerable code runs.++shirudo attaches with ``BPF_LINK_CREATE`` and attach type+``BPF_MODIFY_RETURN``, without a fallback. The kernel admits ``fmod_ret``+only on ``security_*`` hooks, on system call entry points and on+functions marked for error injection or return modification. The+error-injection marks take effect only with+``CONFIG_FUNCTION_ERROR_INJECTION``. On any other function the load fails+in phase ``payload_load``. ``fmod_ret.s`` declares the sleepable variant.++lsm+---++``lsm/<hook>`` attaches a program to the LSM hook ``security_<hook>``+calls, for example ``lsm/file_open`` or ``lsm/socket_connect``. The+program receives the hook's arguments and the return value of the BPF LSM+programs that ran before it on the same hook. A non-zero return on a hook+that returns ``int`` refuses the operation. ``lsm.s/<hook>`` declares a+sleepable program, which the kernel admits only on hooks it lists as+sleepable.++shirudo attaches with ``BPF_LINK_CREATE`` and ``BPF_LSM_MAC``. Every+target that runs shirudo has the BPF LSM active, because shirudo's own+enforcement programs are LSM programs.++tp_btf+------++``tp_btf/<tracepoint>`` attaches to a kernel tracepoint, for example+``tp_btf/sched_process_exec``, and receives the tracepoint's raw+arguments with their BTF types. Tracepoints are stable observation points+that the kernel maintains on purpose.++The loader resolves the tracepoint by BTF, and shirudo attaches with+``BPF_RAW_TRACEPOINT_OPEN`` as for ``fentry``.++kprobe and kretprobe+--------------------++``kprobe/<symbol>`` and ``kretprobe/<symbol>`` attach at the entry or the+return of any kernel function that kallsyms lists, whether or not it is in+BTF. ``kprobe/<symbol>+<offset>`` probes an instruction inside the+function. The offset is decimal or ``0x`` hexadecimal. A leading zero is+refused rather than read as octal, and a ``kretprobe`` takes no offset.+The program reads its arguments from ``struct pt_regs``, so the source+defines the ``__TARGET_ARCH_*`` macro for ``bpf_tracing.h``.++shirudo reads the kprobe PMU's type from+``/sys/bus/event_source/devices/kprobe/type`` and, for a return probe, the+return-probe bit from ``.../kprobe/format/retprobe``, opens a perf event+for the symbol and offset, and attaches the program to it with+``BPF_LINK_CREATE`` and ``BPF_PERF_EVENT``.++A kprobe may call ``bpf_override_return()`` to refuse a call. The kernel+allows that only at the entry of a function on its error-injection list+and with ``CONFIG_BPF_KPROBE_OVERRIDE``. Elsewhere the kernel refuses+the link, and the load fails in phase ``link_create``.++uprobe.multi+------------++``uprobe.multi/<path>:<glob>`` attaches to the entry of every function in+a userspace binary whose symbol matches the glob, in every process, for+example ``SEC("uprobe.multi//usr/bin/example:*Func")``. ``<path>`` is+absolute. The glob has libbpf's syntax: ``*`` matches any sequence and+``?`` one character.++This kind is resolved on the operator host. The builder opens the binary+at ``<path>``, matches the glob against its function symbols, converts the+matches to sorted file offsets and records them with the binary's GNU+build ID in the signed metadata. It refuses a glob that matches nothing+and a binary without a build ID.++On the target, shirudo opens ``<path>``, requires a regular file, opens it+again through ``/proc/self/fd`` and compares device and inode, checks that+every offset lies inside the file, and compares the build ID. A different+binary fails with ``binary_mismatch`` in phase ``target_verify``, before+any BPF is loaded. shirudo keeps that descriptor open and attaches with+``BPF_LINK_CREATE``, ``BPF_TRACE_UPROBE_MULTI`` and+``BPF_F_UPROBE_MULTI_PATH_FD``, so the probes land in the inode it checked,+not in whatever the path names later. There is no path fallback.++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Limit+ - Value+ * - path+ - absolute, shorter than 4096 bytes+ * - build ID+ - 1 to 64 bytes+ * - offsets per program+ - 1 to 1,048,576+ * - glob+ - one pattern, without ``,`` or ``|`` alternation++cgroup_skb+----------++``cgroup_skb/ingress`` and ``cgroup_skb/egress`` see every IP packet that+a socket on the host receives or sends, as a ``struct __sk_buff``. The+program returns 1 to pass the packet and 0 to drop it.++shirudo opens ``/sys/fs/cgroup`` and attaches with ``BPF_LINK_CREATE``+and ``BPF_CGROUP_INET_INGRESS`` or ``BPF_CGROUP_INET_EGRESS``, so the link+sits on the root of the unified cgroup hierarchy. The kernel runs every+program attached there and drops a packet if one of them says so.++netfilter+---------++``netfilter`` attaches a program as a netfilter hook for IPv6 at+``NF_INET_PRE_ROUTING`` with priority ``NF_IP6_PRI_RAW_BEFORE_DEFRAG``+(-450). The program runs before connection tracking and before IPv6+defragmentation, so it sees fragments as they arrive. It receives a+``struct bpf_nf_ctx`` and returns ``NF_ACCEPT`` or ``NF_DROP``.++shirudo fixes the family, hook and priority. The section name carries+none of them. A shield that needs another family or hook is written as a+``cgroup_skb`` or ``lsm`` program.++Programs that attach nowhere+----------------------------++Two roles are recognized by the program's name, and both must be in+``SEC("syscall")``. Any other ``syscall`` program is refused.++``shirudo_serialize__<map>``+ Renders ``<map>`` into records for export. shirudo pins it at+ ``serializers/<map>`` under the upatch's pin directory, and+ ``shirudo upatch map`` runs it with ``BPF_PROG_TEST_RUN``. The upatch+ must also define the ``shirudo_ser`` output map. One serializer per+ map. :doc:`maps-arenas-serializers` describes the interface.+``shirudo_test__<id>``+ Pinned as ``test`` and run once with ``BPF_PROG_TEST_RUN`` and a+ zeroed 16-byte context, after all attachments. A negative return fails+ the load. At most one per upatch.++The LSM allows ``BPF_PROG_TEST_RUN`` from userspace only to tasks with+shirudo's runtime authority, so root cannot run a pinned serializer or+test-run program itself.++Refused sections+----------------++``shirudo build`` refuses these sections with the message shown, before+it generates a loader.++.. list-table::+ :header-rows: 1+ :widths: 40 60++ * - Section+ - Message+ * - ``kprobe``, ``kretprobe`` without a symbol, ``kprobe.multi*``,+ ``kretprobe.multi*``+ - ``unsupported kprobe section '<section>'; use kprobe/<symbol> or+ kretprobe/<symbol>``+ * - ``uprobe``, ``uprobe/*``, ``uretprobe*``, other ``uprobe.*`` forms+ - ``unsupported uprobe section '<section>'; use+ uprobe.multi//absolute/path:function_glob (entry probes only)``+ * - ``sk_skb``, ``sk_skb/*``+ - ``unsupported sk_skb section '<section>'; supported network packet+ sections are cgroup_skb/ingress, cgroup_skb/egress, and netfilter``+ * - ``socket``, ``socket_filter`` and their ``/`` forms+ - ``unsupported socket filter section '<section>'; Shirudo upatches+ require a pinnable bpf_link lifecycle``+ * - ``cgroup_skb``, ``cgroup/skb``, other ``cgroup_skb/*``+ - ``unsupported cgroup_skb section '<section>'; use cgroup_skb/ingress+ or cgroup_skb/egress``+ * - ``fmod_ret``, ``fmod_ret.s`` without a function+ - ``unsupported fmod_ret section '<section>'; use fmod_ret/<symbol> or+ fmod_ret.s/<symbol>``+ * - every other section, ``tp/``, ``raw_tp/``, ``xdp`` and ``tc`` among+ them+ - ``unsupported section '<section>'; supported are fentry, fexit,+ fmod_ret, lsm, tp_btf, kprobe, kretprobe, uprobe.multi, cgroup_skb+ and netfilter``+ * - ``syscall`` with another program name+ - ``SEC("syscall") program '<name>' must be named shirudo_test__<id>``++Attach-scope check+------------------++The site a kprobe, uprobe, cgroup or netfilter program attaches at depends+on state that root can arrange on the target: the mount of+``/sys/fs/cgroup``, the network namespace of the loading process, the+sysfs file that names the kprobe PMU. Before shirudo pins a link, it asks+the kernel about the link and compares the answer with the signed+metadata:++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Kind+ - The kernel must report+ * - ``cgroup_skb``+ - a cgroup link on cgroup id 1, the root of the unified hierarchy+ * - ``netfilter``+ - a netfilter link for IPv6, pre-routing, priority -450, created by a+ task in the initial network namespace+ * - ``kprobe``, ``kretprobe``+ - a perf event link of the kprobe or kretprobe type, with the same+ symbol and offset+ * - ``uprobe.multi``+ - a uprobe multi link with as many offsets as recorded+ * - ``fmod_ret``+ - a tracing link with attach type ``BPF_MODIFY_RETURN``+ * - ``fentry``, ``fexit``, ``lsm``, ``tp_btf``+ - a tracing or raw tracepoint link++On a mismatch shirudo closes the link, which detaches it, removes the pins+this load made and fails with ``attach_scope_mismatch`` in phase+``link_create``.++Missing attach targets+----------------------++``attach_target_missing`` reports a site that does not exist on this+target: a ``kprobe`` symbol that kallsyms does not list, often because the+module that holds it is not loaded, a kernel without the kprobe PMU, a+missing ``/sys/fs/cgroup``, or a ``uprobe.multi`` binary that is not+there. ``shirudo upatch load`` exits with status 2 for it, not 1.++The BTF-based kinds never report it. ``fentry``, ``fexit``, ``fmod_ret``,+``lsm`` and ``tp_btf`` targets are looked up inside the signed loader, and+a missing one fails the load as ``verifier_rejected`` in phase+``payload_load`` with errno ``ENOENT``.++``bpm tree sync`` treats an ``add`` that fails with+``attach_target_missing`` as applied: it logs ``bpm tree: skipped <id>:+module not loaded``, measures the operation and moves past it, and does+not retry it when the module loads later. ``bpm install`` and ``bpm+upgrade`` fail and roll back instead. Narrow tree selectors keep an entry+away from targets that lack its site.++Related+-------++- :doc:`concepts` for the roles, pins and names.+- :doc:`debugging` for every failure category of a load.+- :doc:`/internals/kernel-interfaces` for the system calls in detail.diff --git a/Documentation/upatches/beefile.rst b/Documentation/upatches/beefile.rstnew file mode 100644index 00000000..e718971a--- /dev/null+++ b/Documentation/upatches/beefile.rst@@ -0,0 +1,362 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: upatch authors++Beefile reference+=================++A Beefile describes a package: its name, the files it ships, the upatches+``shirudo bpm build`` compiles and signs into it, and the entries+``shirudo bpm tree append`` publishes to an upatch tree. ``bpm build``+reads ``<context>/Beefile``, or the file given with ``-f``, and treats+the directory that holds it as the package directory. Every path in the+Beefile is relative to that directory. The package archives the Beefile+unchanged as its ``Beefile`` member. :doc:`/reference/cli/bpm` lists the+command options and :doc:`/reference/formats/bpm-formats` the archive+format.++Syntax+------++A Beefile is a small subset of TOML, read line by line.++- Each line holds one table header, one ``key = value`` pair, a comment+ or nothing.+- A value is a quoted string or an array of quoted strings on the same+ line. A ``"..."`` string takes the escapes ``\n``, ``\r``, ``\t``,+ ``\\`` and ``\"``; a ``'...'`` string takes none.+- ``#`` starts a comment outside a string.+- There are no numbers, booleans, inline tables or values that span+ lines.+- ``[[upatches.rodata]]`` and the ``[upatches.tree]`` tables belong to the+ ``[[upatches]]`` entry above them. Write an entry's own keys before its+ first sub-table: a key after ``[upatches.tree]`` belongs to that table.++``bpm build`` reports every error in the file, of syntax or of content,+as ``bpm build: <file> is not a valid Beefile``, without a line number.++Keys+----++``[package]``+~~~~~~~~~~~~~++.. list-table::+ :header-rows: 1+ :widths: 18 14 10 58++ * - Key+ - Type+ - Required+ - Rules+ * - ``name``+ - string+ - yes+ - The package name: 1 to 127 characters of letters, digits, ``.``,+ ``_`` and ``-``, starting with a letter or a digit. The archive is+ ``<name>-<version>.bee``.+ * - ``description``+ - string+ - no+ - Read and ignored.+ * - ``license``+ - string+ - no+ - Read and ignored.+ * - ``authors``+ - array of strings+ - no+ - Read and ignored.++A ``README.md`` in the package directory is added to the package, and+``shirudo bpm info`` prints it.++``[[files]]``+~~~~~~~~~~~~~++One table per file to ship as it is: headers, generator programs, lists,+reproducers.++.. list-table::+ :header-rows: 1+ :widths: 18 14 10 58++ * - Key+ - Type+ - Required+ - Rules+ * - ``source``+ - string+ - yes+ - A regular file inside the package directory. Not absolute, no+ ``..`` component, and its real path must not leave the directory.+ * - ``target``+ - string+ - no+ - The member path in the package. Default: ``source``. Not absolute,+ no empty, ``.`` or ``..`` component.++``[[upatches]]``+~~~~~~~~~~~~~~~~++One table per upatch to build. ``bpm build`` compiles a ``.bpf.c``,+signs the object into a load artifact and generates its unload directive+from the artifact's payload digest, so a package always ships both.++.. list-table::+ :header-rows: 1+ :widths: 18 14 10 58++ * - Key+ - Type+ - Required+ - Rules+ * - ``source``+ - string+ - yes+ - A ``.bpf.c``, ``.bpf.o`` or ``.o`` file inside the package+ directory, under the same rules as a file ``source``. The upatch+ name is its base name without ``.bpf.c``, ``.bpf.o`` or ``.o``.+ There is no key to set another name.+ * - ``type``+ - string+ - no+ - ``bpf``, the default and the only value, in any case.+ * - ``load_target``+ - string+ - no+ - The member path of the load artifact. Default:+ ``upatches/<base>.upatch``, with ``<base>`` the source's base name+ without ``.bpf.c`` or ``.bpf.o``, or without its last extension.+ * - ``unload_target``+ - string+ - no+ - The member path of the unload directive. Default:+ ``upatches/<base>.unload.upatch``.++Keep both targets directly under ``upatches/``. On a target, ``bpm+install`` loads every file in the package's ``upatches/`` directory whose+name contains ``.upatch`` but not ``.unload.upatch``, in name order, and+``bpm uninstall`` applies every ``upatches/*.unload.upatch`` in reverse+name order. ``bpm upgrade`` applies the old version's unload directives+before it loads the new version, and pairs ``<x>.unload.upatch`` with+``<x>.upatch`` to restore the old version when the new one fails. An+artifact elsewhere is shipped but never loaded.++``bpm build`` compiles a ``.bpf.c`` as ``shirudo build`` does, see+:doc:`/reference/cli/build`, but in the package directory. It finds+libbpf's headers in+``./vendor/libbpf`` there, or in the operator package's+``/usr/share/shirudo/bpf/include``, and ``vmlinux.h`` at ``--vmlinux``,+then at ``./vmlinux.h`` and ``./vendor/linux/vmlinux.h`` of the directory+``bpm build`` runs in, then of the package directory, then at the+installed path. ``bpm build`` passes no extra compiler flags.++``[[upatches.rodata]]``+~~~~~~~~~~~~~~~~~~~~~~~++Generated data for one ``const`` variable in the upatch's ``.rodata``. A+generator program produces the variable's bytes from an input file at+``bpm build``, and an updater program does the same at ``bpm config+update``, which re-signs the upatch without compiling it again.++.. list-table::+ :header-rows: 1+ :widths: 18 14 10 58++ * - Key+ - Type+ - Required+ - Rules+ * - ``symbol``+ - string+ - yes+ - The variable's name in the object's BTF, at most 127 characters.+ * - ``input``+ - string+ - yes+ - The default input, a regular file inside the package directory,+ not absolute, without ``..``.+ * - ``generator``+ - array of strings+ - yes+ - The command for ``bpm build``, 1 to 16 arguments.+ * - ``update``+ - array of strings+ - yes+ - The command for ``bpm config update``, 1 to 16 arguments.++The first argument of a command that contains a ``/``, or else the+second, must be a regular file inside the package directory, such as+``["python3", "gen_watch_rodata.py"]``. shirudo runs the command without+a shell, with ``execvp``, in the package directory, and appends ``--input+<path> --symbol <symbol> --output <path>``. The program writes the+variable's raw bytes to the output file. A result whose length differs+from the variable's size fails the build.++An input is named by its file name up to the first dot: ``watch.list``+is ``watch``. ``--rodata-input <name>=<path>`` replaces the input of every+entry with that name for one build. An override for a name that no entry+has fails. Entries that share a name must name the same input.++The generator and the updater run on the operator host with the+operator's rights. The target receives only the signed result. Without+``-f``, ``bpm config update`` takes the Beefile and the updater from the+base package and runs them. It also trusts the base package's unsigned+header to locate ``.rodata`` before it re-signs, so run it only on a base+package you built or verified yourself.++``[upatches.tree]``+~~~~~~~~~~~~~~~~~~~++Optional. Present when ``bpm tree append`` is to publish the upatch as a+tree operation.++.. list-table::+ :header-rows: 1+ :widths: 18 14 10 58++ * - Key+ - Type+ - Required+ - Rules+ * - ``id``+ - string+ - yes+ - The operation's identity across generations. A valid upatch name,+ and equal to the upatch's name, the source's base name:+ ``bpm tree append`` refuses an artifact whose name differs, and so+ does the target.+ * - ``load_artifact``+ - string+ - no+ - The member that an ``add`` publishes. Default: ``load_target``.+ * - ``unload_artifact``+ - string+ - no+ - The member that a ``delete`` publishes. Default:+ ``unload_target``.++``[upatches.tree.selector]``+~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Optional. Says where the operation applies. Every key holds an array of 1+to 16 accepted values, and each key may appear once.++.. list-table::+ :header-rows: 1+ :widths: 25 75++ * - Key+ - Matches when+ * - ``kernel_release_prefix``+ - ``uname -r`` starts with a value and continues with ``.``, ``-`` or+ nothing: ``7.2`` matches ``7.2.0`` and ``7.2-rc1``, not ``7.20``.+ * - ``kernel_build_id``+ - the running kernel's GNU build ID from ``/sys/kernel/notes``, in+ lowercase hex, equals a value. A kernel without one never matches.+ * - ``architecture``+ - ``uname -m`` equals a value, such as ``x86_64``, ``aarch64`` or+ ``riscv64``.++``[upatches.tree.selector.kconfig]``+ Up to 64 keys, each a Kconfig option, once, with its accepted values,+ such as ``CONFIG_IPV6 = ["y", "m"]``. An option that is not set matches+ ``"n"``. The target reads ``/proc/config.gz`` and, when that is+ missing or names none of the options, ``/boot/config-<release>``. A+ target with neither does not match.+``[upatches.tree.selector.labels]``+ Up to 64 keys, each a node label, once, with its accepted values, such+ as ``env = ["prod", "canary"]``. The target reads its labels from the+ signed config image's ``etc/shirudo/node.labels``. A target without+ labels does not match.++A target matches a selector when it matches every key given, and a key+when it matches one of its values. An entry without a selector applies+everywhere. A target that does not match an operation passes over it and+never comes back to it, also after a kernel upgrade or a label change.++Unknown keys and tables+-----------------------++.. list-table::+ :header-rows: 1+ :widths: 50 50++ * - Where+ - Result+ * - an unknown key in ``[package]``, ``[[files]]``, ``[[upatches]]``,+ ``[[upatches.rodata]]`` or ``[upatches.tree.selector]``+ - refused+ * - an unknown array of tables, ``[[name]]``+ - refused+ * - an unknown table under ``upatches.tree``+ - refused, because a selector the builder cannot read would widen+ the rollout+ * - an unknown key in ``[upatches.tree]``+ - ignored, as metadata for newer publishers+ * - a key before the first table, or in a table with any other name+ - ignored++Limits and reserved names+-------------------------++.. list-table::+ :header-rows: 1+ :widths: 50 50++ * - Limit+ - Value+ * - ``[[files]]`` tables+ - 128+ * - ``[[upatches]]`` tables+ - 128+ * - ``[[upatches.rodata]]`` tables per upatch+ - 16+ * - arguments per ``generator`` or ``update`` command+ - 16+ * - values per selector key+ - 16+ * - keys in each of ``kconfig`` and ``labels``+ - 64+ * - length of a string in a selector or command+ - 255 bytes+ * - package version, ``--version``+ - 1 to 127 characters of letters, digits, ``.``, ``_``, ``-`` and+ ``+``, starting with a letter or a digit+ * - member path including ``<name>-<version>/``+ - 99 bytes, the limit of a ustar name+ * - ``.bee`` file+ - 256 MiB per member file++Every member path must be unique. ``Beefile``, ``README.md``,+``cert.der`` and ``build-environment.json`` are reserved for the members+``bpm build`` writes itself. A member path longer than the ustar limit+fails the build with ``bpm build: File name too long``.++Example+-------++``upatches/kernel-obs/Beefile`` declares one upatch with generated+``.rodata`` and ships its generators:++.. literalinclude:: ../../upatches/kernel-obs/Beefile+ :language: toml++``upatches/kernel-cve/kernel-cve.bee`` breaks these rules and is not a+model. Two of its load targets make member paths longer than 99 bytes+with any version, so ``bpm build`` fails. Its tree ids name the CVE+directories while its upatch names are the detectors' base names, so+``bpm tree append`` would refuse every entry. And its+``unload_artifact`` paths name members the package does not have.++Related+-------++- :doc:`publishing` for building, pushing and appending a package.+- :doc:`/reference/cli/bpm` for ``bpm build`` and ``bpm config update``.+- :doc:`/reference/formats/bpm-formats` for the archive, the index and the+ tree.diff --git a/Documentation/upatches/concepts.rst b/Documentation/upatches/concepts.rstnew file mode 100644index 00000000..20603953--- /dev/null+++ b/Documentation/upatches/concepts.rst@@ -0,0 +1,277 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: upatch authors++upatch concepts+===============++An upatch is the unit of BPF code that shirudo installs on a target. The+author writes an ordinary BPF object in C. ``shirudo build`` turns it into+a signed ``.upatch`` file, and the target loads that file through the one+path the kernel accepts from userspace: a signed loader. This page explains+what the author writes, what the build adds around it, what the target does+with it, and what an upatch cannot do.++BPF program+-----------++The author's side of an upatch is libbpf-style BPF C: programs in+``SEC()`` sections, maps in ``SEC(".maps")``, types from ``vmlinux.h``.+The smallest upatch the test suite builds is one ``fentry`` program:++.. code-block:: c++ // SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause+ #include "vmlinux.h"+ #include <bpf/bpf_helpers.h>+ #include <bpf/bpf_tracing.h>++ char _license[] SEC("license") = "Dual BSD/GPL";++ SEC("fentry/do_nanosleep")+ int BPF_PROG(shirudo_test_basic)+ {+ return 0;+ }++The license must be GPL-compatible. The kernel refuses an LSM program+that is not, and most tracing helpers are GPL-only. ``Dual BSD/GPL`` is+the project's choice and matches the ``GPL-2.0 OR BSD-2-Clause`` SPDX tag+of every file that is compiled into a BPF object.++The program reads kernel structures through CO-RE: clang records each+field access as a relocation against the types in ``vmlinux.h``, and the+target kernel resolves the relocations against its own BTF when the+program loads. CO-RE carries an upatch across builds of the same kernel+generation, not across kernels that removed or renamed what it reads. A+hard-coded offset signs as well as a CO-RE access and fails on the wrong+kernel in the same way. :doc:`/concepts/background/co-re-btf` explains the+mechanism.++The section name is the attach point. :doc:`attach-kinds` lists the+sections the builder accepts and how the target attaches each one.++Why the build wraps the program in a loader+-------------------------------------------++The author's programs cannot be signed as they are. Between the build+and the verifier their instructions change: map descriptors are patched+in, CO-RE relocations are resolved against the target's BTF, and kernel+symbol references are resolved. A signature over the built instructions+would not match what the kernel checks. The kernel's signed-BPF design+therefore signs a loader, a ``BPF_PROG_TYPE_SYSCALL`` program that does+those steps in the kernel, together with the data it loads. shirudo's LSM+admits no other ``BPF_PROG_LOAD`` from userspace than such a signed+loader.++``shirudo build`` compiles the source with clang, then runs libbpf's loader+generator over the object. The generator records every step that loading+the object takes, map creation, the BTF load, each program load with its+CO-RE relocation records and the lookup of its attach target, as the+instructions of a loader program. The author's program instructions, the+maps' initial values and the BTF become the loader's data. The build signs+the loader instructions followed by that data with the operator's ML-DSA-87+key and writes both, with the signature, into the ``.upatch`` file.++On the target, ``shirudo upatch load`` puts the data into a frozen array+map that only this loader can use, and passes the loader to+``BPF_PROG_LOAD`` with the signature and the ``.bpf`` keyring. The kernel+checks the signature over the instructions and the frozen map contents+before the verifier runs. Every instruction of the payload is inside the+signed data, so the one signature covers it.+:doc:`/internals/signed-loader` follows the path call by call, and+:doc:`/concepts/background/bpf-signing` describes the kernel side.++When the loader runs, it creates the maps and loads the programs from+kernel context and hands their descriptors back. It cannot attach them:+the generated loader creates no links, and a program running in the kernel+cannot pin anything to a file system. shirudo attaches each program from+userspace and pins the link, so the link survives the exit of the one-shot+command.++What the build signs besides the code+-------------------------------------++The ``.upatch`` header is not signed. Everything the target bases a+decision on is placed in signed sections appended to the loader's data,+where the loader never reads them but the signature covers them:++``NAME``+ The upatch name. The target refuses a file whose header name differs+ from the signed one.+``UPGM``+ The attach metadata of a load: for each program its role, its attach+ kind and, where the kind needs one, the target symbol, offset or+ uprobe binary. The builder derives it from the section names.+``UNLD``+ The payload digest an unload directive expects to find on the upatch+ it removes.+``DCDB``+ The Lua decoders the source declares, with their source text.++The header also carries ``payload_sha256``, the SHA-256 of the loader+instructions followed by the data. The target recomputes it and refuses a+mismatch, because that digest is what the pin records, what the+measurement register extends and what an unload directive is bound to.+:doc:`/reference/formats/upatch-format` gives every field.++What the target keeps+---------------------++A successful load leaves three things behind. The pins hold the programs+and maps in shirudo's private BPF file system. The archive copy at+``/var/lib/shirudo/upatches/<name>.upatch`` is what ``shirudo init``+restores on the next boot. The measurement register and the eventlog+record the load. The pins of one upatch live in one directory:++.. code-block:: none++ /run/shirudo/bpffs/upatches/<name>/+ link one attach program, or+ link_0, link_1, ... one per attach program, in object order+ test the test-run program, when there is one+ serializers/<map> one serializer program per map it renders+ maps/<map> the upatch's maps++``<name>`` is the upatch name with every ``.`` written as ``~d``, because+the BPF file system does not accept every dotted name. The directory+carries the payload digest in the ``security.bpf.shirudo.payload``+extended attribute, which unload compares against.++Maps whose names contain a dot are not pinned: these are libbpf's+``.rodata``, ``.data``, ``.bss`` and ``.kconfig``. Maps whose names start+with ``obs_i_`` are not pinned either, because that prefix marks state that+is private to the upatch. A map that cannot be pinned is logged and the load+stands without it.++Load directives and unload directives+-------------------------------------++A load directive, the ordinary ``.upatch``, carries programs and maps.+An unload directive carries no payload. ``shirudo build --unload <name>``+generates it from a small template that is built into the helper. It+holds the name of the upatch to remove in ``NAME`` and the payload digest+that upatch must have in ``UNLD``.++``shirudo upatch unload`` loads the directive's loader only so that the+kernel verifies its signature, and never runs it. It then compares the+signed digest with the payload attribute of the pin directory. A+different digest fails with ``payload_mismatch``, so a directive removes+the exact build its signer made it for and nothing else. When nothing of+that name is pinned, the result is ``already_unloaded`` and nothing is+measured.++Build every unload directive with ``--payload-sha256`` set to the digest+of the load it undoes. Without the option, the helper looks for an+archive copy under ``/var/lib/shirudo/upatches/`` on the host where it+runs and, failing that, signs an all-zero digest. No loaded upatch+carries an all-zero digest, so such a directive fails with+``payload_mismatch`` on every target where the upatch is loaded.++Names+-----++One name follows an upatch everywhere: the pin directory, the archive+file, the eventlog record and the target of its unload directive.++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Name+ - Rule+ * - upatch name+ - 1 to 255 characters of ``A-Z``, ``a-z``, ``0-9``, ``.``, ``_`` and+ ``-``, not starting with ``.``. The builder refuses anything else,+ and the target refuses it again at load.+ * - name from ``shirudo build``+ - The input's base name without ``.bpf.c``, ``.bpf.o`` or ``.o``.+ ``--name`` sets another.+ * - name in a package+ - The base name of the ``source`` in the Beefile, the same rule+ without an override. :doc:`beefile` has the details.+ * - tree id+ - Equal to the upatch name. :doc:`publishing` explains why.+ * - upatch with decoders+ - At most 63 characters, because the decoder manifest holds the+ upatch name in a 64-byte field.+ * - map+ - At most 15 characters. The kernel keeps 15 characters of a map+ name, and decoders and serializers name their map in a 16-byte+ field. ``shirudo_ser`` is reserved for serializer output.+ * - serializer+ - ``shirudo_serialize__<map>`` in ``SEC("syscall")``, one per map.+ * - test-run program+ - ``shirudo_test__<id>`` in ``SEC("syscall")``, at most one per+ upatch.+ * - loader program+ - The first 15 characters of the upatch name, with any character+ other than letters, digits, ``_`` and ``.`` replaced by ``_``, is+ the name the kernel records for the signed loader.++Programs, maps and decoders+---------------------------++A program has one of three roles, all recorded in the signed attach+metadata. An attach program is linked to the site its section names. A+serializer renders one map into records when the map is exported. A+test-run program runs once at load, right after the attachments, which is+how an upatch initializes state such as an arena before its first export.+A negative return from the test-run program fails the load.++An upatch that accumulates records keeps them in one BPF arena and ships a+serializer that walks them. :doc:`maps-arenas-serializers` explains why.+A map becomes a log record or a metric through a decoder, a Lua function+that the source declares in ``.rodata`` and the build signs into the+upatch. :doc:`decoders` shows how to write one.++What an upatch cannot do+------------------------++It cannot run code the operator did not sign. The kernel checks the+loader's signature against the sealed ``.bpf`` keyring before the verifier+runs, and the payload, the attach sites, the name and the decoders are all+part of the signed data. The limit is what a signature means: it shows who+built the upatch, not that the upatch is correct. A signed upatch does+whatever its source does within what the verifier allows for its program+type, which for ``fmod_ret``, ``lsm``, ``cgroup_skb`` and ``netfilter``+includes refusing calls and dropping packets. Test it on a kernel like the+target's before it ships.++It cannot attach anywhere other than where its signed metadata says.+Before shirudo pins a link, it compares what the kernel reports about the+link with the metadata: the link type and attach type, the kprobe symbol+and offset, the cgroup, the netfilter hook and network namespace, the+number of uprobe offsets. A mismatch unpins what the load made and fails+with ``attach_scope_mismatch``. For fentry, fexit, ``fmod_ret``, LSM and+``tp_btf`` programs the site is the BTF target the verifier bound at load.++It cannot use a program type that has no pinnable link. The builder+refuses socket filters, ``sk_skb``, ``xdp`` and every other section+outside the list in :doc:`attach-kinds`, because only a pinned link keeps+a program attached after the command exits and lets the unload path+detach it.++It cannot stay loaded unmeasured. A load whose archive copy or register+extend fails is undone, and ``init`` refuses to restore an archived upatch+the register does not cover.++It cannot be removed without the signer. A loaded upatch goes away through+a signed unload directive bound to its payload, or through a key+revocation in a signed config image, which purges the upatches of the+revoked key. shirudo's LSM programs refuse every userspace command that+detaches or replaces a link, and refuse removing a pin to every task+without shirudo's runtime authority. :doc:`/security/threat-model` lists+what remains.++Related+-------++- :doc:`kernel-fix-tutorial` takes one upatch from a kernel fix to a+ published package.+- :doc:`/reference/cli/build` for every ``shirudo build`` option.+- :doc:`/concepts/upatches-and-packages` for how upatches, packages and+ the tree relate.diff --git a/Documentation/upatches/debugging.rst b/Documentation/upatches/debugging.rstnew file mode 100644index 00000000..4ae090be--- /dev/null+++ b/Documentation/upatches/debugging.rst@@ -0,0 +1,257 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: upatch authors++Debug a failed load+===================++When ``shirudo upatch load`` or ``unload`` fails, its JSON report says+how far the operation got and why it stopped. This page shows how to get+the report, how to read the phase, the category and the verifier log, and+what to change for each failure.++Before you begin+----------------++- Root on the target where the load failed, and the ``.upatch`` file.+- The source and the ``vmlinux.h`` the upatch was built from, on the+ operator host.++Get the report+--------------++1. Load the upatch again with a report:++ .. code-block:: console++ target# shirudo upatch load --report=- <file>.upatch++ ``<file>`` is the upatch. ``--report=<path>`` writes the report to a+ file instead of standard output. Log lines, including the verifier log,+ go to standard error and to the journal. In the test VM, run+ ``shirudo-runtime`` instead of ``shirudo``.++ A failed load is undone: shirudo removes whatever it pinned, and a load+ that the measurement register did not record is taken back out. You can+ load again after every change.++2. Read three fields of the report: ``phase``, the step that failed,+ ``category``, the kind of failure, and ``errno_name``, the error the+ kernel or shirudo returned. ``message`` adds a short description.+ :doc:`/reference/failure-categories` defines every category and the+ exit status of each command.++ For an upatch that a package or the tree delivered, the same failure+ is in the journal:++ .. code-block:: console++ target# journalctl -t shirudo -p err++Find the cause+--------------++3. Look up the phase and the category. A load goes through the phases in+ this order and stops at the first failure.++ .. list-table::+ :header-rows: 1+ :widths: 20 24 56++ * - Phase+ - Category+ - Cause and what to do+ * - ``pre_flight``+ - ``version_mismatch``+ - ``--expect-version-id`` names another shirudo build than the+ target runs. Build with the target's version, or drop the+ option.+ * - ``pre_flight``+ - ``kernel_abi_unsupported``+ - The kernel's BTF lacks the signed-loader fields shirudo needs.+ ``message`` names the field. Boot a kernel that meets+ :doc:`/operate/system-requirements`.+ * - ``pre_flight``+ - ``keyring_missing``+ - ``shirudo init`` has not frozen a trust anchor this boot. The+ target is not initialized.+ * - ``pre_flight``+ - ``tampered``+ - The ``.bpf`` keyring is not the one ``init`` froze, shirudo's+ LSM link is not pinned, or the register is not the+ ``--expect-chain`` value. Do not retry. Follow+ :doc:`/operate/incident-tampered`.+ * - ``pre_flight``+ - ``eventlog_full``+ - The eventlog would grow past ``eventlog.max_bytes``. Nothing was+ loaded. The operator has to make room.+ * - ``parse``+ - ``parser_rejected``+ - The file is not a valid upatch, is an unload directive, has a+ name that is not signed or not allowed, a payload digest that+ does not match its content, or attach metadata that is missing+ or invalid. Rebuild it with ``shirudo build`` and check that you+ passed the right file.+ * - ``target_verify``+ - ``attach_target_missing``, ``binary_mismatch``,+ ``parser_rejected``, ``lsm_denied``+ - A ``uprobe.multi`` binary is missing, differs from the one the+ upatch was built against, is shorter than a recorded offset, or+ could not be read. Rebuild against the binary the target runs.+ * - ``signed_loader_load``+ - ``signature_rejected``+ - The signature does not verify against the ``.bpf`` keyring: the+ upatch was signed with a key the target did not enroll, or it+ changed after signing. Compare ``shirudo keys`` on the target+ with your certificate.+ * - ``signed_loader_load``+ - ``keyring_missing``+ - The keyring holds no key for the signer.+ * - ``signed_loader_load``+ - ``signature_unsupported``+ - The kernel cannot verify ML-DSA signatures, because it lacks+ ``CONFIG_CRYPTO_MLDSA``.+ * - ``signed_loader_load``+ - ``lsm_denied``+ - The LSM refused a BPF command, usually because the command did+ not run as shirudo's runtime binary.+ * - ``signed_loader_load``+ - ``verifier_rejected``+ - The verifier refused the loader itself. Read the verifier log.+ * - ``payload_load``+ - ``verifier_rejected``+ - The loader ran and failed: the verifier refused a payload+ program, a CO-RE relocation found no match, a BTF attach target+ does not exist, or a map could not be created. Read the+ verifier log and ``loader_return``.+ * - ``link_create``+ - ``attach_target_missing``+ - A ``kprobe`` symbol that kallsyms does not list, often in a+ module that is not loaded, a kernel without the kprobe PMU, or a+ missing ``/sys/fs/cgroup``. The command exits with 2.+ * - ``link_create``+ - ``attach_scope_mismatch``+ - The kernel attached somewhere else than the metadata names,+ because the command ran in another cgroup or network namespace+ or with a changed sysfs. Load from the host's initial+ namespaces.+ * - ``link_create``+ - ``kernel_abi_unsupported``, ``lsm_denied``, ``binary_mismatch``+ - The kernel does not support the attachment, the LSM refused it,+ or the uprobe binary changed.+ * - ``link_create``+ - ``unknown``+ - Any other error. ``EEXIST``: an upatch of the same name is+ loaded. Unload it first. ``EINVAL``: the kernel refused the+ attachment, such as ``bpf_override_return()`` outside an+ error-injection function. ``EADDRNOTAVAIL``: kallsyms lists the+ ``kprobe`` symbol more than once.+ * - ``persist``+ - ``unknown``+ - The archive copy could not be written. The load was undone.+ * - ``tpm_extend``+ - ``tampered``+ - The register refused the extend because it is not the one+ ``init`` bound. The load was undone. Treat it as an incident.+ * - ``tpm_extend``+ - ``tpm_error``+ - The TPM or the eventlog failed. When the extend itself failed,+ the load was undone.++ An unload reports these besides the shared ones:++ .. list-table::+ :header-rows: 1+ :widths: 20 24 56++ * - Phase+ - Category+ - Cause and what to do+ * - ``parse``+ - ``parser_rejected``+ - The file is a load directive, or its target name is not signed.+ * - ``pin``+ - ``payload_mismatch``+ - The loaded upatch has another payload digest than the directive+ expects, or its recorded digest cannot be read. Build the+ directive with ``--payload-sha256`` set to the digest of the+ loaded build, from ``shirudo upatch info --json``.+ * - ``done``+ - ``already_unloaded``+ - Nothing of that name is loaded. Exit status 0, nothing measured.+ * - ``pin``+ - ``detach_failed``+ - The unload was measured, but the pins could not be removed.+ Apply the directive again.++Read the verifier log+---------------------++4. For ``verifier_rejected``, read the report's ``verifier_log``, which+ keeps up to 16 MiB of the kernel's log. In phase+ ``signed_loader_load`` it is the log of the loader's own load. In phase+ ``payload_load`` it is the log of the last load the loader made, since+ the loader passes the same buffer to each map, BTF and program load,+ so its end is about the step that failed. The log on standard error is+ cut at 4096 bytes when the loader returned an error. The report has+ all of it. ``loader_return`` is the loader's negative error.++5. Match the last lines of the log:++ .. list-table::+ :header-rows: 1+ :widths: 42 58++ * - Log+ - Cause and what to do+ * - ``invalid func unknown#195896080``+ - A CO-RE relocation found no matching type or field in the+ target's BTF, and the kernel replaced the instruction. Build+ against the target kernel's ``vmlinux.h``, or test for the field+ with ``bpf_core_field_exists()`` and skip the access.+ * - ``<function>() is not modifiable``+ - ``fmod_ret`` on a function the kernel does not admit. Attach+ elsewhere. :doc:`attach-kinds` lists the rules.+ * - ``<function> is not sleepable``+ - A ``.s`` section on a function or hook that cannot sleep. Use+ the section without ``.s``.+ * - ``LSM programs must have a GPL compatible license``, ``cannot+ call GPL-restricted function from non-GPL compatible program``+ - Declare ``char _license[] SEC("license") = "Dual BSD/GPL";``.+ * - no log, ``errno_name`` ``ENOENT``, ``loader_return`` -2+ - The loader did not find the ``fentry``, ``fexit``,+ ``fmod_ret``, ``lsm`` or ``tp_btf`` target in the kernel's BTF.+ The function does not exist on this kernel, has another name, or+ is inlined. Choose another attach point, or limit the upatch to+ kernels that have it.+ * - any other verifier message+ - The verifier's own diagnosis of the program. Fix the source.+ The kernel's BPF documentation explains the messages.++Fix and load again+------------------++6. Change the source or the build, rebuild and sign, and load the new+ file. A rebuilt upatch has a new payload digest, so build its unload+ directive again too.++7. Confirm the result with the report's category ``ok`` and with:++ .. code-block:: console++ target# shirudo upatch get <name>++ ``<name>`` is the upatch name. Use shirudo's own commands to look at a+ loaded upatch: the LSM refuses every other tool a descriptor of+ shirudo's maps and links, by pin or by id, and counts each attempt as+ ``ObjGet``.++Next steps+----------++- :doc:`/reference/cli/upatch-load` for the report's fields.+- :doc:`/concepts/background/co-re-btf` for how relocations resolve.+- :doc:`testing` for the test VM.diff --git a/Documentation/upatches/decoders.rst b/Documentation/upatches/decoders.rstnew file mode 100644index 00000000..6df7f3af--- /dev/null+++ b/Documentation/upatches/decoders.rst@@ -0,0 +1,268 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: upatch authors++Write a Lua decoder+===================++A decoder turns a snapshot of one map into the record that shirudo+exports: the body of an OTLP log record, or a list of OTLP metrics. It is+a Lua function that the BPF source declares and the build signs into the+upatch, so it has the same signer as the program whose data it reads.+This page shows how to declare one, write it, check it and run it.++Before you begin+----------------++- An upatch source with the map to export, and the layout of that map:+ the records its serializer writes, or its key and value types.+ :doc:`maps-arenas-serializers` covers serializers.+- The test VM or another target to run the decoder on, as+ :doc:`testing` describes.+- Familiarity with Lua 5.1, the language LuaJIT runs.+ :doc:`/concepts/background/luajit` covers what shirudo uses it for.++Declare the decoder+-------------------++1. Decide on the signal. A log decoder returns a table that becomes the+ body of one log record per snapshot. A metric decoder returns OTLP+ metrics with names, units and data points of its choosing.++2. Include ``shirudo_decoder.h`` after ``vmlinux.h`` and declare a+ manifest in ``.rodata``. ``kernel-obs`` declares this one, through a+ macro, for ``watch_stat``, a per-CPU array whose one value holds two+ ``__u64`` counters, ``checked`` and ``matched``:++ .. code-block:: c++ #include "shirudo_decoder.h"++ const struct shirudo_decoder_manifest watch_stat_decoder SEC(".rodata") = {+ .magic = SHIRUDO_DECODER_MANIFEST_MAGIC,+ .version = SHIRUDO_UPATCH_DECODER_VERSION,+ .language = SHIRUDO_UPATCH_DECODER_LANG_LUA,+ .api_version = 1,+ .input_format = SHIRUDO_UPATCH_DECODER_INPUT_MAP_V1,+ .export_signal = SHIRUDO_UPATCH_DECODER_EXPORT_METRIC,+ .upatch = "kernel-obs",+ .map = "watch_stat",+ .source = "decoders/watch_stat.lua",+ .entrypoint = "decode",+ };++ The builder finds manifests by their magic in the object's ``.rodata``,+ so declare the manifest ``const``. It also passes over a manifest with+ an empty string field or a zero ``language``, ``api_version``,+ ``input_format`` or ``export_signal``, without an error, so check the+ result as step 6 shows. Set the fields as follows:++ .. list-table::+ :header-rows: 1+ :widths: 22 78++ * - Field+ - Value+ * - ``magic``, ``version``+ - The constants shown. With any other value the builder does not+ recognize the manifest and builds the upatch without it.+ * - ``language``, ``api_version``, ``input_format``+ - The constants shown. Any other value fails the build with+ ``unsupported decoder ABI for '<upatch>/<map>'``.+ * - ``export_signal``+ - ``SHIRUDO_UPATCH_DECODER_EXPORT_LOG`` or+ ``SHIRUDO_UPATCH_DECODER_EXPORT_METRIC``.+ * - ``upatch``+ - The upatch name, at most 63 characters. In a package that is the+ source's base name.+ * - ``map``+ - The name of a map of the object, at most 15 characters. One+ decoder per map.+ * - ``source``+ - The Lua file, at most 63 characters, relative to the directory+ of the ``.bpf.c`` file, or to the current directory when the+ input is a ``.bpf.o``. No leading ``/``, no ``.`` or ``..``+ component, no backslash. Not empty, at most 16 MiB.+ * - ``entrypoint``+ - The function to call, at most 31 characters.++Write the function+------------------++3. Create the Lua file. The chunk either defines a global function with+ the entrypoint's name, returns a function, or returns a table that has+ one under that name. shirudo calls it with one argument, the input+ table:++ .. list-table::+ :header-rows: 1+ :widths: 38 62++ * - Field+ - Content+ * - ``schema``+ - ``1``+ * - ``upatch``, ``map``+ - the upatch and map names+ * - ``startTimeUnixNano``+ - when the upatch was loaded, as a decimal string+ * - ``timeUnixNano``+ - the time of the snapshot, as a decimal string+ * - ``data.name``, ``data.type``+ - the map's name and type, such as ``percpu_array``+ * - ``data.max_entries``, ``data.n_entries``+ - the map's capacity and the entries read+ * - ``data.key_size``, ``data.value_size``, ``data.n_cpus``+ - sizes in bytes, and the number of CPUs for a per-CPU map+ * - ``data.truncated``+ - whether the read stopped at the entry limit+ * - ``data.entries[i].key_hex``, ``.value_hex``+ - a directly read entry in hex. A per-CPU value holds one 8-byte+ aligned slot per CPU.+ * - ``data.serialized``, ``data.serialized_pages``,+ ``data.serialized_bytes``+ - whether a serializer produced the snapshot, and its size+ * - ``data.pages[i]``+ - one serializer page: ``page_index``, ``cursor``,+ ``next_cursor``, ``done``, ``flags``, ``chunks``, ``bytes`` and+ ``data_hex``++ Lua numbers cannot hold a 64-bit value exactly, so shirudo passes+ timestamps as decimal strings, and these host functions exchange+ 64-bit values as decimal strings too:++ .. list-table::+ :header-rows: 1+ :widths: 42 58++ * - Function+ - Returns+ * - ``shirudo.page_slots(page, size)``+ - the page's payload cut into slots of ``size`` bytes, in order,+ respecting chunk boundaries+ * - ``shirudo.fixed_records(pages, size)``+ - the slots of all pages, indexed by each page's ``cursor`` plus+ the slot's position+ * - ``slot:u8(off)``, ``slot:u16(off)``, ``slot:u32(off)``+ - a little-endian integer at ``off``, 0 when out of range+ * - ``slot:u64(off)``+ - a little-endian 64-bit value as a decimal string+ * - ``slot:cstring(off, len)``+ - the bytes from ``off`` up to the first NUL, at most ``len``+ * - ``shirudo.u64_add(a, b)``, ``shirudo.u64_sub(a, b)``+ - exact sum and difference of two decimal strings. The sum stops+ at the largest value and the difference at 0.+ * - ``shirudo.hex_u64(hex, off)``+ - the little-endian 64-bit value at byte ``off`` of a hex string,+ as a decimal string++ The ``watch_stat`` decoder adds up both counters over all CPUs and+ returns one monotonic sum with a data point for each:++ .. literalinclude:: ../../upatches/kernel-obs/decoders/watch_stat.lua+ :language: lua++4. Return the record. A log decoder returns a table. With ``--otel`` it+ becomes the log record's body: a table whose keys are 1 to n becomes+ an array, any other table a key-value list, a whole number up to 2^53+ an ``intValue`` and any other number a ``doubleValue``. A metric+ decoder returns an array of OTLP ``Metric`` objects, exactly as they+ appear in the ``metrics`` array of a ``scopeMetrics`` entry. A string+ that is not valid UTF-8 is exported with U+FFFD in place of each bad+ byte.++ To turn a timestamp a serializer took on the boot-time clock into wall+ clock time, subtract its age from ``timeUnixNano``. The ``kernel-obs``+ decoders do it with the time the serializer ran, which their page+ header carries:++ .. code-block:: lua++ shirudo.u64_sub(input.timeUnixNano, shirudo.u64_sub(boot_now, ts))++The decoder runs in a restricted LuaJIT state:++- It is loaded as source text. LuaJIT does not verify bytecode, so a+ precompiled chunk is refused.+- The JIT compiler is off, so that the instruction count sees every+ instruction. One snapshot may take 1,000,000 virtual machine+ instructions, loading the chunk included, and 32 MiB of memory, and the+ result may nest 32 levels deep.+- ``io``, ``os``, ``package``, ``require``, ``debug``, ``jit``, ``ffi``,+ ``dofile``, ``loadfile``, ``load``, ``loadstring``, ``module`` and+ ``collectgarbage`` are removed. The rest of the base library and the+ ``string``, ``table``, ``math`` and ``bit`` libraries remain.+- shirudo reads the decoder from the archived copy of the upatch,+ ``/var/lib/shirudo/upatches/<name>.upatch``, and opens it as sealed+ state. A decoder that did not arrive inside the signed artifact never+ runs.++An error raised in the decoder drops that snapshot with a message on+standard error. It never produces a partial record.++Build and check it+------------------++5. Build the upatch as usual. The builder reads each manifest, resolves+ ``source`` and embeds the file in the signed ``DCDB`` section. It+ refuses the build when a manifest names another upatch, a map the+ object does not have, a second decoder for the same map, or a source+ it cannot read.++6. Confirm that the decoder is in the artifact:++ .. code-block:: console++ operator$ shirudo upatch info <file>.upatch++ ``<file>`` is your upatch. The ``Decoders`` section lists each decoder+ with its target as ``<upatch>/<map>``, the language and API version,+ the input format ``shirudo.map.v1``, the export signal, and the source+ file with its entry point and size.++Run it on a target+------------------++7. Load the upatch on the target, then run the decoder against the live+ map without draining it:++ .. code-block:: console++ target# shirudo-runtime upatch map <upatch> <map> --json --peek++ ``shirudo-runtime`` is the command in the test VM, as :doc:`testing`+ explains. ``<upatch>`` and ``<map>`` are the names in the manifest. The+ command prints what the decoder returned as one JSON document. A failure+ prints one of ``upatch map: decoder load failed: <message>``, ``upatch+ map: decoder entrypoint '<name>' not found``, ``upatch map: decoder+ failed: <message>`` or ``upatch map: decoder encode failed: <message>``,+ and the instruction limit shows as ``decoder instruction limit+ exceeded``.++8. Send one snapshot to a collector:++ .. code-block:: console++ target# shirudo-runtime upatch map <upatch> <map> --peek --otel \+ --otel-endpoint=<url>++ ``<url>`` is the collector's OTLP/HTTP base URL. A log decoder's record+ goes to ``<url>/v1/logs``, a metric decoder's metrics to+ ``<url>/v1/metrics``.++A map without a decoder is exported over OTLP as a log record whose body+lists its entries or serializer pages in hex, and ``--json`` reports ``No+data available`` for it. An unsigned per-CPU integer map without a decoder+is classified as a metric and then fails to export over OTLP with the same+message, so give such a map a metric decoder.++Next steps+----------++- :doc:`/operate/telemetry` to export every map on a schedule.+- :doc:`/reference/formats/otlp` for the documents on the wire.+- The decoders under ``upatches/kernel-obs/decoders/`` for complete log+ decoders over arena tables, timestamps included.diff --git a/Documentation/upatches/examples.rst b/Documentation/upatches/examples.rstnew file mode 100644index 00000000..85ae8cc2--- /dev/null+++ b/Documentation/upatches/examples.rst@@ -0,0 +1,107 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Reference+:audience: upatch authors++Example packages+================++The tree ships two packages under ``upatches/``: ``kernel-obs``, a+complete observability package with arena tables, serializers, decoders+and generated ``.rodata``, and ``kernel-cve``, a set of small CVE+detectors exported from a mitigation campaign.++kernel-obs+----------++.. list-table::+ :header-rows: 1+ :widths: 28 72++ * - Item+ - Content+ * - Package+ - ``kernel-obs``, from ``upatches/kernel-obs/Beefile``+ * - upatch+ - ``kernel-obs``, built from ``kernel-obs.bpf.c``, which includes+ ``obs_exec.bpf.c``, ``obs_net.bpf.c``, ``obs_dns.bpf.c``,+ ``obs_priv.bpf.c`` and ``obs_file.bpf.c``+ * - Attach kinds+ - ``lsm`` and ``lsm.s`` hooks for processes, files, sockets,+ credentials, mounts, modules and ``bpf()``; ``cgroup_skb/ingress``+ and ``cgroup_skb/egress`` for packets and DNS+ * - Tables+ - ``exec``, ``net``, ``socket``, ``listen``, ``watch``, ``dns``,+ ``priv`` and ``file``: one ``obs_table.h`` instance each, all in the+ arena ``obs_i_arena``, each with a serializer and a log decoder+ * - Counters+ - ``watch_stat``, a per-CPU array with a metric decoder+ * - Test-run program+ - ``shirudo_test__kernel_obs`` allocates every table in the arena at+ load+ * - Generated ``.rodata``+ - ``obs_watch_v4`` and ``obs_watch_v6``, generated from+ ``watch.list`` by ``gen_watch_rodata.py``+ * - Enforces+ - nothing, every hook observes++``kernel-obs`` is the reference for the conventions in+:doc:`maps-arenas-serializers` and :doc:`decoders`: the double-buffered+tables, the one-entry maps that name the tables, the arena association,+the page header and the timestamp conversion in the decoders.++Its ``README.md`` is what ``shirudo bpm info`` prints for the package.+It follows here as it ships. Where it tells a target to add a key with+``bpm key add``, note that a production target takes its keys and+repositories from its signed config image and refuses local key changes.+:doc:`/operate/deliver-packages` describes that setup.++.. include:: ../../upatches/kernel-obs/README.md+ :parser: myst_parser.sphinx_++kernel-cve+----------++``upatches/kernel-cve/`` holds three detectors, each in+``sources/<slug>/observability/``, a ``vmlinux.h``, ``manifest.json``+with one record per detector, and the Beefile ``kernel-cve.bee``. The+manifest names the kernel the detectors were loaded on,+``7.2.0-shirudo-7.2``.++.. list-table::+ :header-rows: 1+ :widths: 34 26 40++ * - Source+ - Hook+ - ``hits`` counts calls where+ * - ``cve-2025-71093-e1000-tbi-detector.bpf.c``+ - ``kprobe/e1000_tbi_should_accept``+ - the frame length is 0+ * - ``cve-2026-31675-netem-detector.bpf.c``+ - ``kprobe/netem_enqueue``+ - the packet's linear head is empty+ * - ``cve-2026-63984-rpl-detector.bpf.c``+ - ``kprobe/ipv6_rpl_srh_decompress``+ - ``n + 1`` exceeds 127, the bound the fix introduces++Each detector counts every call in a per-CPU ``activity`` counter and the+calls that match its predicate in ``hits``. None of them refuses+anything. They are ``kprobe`` programs and define+``__TARGET_ARCH_x86``, so they need a target with ``CONFIG_KPROBES`` and+``CONFIG_KPROBE_EVENTS`` on x86-64. ``manifest.json`` marks every+predicate as ``source_derived_unvalidated``: derived from the fix, not+checked against an exploit.++:doc:`kernel-fix-tutorial` takes the third detector from its fix to a+package, as an ``fentry`` program. ``kernel-cve.bee`` itself does not+build, and its tree entries do not match its upatch names.+:doc:`beefile` lists what is wrong with it.++Related+-------++- :doc:`kernel-fix-tutorial` to write a detector of your own.+- :doc:`beefile` for the keys both Beefiles use.diff --git a/Documentation/upatches/index.rst b/Documentation/upatches/index.rstnew file mode 100644index 00000000..c6ccef0e--- /dev/null+++ b/Documentation/upatches/index.rst@@ -0,0 +1,28 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++upatches+========++These pages are for upatch authors: engineers who turn a kernel fix or+an observation into a signed upatch and ship it as a package. Start with+:doc:`/upatches/concepts`, then follow+:doc:`/upatches/kernel-fix-tutorial` from a real kernel fix to a+published package. :doc:`/upatches/attach-kinds` and+:doc:`/upatches/beefile` are the references to keep at hand, and+:doc:`/upatches/debugging` explains each way a load can fail.++.. toctree::+ :titlesonly:++ concepts+ kernel-fix-tutorial+ attach-kinds+ maps-arenas-serializers+ decoders+ testing+ beefile+ publishing+ debugging+ examplesdiff --git a/Documentation/upatches/kernel-fix-tutorial.rst b/Documentation/upatches/kernel-fix-tutorial.rstnew file mode 100644index 00000000..03d265d5--- /dev/null+++ b/Documentation/upatches/kernel-fix-tutorial.rst@@ -0,0 +1,435 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Tutorial+:audience: upatch authors++From a kernel fix to an upatch+==============================++This tutorial takes one kernel fix to a signed upatch, loads it on a test+target, unloads it again, and packages it for a registry. The example is+CVE-2026-63984, an overflow in the IPv6 RPL routing header code, whose+detector ships in ``upatches/kernel-cve/sources/``. You read the fix,+decide where the upatch attaches, write the program, then build, inspect,+test, unload, package and publish it.++Before you begin+----------------++- A shirudo checkout built with ``make`` and ``make shirudo-build``, and+ clang installed as ``/usr/bin/clang``, the path the build helper runs.+- A test VM running from that checkout, as :doc:`testing` describes. The+ steps below use the default ``bpf-next`` VM and the signing key its+ bundle enrolled.+- A Linux kernel git tree, to read the fix.+- For the last step only, an OCI registry you can push to.++Run the operator commands as root, the user who built the test VM and+owns the key it enrolled, from the checkout's root at first, with the+binary and the helper on your path:++.. code-block:: console++ operator$ export PATH="$PWD:$PWD/tools/shirudo-build:$PATH"++Read the fix+------------++Start from the commit that fixes the bug, not from the CVE text. The fix+says exactly which inputs are dangerous, and that condition becomes the+upatch's predicate. In a kernel tree:++.. code-block:: console++ $ git show 9d5e7a46a9f6++The commit is ``ipv6: rpl: fix hdrlen overflow in+ipv6_rpl_srh_decompress()``. ``ipv6_rpl_srh_rcv()`` derives ``n`` from a+received RPL routing header, which carries ``n + 1`` addresses, and calls+``ipv6_rpl_srh_decompress()``. That function stores+``((n + 1) * 16) >> 3`` in the 8-bit ``hdrlen`` of the header it builds.+From ``n = 127`` on, the value no longer fits, the recompressed header+lands inside the decompressed addresses, and the recompression corrupts+the routing header of the forwarded packet. The fix+changes one bound in ``ipv6_rpl_srh_rcv()`` from ``(n + 1) > 255`` to+``(n + 1) > 127``.++Two facts from the source shape the upatch. The dangerous call is a call+of ``ipv6_rpl_srh_decompress()`` with ``n + 1 > 127``. And the kernel only+reaches it when ``net.ipv6.conf.all.rpl_seg_enabled`` and the receiving+interface's ``rpl_seg_enabled`` are both set.++Choose the attach point+-----------------------++An upatch can refuse the dangerous input or record it. Refusing needs a+hook that can change the outcome:++- ``fmod_ret`` would return early from ``ipv6_rpl_srh_rcv()`` or its+ caller ``ipv6_rthdr_rcv()``. The kernel admits ``fmod_ret`` only on+ ``security_*`` hooks, system call entry points and functions marked for+ error injection or return modification, and neither function is marked.+ In the test VM's kernel, ``ipv6_rpl_srh_rcv()`` does not even appear in+ the BTF.+- A ``netfilter`` program at IPv6 pre-routing could drop such packets+ before the routing header code sees them, by parsing the routing header+ itself. That parser is a larger piece of work than this tutorial.++So this upatch records. ``ipv6_rpl_srh_decompress()`` is a global function+that is present in the kernel's BTF, and ``n`` is its fourth argument. The+shipped detector, ``cve-2026-63984-rpl-detector.bpf.c``, attaches a+``kprobe`` there. This tutorial uses ``fentry`` instead, for three+reasons: the program receives the arguments with their BTF types instead+of raw registers, the verifier checks the program's prototype against the+kernel's, and the test VM's kernel is built without kprobes.+:doc:`attach-kinds` compares the kinds.++Write the program+-----------------++Work in a directory under ``build/``, which git ignores and the test VM+sees. Create it and change into it:++.. code-block:: console++ operator$ mkdir -p build/rpl-shield && cd build/rpl-shield++Generate a ``vmlinux.h`` from the BTF of the kernel the upatch is for,+here the test VM's:++.. code-block:: console++ operator$ ../../tools/gen-vmlinux-h/gen-vmlinux-h \+ ../../artifacts/bpf-next-kernel-debs/vmlinux.btf > vmlinux.h++The compiler looks for libbpf's headers under ``./vendor/libbpf``, so link+the checkout's vendored copy into the directory:++.. code-block:: console++ operator$ ln -s ../../vendor vendor++Write ``cve-2026-63984-rpl.bpf.c``:++.. code-block:: c++ // SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause+ /*+ * CVE-2026-63984: count ipv6_rpl_srh_decompress() calls whose segment+ * count overflows the 8-bit hdrlen the function computes.+ */++ #include "vmlinux.h"+ #include <bpf/bpf_helpers.h>+ #include <bpf/bpf_tracing.h>++ char _license[] SEC("license") = "Dual BSD/GPL";++ struct {+ __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);+ __uint(max_entries, 1);+ __type(key, __u32);+ __type(value, __u64);+ } hits SEC(".maps");++ struct {+ __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);+ __uint(max_entries, 1);+ __type(key, __u32);+ __type(value, __u64);+ } activity SEC(".maps");++ static __always_inline void count_event(void *map)+ {+ __u32 zero = 0;+ __u64 *count = bpf_map_lookup_elem(map, &zero);++ if (count)+ (*count)++;+ }++ SEC("fentry/ipv6_rpl_srh_decompress")+ int BPF_PROG(cve_2026_63984_rpl, struct ipv6_rpl_sr_hdr *outhdr,+ const struct ipv6_rpl_sr_hdr *inhdr,+ const struct in6_addr *daddr, unsigned char n)+ {+ count_event(&activity);+ if ((__u32)n + 1 > 127)+ count_event(&hits);+ return 0;+ }++The maps and the predicate are the shipped detector's. ``activity`` counts+every call, which shows that the upatch is attached and the path is in+use. ``hits`` counts the calls the fix rejects. Per-CPU counters need no+locking. The section name and the ``BPF_PROG`` prototype are what changed+from the ``kprobe`` version, which also needs a ``__TARGET_ARCH_*`` define+to read arguments from registers.++Build and sign it+-----------------++The test VM enrolled the certificate of the key in+``build/test-vm/host-bundle-bpf-next-verity.operator/keys``. Sign with+that key:++.. code-block:: console++ operator$ shirudo build cve-2026-63984-rpl.bpf.c --vmlinux vmlinux.h \+ --keys-dir <keys-dir> -o cve-2026-63984-rpl.upatch+ wrote cve-2026-63984-rpl.upatch (insns=1376 sig=4853 data=3480 sections=2 maps=2 progs=1 decoders=0 name=cve-2026-63984-rpl)++``<keys-dir>`` is ``../test-vm/host-bundle-bpf-next-verity.operator/keys``+from this directory. ``shirudo build`` compiled the source, generated the+signed loader around the object, signed it with ML-DSA-87 and named the+upatch after the file, ``cve-2026-63984-rpl``. The sizes and digests on+this page depend on your headers and paths.++Inspect it+----------++Read the artifact back before it leaves the operator host:++.. code-block:: console++ operator$ shirudo upatch info cve-2026-63984-rpl.upatch+ File: cve-2026-63984-rpl.upatch+ Name: cve-2026-63984-rpl+ Type: LOAD+ Payload type: bpf+ Version: 1+ Payload SHA256: f3e2894d7c20d90e759b9d716849fc2acf01ff5de2ad8565b1e0f0320ef9e711+ File size: 10069 bytes++ Loader:+ Instructions: off=360 len=1376+ Log buffer size: 1048576+ Metadata: (none)+ Data: off=6589 len=3480++ Signature:+ Offset: 1736+ Length: 4853 bytes++ Signed sections:+ Name: cve-2026-63984-rpl+ Attach metadata: 176 bytes+ Unload payload: (none)++ Decoders:+ (none)++``Payload SHA256`` is the SHA-256 of the signed loader and its data. The+signed sections hold the name and the attach metadata, one program entry+for the fentry program. The file carries no decoders, because the source+declares none.++Build the unload directive next, bound to that digest:++.. code-block:: console++ operator$ shirudo build --unload cve-2026-63984-rpl \+ --payload-sha256 "$(shirudo upatch info --json cve-2026-63984-rpl.upatch | jq -r .payload_sha256)" \+ --keys-dir <keys-dir> -o cve-2026-63984-rpl.unload.upatch+ wrote cve-2026-63984-rpl.unload.upatch (insns=1320 sig=4853 data=2808 sections=2 maps=1 progs=1 decoders=0 name=cve-2026-63984-rpl UNLOAD)++The directive removes only a loaded upatch with exactly this payload.++Test it on the target+---------------------++In a second terminal, at the checkout's root, open a shell on the test VM:++.. code-block:: console++ # make -C testing vm-ssh++The VM sees the checkout read-only at ``/mnt/shirudo-src``. Run shirudo+there as ``shirudo-runtime``, which executes the binary from the verified+runtime image. Load the upatch and print the report:++.. code-block:: console++ target# shirudo-runtime upatch load --report=- \+ /mnt/shirudo-src/build/rpl-shield/cve-2026-63984-rpl.upatch+ loaded signed loader: prog_fd=10 keyring=531121468 sig=4853B insns=172 data=3480B+ loader ok, retval=0 (maps=2 progs=1)+ attached + pinned prog 0 (raw_tracepoint) -> /run/shirudo/bpffs/upatches/cve-2026-63984-rpl/link+ pinned map 0 (hits, type=6) -> /run/shirudo/bpffs/upatches/cve-2026-63984-rpl/maps/hits+ pinned map 1 (activity, type=6) -> /run/shirudo/bpffs/upatches/cve-2026-63984-rpl/maps/activity+ upatch load: name=cve-2026-63984-rpl keyring=531121468 progs=1+ upatch load: chain extended, value=3380b0e2d22c066ecba561c182869b1366e5706f73fc3a657b907394953cfbfc+ upatch load measured: name=cve-2026-63984-rpl chain=3380b0e2d22c066ecba561c182869b1366e5706f73fc3a657b907394953cfbfc+ {"schema":1,"result":"ok","op":"upatch_load","phase":"done","errno":null,"errno_name":null,"category":"ok","message":"","verifier_log":"","loader_return":0,"upatch":{"path":"/mnt/shirudo-src/build/rpl-shield/cve-2026-63984-rpl.upatch","name":"cve-2026-63984-rpl","payload_sha256":"f3e2894d7c20d90e759b9d716849fc2acf01ff5de2ad8565b1e0f0320ef9e711"},"kernel":{"release":"7.3.0-bpf-next+"},"tpm":{"nv_index":"0x01818E00","chain_after":"3380b0e2d22c066ecba561c182869b1366e5706f73fc3a657b907394953cfbfc"}}++The log lines go to standard error and the JSON report to standard+output. The report has ``"result":"ok"``, phase ``done`` and category+``ok``, and its ``tpm.chain_after`` is the measurement register after the+load. ``attached + pinned prog 0 (raw_tracepoint)`` means that shirudo+attached the fentry program through ``BPF_RAW_TRACEPOINT_OPEN`` at the+function the verifier bound, and pinned the link. :doc:`debugging`+explains the report when a load fails.++Check where the kernel attached it and read the counters:++.. code-block:: console++ target# shirudo-runtime upatch get cve-2026-63984-rpl+ upatch: cve-2026-63984-rpl+ Location: fentry/ipv6_rpl_srh_decompress+ Prog id: 77+ Loaded at: <time> (12s ago)+ Payload: f3e2894d7c20d90e759b9d716849fc2acf01ff5de2ad8565b1e0f0320ef9e711 (signature-bound)+ Maps (2): activity, hits++ Source (kernel BTF line_info):++ <checkout>/build/rpl-shield/cve-2026-63984-rpl.bpf.c:+ 29: __u32 zero = 0;+ 30: __u64 *count = bpf_map_lookup_elem(map, &zero);+ 32: if (count)+ 33: (*count)++;+ 37: int BPF_PROG(cve_2026_63984_rpl, struct ipv6_rpl_sr_hdr *outhdr,+ 42: if ((__u32)n + 1 > 127)++ == Map: activity ==+ ...++``<time>`` is the time of the load and ``<checkout>`` the path of your+checkout on the host, where the compiler saw the source. ``upatch get``+shows the attach site, ``fentry/ipv6_rpl_srh_decompress``, the source+lines the kernel holds for the program, and the maps with their contents.+Read one map:++.. code-block:: console++ target# shirudo-runtime upatch map cve-2026-63984-rpl hits+ upatch: cve-2026-63984-rpl+ Map: hits+ Type: percpu_array (64 CPUs)+ Max entries: 1+ Entries: 1 of 1+ Key type: unsigned int (4 B)+ Value type: unsigned long long (8 B)++ Contents:+ key=0: sum=0+ cpu0=0 cpu1=0 cpu2=0 cpu3=0+ ...++Both counters stay at zero until the kernel processes an RPL routing+header, which needs ``rpl_seg_enabled`` set and a crafted packet. On a+kernel that carries the fix, ``ipv6_rpl_srh_rcv()`` drops a header with+too many addresses before the call, so ``hits`` stays at zero there even+under attack.++Unload it+---------++Apply the unload directive:++.. code-block:: console++ target# shirudo-runtime upatch unload --report=- \+ /mnt/shirudo-src/build/rpl-shield/cve-2026-63984-rpl.unload.upatch+ loaded signed loader: prog_fd=10 keyring=531121468 sig=4853B insns=165 data=2808B+ upatch unload: payload matches for 'cve-2026-63984-rpl'+ upatch unload: chain extended, value=3b96bfbac667807c99332a8d2ba9d2a7b5eb74db42aba18eea452bef9a7d0c6b+ upatch unload measured: name=cve-2026-63984-rpl chain=3b96bfbac667807c99332a8d2ba9d2a7b5eb74db42aba18eea452bef9a7d0c6b+ upatch unload: detached + unpinned cve-2026-63984-rpl+ {"schema":1,"result":"ok","op":"upatch_unload","phase":"done","errno":null,"errno_name":null,"category":"ok","message":"","verifier_log":"","loader_return":0,"upatch":{"path":"/mnt/shirudo-src/build/rpl-shield/cve-2026-63984-rpl.unload.upatch","name":"cve-2026-63984-rpl","payload_sha256":"f3e2894d7c20d90e759b9d716849fc2acf01ff5de2ad8565b1e0f0320ef9e711"},"kernel":{"release":"7.3.0-bpf-next+"},"tpm":{"nv_index":"0x01818E00","chain_after":"3b96bfbac667807c99332a8d2ba9d2a7b5eb74db42aba18eea452bef9a7d0c6b"}}++The report again shows category ``ok``. The kernel verified the+directive's signature, shirudo matched its digest against the pinned+upatch, measured the unload, and removed the pins and the archive copy.+``shirudo-runtime upatch list`` no longer shows the upatch. Leave the VM+shell.++Package it+----------++A package carries the upatch, its unload directive and an optional entry+for the upatch tree. In ``build/rpl-shield`` on the operator host, write+``Beefile``:++.. code-block:: toml++ [package]+ name = "rpl-shield"+ description = "Detector for CVE-2026-63984 in ipv6_rpl_srh_decompress()"+ license = "GPL-2.0 OR BSD-2-Clause"+ authors = ["Example Org"]++ [[upatches]]+ source = "cve-2026-63984-rpl.bpf.c"++ [upatches.tree]+ id = "cve-2026-63984-rpl"++ [upatches.tree.selector.kconfig]+ CONFIG_IPV6 = ["y", "m"]++The upatch name in a package is always the source's base name, and the+tree ``id`` must equal it. The selector limits the tree entry to kernels+built with IPv6. A target evaluates it against ``/proc/config.gz`` or+``/boot/config-<release>``. A target that has neither does not match, and+a target that does not match an entry passes over it for good.+:doc:`beefile` lists every key.++Build the package:++.. code-block:: console++ operator$ shirudo bpm build --version 1.0.0 --vmlinux vmlinux.h \+ --keys-dir <keys-dir>+ wrote /tmp/shirudo-bpm-build.<random>/0.upatch (insns=1376 sig=4853 data=3480 sections=2 maps=2 progs=1 decoders=0 name=cve-2026-63984-rpl)+ wrote /tmp/shirudo-bpm-build.<random>/0.unload.upatch (insns=1320 sig=4853 data=2808 sections=2 maps=1 progs=1 decoders=0 name=cve-2026-63984-rpl UNLOAD)+ <checkout>/build/rpl-shield/rpl-shield-1.0.0.bee++``<random>`` is the suffix of a temporary directory and ``<checkout>`` the+path of your checkout. ``bpm build`` compiled and signed the upatch again,+generated its unload directive from the new payload digest, and wrote+``rpl-shield-1.0.0.bee``. Built from the same source, headers and+directory, the packaged upatch has the same payload digest as the one you+tested. List what the package will load:++.. code-block:: console++ operator$ shirudo bpm info upatches rpl-shield-1.0.0.bee --all+ upatches/cve-2026-63984-rpl.upatch+ upatches/cve-2026-63984-rpl.unload.upatch++Publish it+----------++Push the package to a repository and add it to the registry's signed+index:++.. code-block:: console++ operator$ shirudo bpm push rpl-shield-1.0.0.bee \+ oci://<registry>/<namespace>/rpl-shield --keys-dir <keys-dir>++Append its tree entry to a tree that targets follow:++.. code-block:: console++ operator$ shirudo bpm tree append rpl-shield-1.0.0.bee \+ oci://<registry>/<namespace>/<tree> --keys-dir <keys-dir>++``<registry>`` and ``<namespace>`` name your registry and repository path,+and ``<tree>`` the repository of the tree. ``bpm push`` prints the pushed+reference, ``bpm tree append`` the tree's reference and manifest digest.+A package signed with the test bundle's key is for test targets only.+Sign what a fleet runs with your own key.++Next steps+----------++- :doc:`publishing` for the index, the tree and withdrawing an entry.+- :doc:`/operate/deliver-packages` for what a target does with them.+- :doc:`maps-arenas-serializers` and :doc:`decoders` to export what the+ upatch records.+- :doc:`attach-kinds` for the other places an upatch can attach.diff --git a/Documentation/upatches/maps-arenas-serializers.rst b/Documentation/upatches/maps-arenas-serializers.rstnew file mode 100644index 00000000..68dde972--- /dev/null+++ b/Documentation/upatches/maps-arenas-serializers.rst@@ -0,0 +1,214 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: upatch authors++Maps, arenas and serializers+============================++An upatch that observes builds up records in the kernel, and the operator+wants them out of the target at a steady rate, in complete and bounded+snapshots. This page explains why such state lives in a BPF arena, how a+serializer program turns it into records, what draining and peeking mean,+and what the export reads.++Why plain maps are not enough+-----------------------------++The obvious design keeps records in a hash map and lets the exporter read+it from userspace, one ``BPF_MAP_GET_NEXT_KEY`` and ``BPF_MAP_LOOKUP_ELEM``+at a time. Two things go wrong. The programs keep writing while the+exporter walks, so the snapshot mixes entries from different moments and+can miss or repeat keys. And nothing empties the map: once it is full,+every new key is refused, silently, until someone deletes entries, which+from userspace is yet another racing walk.++A structure with more shape than a flat table, a tree, a ring or several+maps that refer to each other, cannot be read consistently from userspace+at all. Its invariants hold only for code that takes the same locks or+follows the same ordering as the writers, and that code runs in the+kernel.++So we keep accumulating state in one place the upatch's own programs+control, and have a program of the upatch render it. Hash and array maps+remain for what cannot live elsewhere: task, socket and per-CPU scratch+state, lookup keys the kernel owns, and the serializer's output map.++Why an arena+------------++A ``BPF_MAP_TYPE_ARENA`` map is memory that the upatch's programs allocate+from and address with ordinary pointers. That gives three properties a+hash map lacks. The upatch can keep two copies of a table and switch+between them, so an export reads a buffer that no hook writes to any more.+The serializer can reset that buffer when the export is done, so the table+holds one export interval and never fills up for good. And when an+interval runs out of room, the table can count the refused records and+report the count with the snapshot.++Userspace cannot iterate an arena through ``bpf()``: the kernel has no+key walk for it, and ``shirudo upatch map`` reports such a map as one+whose contents require a serializer. A program uses at most one arena, so+an upatch keeps all its tables in one. The arena needs a 64-bit kernel+with an MMU and a BPF JIT that supports arenas, which x86-64, arm64 and+riscv64 have.++obs_table.h template+--------------------++``upatches/kernel-obs/obs_table.h`` is the template for such a table. A+source defines the table's name, key and value types, capacity, bucket+count, record size and record encoder, and includes the file once per+table. Each inclusion produces a hash table in the arena and a serializer+for it.++The table is double-buffered, as Figure 1 shows. Hooks insert into the+active buffer. A probe chain of bounded length finds an existing key, and+a new key takes the next free slot. When the slots run out, the insert+fails and the ``overflow`` count goes up. Records are therefore deltas+over one export interval.++.. figure:: /images/upatches-double-buffer.svg+ :alt: Hooks write into the active buffer. An export swaps the buffers,+ a serializer renders the drained buffer page by page into the+ shirudo_ser map, and the drained buffer is cleared after the last+ page.++ Figure 1. One table of an ``obs_table.h`` instance. The export swaps+ the buffers, renders the drained one and clears it after its last page.++The first serializer run of an export swaps the buffers. The serializer+then renders the drained buffer, page by page, and clears it after the+last page. If an export stopped before its last page, the next swap finds+the drained buffer still full: it counts those records as ``lost``,+clears the buffer and goes on. Every page starts with a header record that+carries the interval's start, the number of records, the ``overflow`` and+``lost`` counts, and the time the serializer ran on the boot-time clock,+which a decoder uses to turn record timestamps into wall-clock time.++A serializer is named after a map, and the builder requires that map to+exist. When all tables live in one arena, a table has no map of its own,+so ``kernel-obs`` declares a one-entry array map per table, ``exec``,+``net`` and the others, to carry the name the serializer, the decoder and+the operator use.++The arena's pages are allocated once, after the programs are attached, by+the upatch's test-run program ``shirudo_test__<id>``, which shirudo runs at+load. The kernel binds a program to an arena only when the program refers to+the arena map directly, so ``kernel-obs`` makes a no-op allocation call on a+cold path in every program that dereferences arena pointers it did not+allocate itself.++Serializer interface+--------------------++A serializer is a ``SEC("syscall")`` program named+``shirudo_serialize__<map>``. It writes into ``shirudo_ser``, an array map+with a ``__u32`` key and ``struct shirudo_serial_chunk`` values that the+upatch defines with 1 to 256 entries. ``bpf/lib/shirudo_serializer.h``+holds the definitions. The builder refuses a serializer that is not in+``SEC("syscall")``, targets a map that does not exist or is+``shirudo_ser`` itself, or duplicates another one, and refuses an upatch+with a serializer and without a valid ``shirudo_ser``.++``shirudo upatch map`` runs the serializer with ``BPF_PROG_TEST_RUN``,+once per page:++.. list-table::+ :header-rows: 1+ :widths: 28 72++ * - Context field+ - Meaning+ * - ``magic``, ``version``+ - ``SHIRUDO_SERIAL_MAGIC`` and ``SHIRUDO_SERIAL_VERSION``, 3+ * - ``flags``+ - ``SHIRUDO_SERIAL_CTX_F_PEEK`` when the reader asks for a peek+ * - ``max_chunks``+ - the number of entries of ``shirudo_ser``+ * - ``chunk_payload_size``+ - 4032, the payload bytes of one chunk+ * - ``page_index``+ - 0 for the first page, then 1, 2 and so on+ * - ``cursor``+ - 0 for the first page, then the previous page's ``next_cursor``+ * - ``invocation_id``+ - a random number that is the same for every page of one read++Before each run, shirudo clears ``shirudo_ser``. The serializer fills+chunks 0 to ``total_chunks - 1``, each a 64-byte header and 4032 bytes of+payload. Every chunk carries its own ``chunk_index`` and repeats the+page's ``total_chunks``, ``page_index``, ``cursor``, ``next_cursor``,+``invocation_id`` and ``bytes_total``. On the last page, chunk 0 has+``SHIRUDO_SERIAL_F_DONE`` in ``flags``. A negative return or a non-zero+``status`` in a chunk fails the read. shirudo checks the+magic, the version, the invocation id, the page index and cursor, the+chunk count and the byte counts, concatenates the chunks' payloads into a+page, and runs the serializer again with ``next_cursor`` until a page is+done. A page that is not done and does not advance the cursor fails the+read, and so does a read that is not done after 256 pages. A lock keyed by+the id of ``shirudo_ser`` keeps two readers of the same upatch apart.++The cursor's meaning belongs to the serializer: an index into a table, a+position in a tree walk, anything that lets the next run continue where+the last one stopped.++Draining and peeking+--------------------++Whether a read consumes the data is the serializer's decision. shirudo+passes one flag, ``SHIRUDO_SERIAL_CTX_F_PEEK``, and nothing else. The+convention every shipped serializer follows: without the flag, the read+drains. It hands over the interval collected since the previous export+and resets it, as ``obs_table.h`` does with its swap and clear. With the+flag, it reads the interval that is still being collected and changes+nothing, and ``obs_table.h`` marks such a page header as a peek.++On a target, ``shirudo-map-export.timer`` runs ``shirudo upatch map+--all`` five seconds after each previous run, and every such run drains.+A manual ``shirudo upatch map <upatch> <map>`` drains too and takes the+records away from the exporter. Add ``--peek`` to look without taking.++What the export reads+---------------------++``shirudo upatch map`` reads the pins under+``/run/shirudo/bpffs/upatches/<name>/``. For each map, it runs the map's+serializer when the upatch pinned one and collects the pages. A map+without a serializer it reads directly, key by key, with its BTF types+when the upatch was built with them. The text form shows the first 256+entries unless ``--show-full`` is given. Ring buffers, perf event arrays,+stack trace maps, program arrays and arenas are not read directly. The+``shirudo_ser`` map is not listed, and maps that were not pinned, those+with a dot in the name or the ``obs_i_`` prefix, are not visible at all.++The pages or entries then go to the map's decoder, which turns them into a+log record or a metric. :doc:`decoders` describes that step, and+:doc:`/operate/telemetry` the export to a collector.++Only tasks with shirudo's runtime authority can do any of this. The LSM+refuses ``BPF_PROG_TEST_RUN``, opening a pinned map or obtaining a map+descriptor by id to every other task, root included, so the records reach+the operator only through shirudo's own export path.++Limits+------++- A snapshot covers one export interval. Records from an interval whose+ export stopped part way are counted as ``lost``, not delivered.+- One read returns at most 256 pages of at most 256 chunks of 4032 bytes.+ A table that renders more fails the read with ``E2BIG``.+- Draining is a convention of the serializer, not something shirudo+ enforces. A serializer that ignores the peek flag drains on a peek.+- The arena's size is fixed when the upatch is built. A larger table means+ a new build and a new load.++Related+-------++- :doc:`attach-kinds` for the serializer and test-run roles.+- :doc:`examples` for ``kernel-obs``, which uses this template for all+ its tables.+- :doc:`/reference/cli/upatch-map` for the command's options.diff --git a/Documentation/upatches/publishing.rst b/Documentation/upatches/publishing.rstnew file mode 100644index 00000000..9280e653--- /dev/null+++ b/Documentation/upatches/publishing.rst@@ -0,0 +1,169 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: upatch authors++Publish a package+=================++Publishing makes a package reachable for targets in two ways. ``bpm+push`` puts it into an OCI repository and adds it to the registry's+signed index, for targets that install packages by name. ``bpm tree+append`` adds its tree entries to an upatch tree, for targets that follow+the tree without naming anything. The registry only transports: targets+verify the operator's signatures on the index, the tree and every upatch.++Before you begin+----------------++- An operator host with the operator package installed, or a checkout+ with ``shirudo-build`` on the path, as :doc:`/reference/cli/build`+ describes.+- The signing key whose certificate your targets trust, in a key+ directory. The same key signs the upatches, the index and the tree.+- A package directory with a Beefile, as :doc:`beefile` describes, whose+ upatches you have tested, as :doc:`testing` describes.+- Push access to an OCI registry. shirudo reads credentials from+ ``BPM_OCI_USERNAME`` and ``BPM_OCI_PASSWORD``, ``BPM_OCI_BEARER_TOKEN``,+ ``REGISTRY_AUTH_FILE`` or the Docker configuration, and an extra CA+ from ``BPM_OCI_CA_FILE``. :doc:`/reference/environment` lists them.++Build the package+-----------------++1. Build and sign the package:++ .. code-block:: console++ operator$ shirudo bpm build <package-dir> --version <version> \+ --keys-dir <keys-dir>++ ``<package-dir>`` holds the ``Beefile``; pass ``-f <file>`` for a+ Beefile with another name. ``<version>`` is the new version and+ ``<keys-dir>`` your key directory. The command prints the path of+ ``<name>-<version>.bee``, which it writes into the current directory.++ Targets order versions by their numeric ``major.minor.patch`` and+ upgrade to the highest, and the signed index refuses a version it+ already lists with other content. Give every build that leaves the+ operator host a new version.++2. Read the package back:++ .. code-block:: console++ operator$ shirudo bpm info <name>-<version>.bee+ operator$ shirudo bpm info upatches <name>-<version>.bee --all++ The first command prints the ``README.md`` the package carries, the+ second its load and unload artifacts. ``shirudo bpm key fingerprint+ <name>-<version>.bee`` prints the fingerprint of the signing+ certificate the package carries.++Push it to a repository+-----------------------++3. Push the package and add it to the signed index:++ .. code-block:: console++ operator$ shirudo bpm push <name>-<version>.bee \+ oci://<registry>/<namespace>/<name> --keys-dir <keys-dir>++ ``<registry>`` is the registry's host and ``<namespace>/<name>`` the+ repository, without a tag. The command uploads the package as an OCI+ artifact, attaches the package's certificate to it as a referrer, adds+ the version with the package's digests to the index at+ ``shirudo/bpm-index:stable`` in the same registry, signs the index+ with your key, and tags the package with its version. It prints the+ pushed reference, ``oci://<registry>/<namespace>/<name>:<version>``.++ Without ``--keys-dir``, or ``--index-cert`` and ``--index-key``, the+ command pushes the package and moves the version tag, but leaves the+ index unchanged and does not check that the version is new. Targets+ that install by name do not see such a push.++4. Verify that the registry serves the package:++ .. code-block:: console++ operator$ shirudo bpm info oci://<registry>/<namespace>/<name>:<version>++ The command downloads the package and prints its ``README.md``.++Append it to the tree+---------------------++5. Publish the package's ``[upatches.tree]`` entries as ``add``+ operations:++ .. code-block:: console++ operator$ shirudo bpm tree append <name>-<version>.bee \+ oci://<registry>/<namespace>/<tree> --keys-dir <keys-dir>++ ``<tree>`` is the tree's repository. The command fetches the current+ publication at ``<tree>:stable`` and verifies its signature against+ your certificate. For every entry it checks that the artifact is a+ load directive whose upatch name equals the entry's ``id``, pushes the+ artifact as an artifact of its own, and appends an operation with the+ entry's selector. It then signs the next generation, which names the+ previous publication's digest as its parent, and prints the tree's+ reference and new digest.++ A repository without a publication starts a new tree at generation 1,+ with the package name as tree id or the id ``--tree-id`` gives. For an+ existing tree, ``--tree-id`` must name the id it has. ``--reference+ <ref>`` publishes to another tag than ``stable``, such as a canary+ tree.++6. To withdraw an entry, publish its unload directive as a ``delete``:++ .. code-block:: console++ operator$ shirudo bpm tree append <name>-<version>.bee \+ oci://<registry>/<namespace>/<tree> --keys-dir <keys-dir> --op delete++ Nothing is ever removed from the tree: a ``delete`` is a new operation+ after the ``add``. To replace a loaded upatch with a new build of the+ same name, append the ``delete`` of the old package first and the+ ``add`` of the new one after it, since a target cannot load a second+ upatch under a name that is already loaded.++What a target does with them+----------------------------++A target learns its repositories, their index certificates and the tree+it follows from its signed config image.+:doc:`/operate/deliver-packages` shows the setup.++For a package by name, ``shirudo bpm repo update`` fetches the index and+verifies its signature. ``shirudo bpm install <source>/<name>`` checks the+package's manifest and archive against the digests in the index, refuses+a package whose ``cert.der`` has another public key than the target's+``/var/lib/shirudo/keys/cert.der``, and loads every+``upatches/*.upatch`` of the package, each one measured. The+``shirudo-bpm-repo-update.timer`` runs ``bpm repo update`` and then+``bpm upgrade`` at boot and a minute after each run, so a pushed version+reaches the targets that have the package installed within minutes.++For the tree, ``shirudo-bpm-tree-sync.timer`` runs ``bpm tree sync``+every minute. It fetches the publication, verifies the signature, the tree+id and the chain of parent digests, and goes through the operations it has+not seen in order. For each one whose selector matches, it fetches the+artifact once, checks its payload digest, name and kind against the+operation, loads or unloads it, and measures the operation. An operation+whose selector does not match is passed over for good.++The kernel verifies the signature of every upatch at load in either case,+whatever the registry served.++Next steps+----------++- :doc:`/reference/formats/bpm-formats` for the index and the tree+ documents.+- :doc:`/operate/deliver-packages` to configure targets.+- :doc:`/operate/attest` to verify what targets loaded.diff --git a/Documentation/upatches/testing.rst b/Documentation/upatches/testing.rstnew file mode 100644index 00000000..5ec3b396--- /dev/null+++ b/Documentation/upatches/testing.rst@@ -0,0 +1,210 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: upatch authors++Test an upatch on a target+==========================++Load an upatch on a real target before it ships, read what it records,+and unload it again. The test VM in a shirudo checkout is such a target:+it boots the dm-verity runtime image and a signed config image from a+dracut initrd, with a software TPM, and runs ``shirudo init`` there as a+production target does. This page uses it, and the commands on the target+are the same elsewhere.++Before you begin+----------------++- A shirudo checkout built with ``make`` and ``make shirudo-build``.+- A Linux host with KVM, root, and the host packages the test VM needs,+ listed in :doc:`/contribute/testing`.+- An upatch and its unload directive, built as in+ :doc:`kernel-fix-tutorial`, or one of the signed fixtures below.++Boot the test VM+----------------++1. Boot an interactive VM from the checkout's root:++ .. code-block:: console++ # make -C testing vm VM_NAME=upatch-dev++ ``VM_NAME`` is optional and names the VM for the commands below. The VM+ boots a bpf-next kernel by default. ``KERNEL=7.4``, or a later release,+ boots that release instead. The first run builds the kernel and the+ bundle of signed images and fixtures, which takes a while. The command+ returns once the VM is ready.++2. Open a shell on it:++ .. code-block:: console++ # make -C testing vm-ssh VM_NAME=upatch-dev++ Without ``VM_NAME``, ``vm-ssh`` opens the most recently started VM.++3. Check that enforcement is up:++ .. code-block:: console++ target# shirudo-runtime status+ Host: upatch-dev+ Roles: target+ Mode: production+ Status: ok+ ...++ The ``Status:`` line reads ``ok``. In the VM, run every shirudo command+ as ``shirudo-runtime``. It executes shirudo from the verified runtime+ image, and only a process started from that image has shirudo's runtime+ authority. The plain ``shirudo`` in the VM, ``/usr/local/bin/shirudo``,+ is the same binary outside the runtime image. Every command of it that+ reads shirudo's state stops with ``shirudo: image state: Permission+ denied``.++Get the upatch into the VM+--------------------------++4. Sign the upatch and its unload directive with the key the VM enrolled.+ The bundle keeps it in+ ``build/test-vm/host-bundle-<kernel>-verity.operator/keys``, where+ ``<kernel>`` is ``bpf-next`` or ``v`` and the release, such as+ ``v7.4``. Pass that directory to ``shirudo build --keys-dir``, as+ root: the bundle belongs to the user who built the VM.++5. Put both files under the checkout, for example under ``build/``. The VM+ sees the checkout read-only at ``/mnt/shirudo-src``, so+ ``build/rpl-shield/cve-2026-63984-rpl.upatch`` on the host is+ ``/mnt/shirudo-src/build/rpl-shield/cve-2026-63984-rpl.upatch`` in the+ VM.++Load and observe it+-------------------++6. Load the upatch and keep the report:++ .. code-block:: console++ target# shirudo-runtime upatch load --report=/tmp/load.json \+ /mnt/shirudo-src/<path>.upatch++ ``<path>`` is the upatch's path in the checkout. The command exits with 0+ on success, 2 when an attach target is missing or the command line is+ wrong, and 1 on any other failure. The report's ``category`` says why,+ and :doc:`debugging` goes through each one. To refuse the load unless the+ measurement register still holds a value you read before, add+ ``--expect-chain=<chain>``, with ``<chain>`` the ``tpm.chain`` field of+ ``shirudo-runtime status --json``.++7. List what is loaded and archived:++ .. code-block:: console++ target# shirudo-runtime upatch list++8. Show where the upatch attached, its program source lines and its maps:++ .. code-block:: console++ target# shirudo-runtime upatch get <name>++ ``<name>`` is the upatch name, which ``shirudo upatch info`` shows on+ the operator host.++9. Run the workload or the reproducer that should reach the hooked code,+ then read a map without draining it:++ .. code-block:: console++ target# shirudo-runtime upatch map <name> <map> --peek++ ``shirudo-runtime upatch map <name>`` lists the upatch's maps. A map+ with a serializer is rendered by it, and ``--peek`` asks the serializer+ to leave the records for the exporter. Add ``--json`` to see what the+ map's decoder returns. For a map without a decoder, ``--json`` fails+ with ``upatch map: print JSON: No data available``.++Unload it+---------++10. Apply the unload directive:++ .. code-block:: console++ target# shirudo-runtime upatch unload --report=- \+ /mnt/shirudo-src/<path>.unload.upatch++ The report shows category ``ok``. ``already_unloaded``, with exit+ status 0, means nothing of that name was loaded. ``payload_mismatch``,+ with exit status 1, means the directive was built for another build of+ the upatch, and the upatch stays loaded.++11. Verify that the upatch is gone and the target is still healthy:++ .. code-block:: console++ target# shirudo-runtime upatch list+ target# shirudo-runtime status++ The upatch is not listed, and ``status`` still reads ``ok``. Every+ load and unload moved the measurement register forward.++12. Leave the VM shell, and stop the VM on the host when you are done:++ .. code-block:: console++ # make -C testing vm-stop VM_NAME=upatch-dev++ Without ``VM_NAME``, ``vm-stop`` stops every VM it tracks. The VM's+ state stays under ``build/test-vm/vms/``.++Use the signed fixtures+-----------------------++The bundle carries upatches signed with the same key, in the VM at+``/mnt/shirudo-bundle/fixtures/``, those below with an ``.unload.upatch``+beside them. Their sources are in ``testing/fixtures/``. They are handy for+trying the commands above or for comparing your upatch with a known good+one.++.. list-table::+ :header-rows: 1+ :widths: 38 62++ * - Fixture+ - What it shows+ * - ``shirudo-test-basic``, ``shirudo-test-marker``+ - an ``fentry`` program on ``do_nanosleep`` and nothing else+ * - ``shirudo-test-map-export``+ - two maps, one with a log decoder and one with a metric decoder+ * - ``shirudo-test-otel-backend``+ - log and metric decoders for the OTLP export+ * - ``shirudo-test-serialized-metric``+ - a serializer over an array map, with a metric decoder+ * - ``shirudo-test-arena-tree``+ - a binary tree in an arena, rendered by a serializer+ * - ``shirudo-test-uprobe-multi``+ - ``uprobe.multi`` on ``/tmp/shirudo-test-uprobe-target``. Copy+ ``shirudo-test-uprobe-target`` from the fixtures to that path first.+ * - ``shirudo-test-scope-cgroup``, ``shirudo-test-scope-netfilter``,+ ``shirudo-test-scope-kprobe``+ - ``cgroup_skb``, ``netfilter`` and ``kprobe`` attachments and the+ attach-scope check+ * - ``kernel-obs``+ - the upatch of the ``kernel-obs`` package++The test VM's kernel configuration has no kprobes, so the kprobe fixture+fails there with ``attach_target_missing``, which shows what that+category looks like.++Next steps+----------++- :doc:`debugging` when a load fails.+- :doc:`publishing` once the upatch works.+- :doc:`/contribute/testing` for the automated tests that boot the same+ VM.diff --git a/Makefile b/Makefileindex a67f333a..5091dda9 100644--- a/Makefile+++ b/Makefile@@ -50,7 +50,7 @@ export prefix exec_prefix bindir libexecdir sharedir libdir mandir completionsdisystemdunitdir dracutmodulesdir SHIRUDO_TARGET_PKG_CONFIG_PATH \SHIRUDO_TARGET_STATIC_LIBDIR-.PHONY: all help target target-deps target-deps-clean shirudo-target target-config shirudo-build bpf-deps install install-target install-operator clean distclean config tests+.PHONY: all help target target-deps target-deps-clean shirudo-target target-config shirudo-build docs bpf-deps install install-target install-operator clean distclean config testsall: config+$(Q)$(MAKE) -f Makefile.shirudo PROFILE=operator CONFIG_MK=config.mk all@@ -90,12 +90,15 @@ help:' Install roles: make install-target, make install-operator' \' Package: make -C packaging help' \' Tests: make tests (all of them), make -C testing help' \- ' Documentation: make -C Documentation html-docs' \+ ' Documentation: make docs (render and serve), make -C Documentation help' \' Watch lists: make -C upatches/kernel-obs lists'shirudo-build:+$(Q)$(MAKE) -C tools/shirudo-build+docs:+ +$(Q)$(MAKE) -C Documentation serve+tests:+$(Q)$(MAKE) -C testingdiff --git a/README.md b/README.mdindex af2ae0fd..8ce94a82 100644--- a/README.md+++ b/README.md@@ -30,22 +30,23 @@ into the fleet.## Getting Started-* [Getting started](Documentation/getting-started.rst): build, sign,- initialise a target, load and unload, publish and install packages-* [Architecture](Documentation/architecture.rst): why shirudo exists,- its design properties and how all fits together-* [Requirements](Documentation/requirements.rst): kernel requirements,- operator toolchain, target runtime-* [Threat model](Documentation/threat-model.rst): trust boundaries,- the threats addressed and residual risks-* [Telemetry](Documentation/telemetry.rst): the OTLP export and how- to integrate with collectors-* [Features](Documentation/features.rst): every supported attachment- type a upatch can have-* [Operations](Documentation/operations.rst): watching a target,- upgrades, decommissioning, backup, recovery and more--The full index is in [Documentation/index.rst](Documentation/index.rst).+* [Quickstart](Documentation/start/quickstart.rst): build shirudo, boot+ a protected test target and take one upatch through load, attestation+ and unload+* [System requirements](Documentation/operate/system-requirements.rst):+ the kernel, the operator host and the target runtime+* [Architecture overview](Documentation/internals/architecture.rst): how+ the pieces fit together+* [Threat model](Documentation/security/threat-model.rst): what shirudo+ protects, against whom, and where each mechanism stops+* [Operate](Documentation/operate/index.rst): deploying, monitoring,+ upgrading and troubleshooting targets+* [upatches](Documentation/upatches/index.rst): writing, testing and+ publishing upatches++`make docs` renders the documentation and serves it on+http://127.0.0.1:8000; the sources start at+[Documentation/index.rst](Documentation/index.rst).## Releases@@ -61,7 +62,7 @@ start, each release tag publishes its packages onand the actively maintained releases are listed here.For upgrades of shirudo and the kernel on a target, consult-[Operations](Documentation/operations.rst).+[Upgrade shirudo and the kernel](Documentation/operate/upgrade.rst).### Architecturesdiff --git a/include/shirudo/upatch.h b/include/shirudo/upatch.hindex f7917ba4..9b3b2677 100644--- a/include/shirudo/upatch.h+++ b/include/shirudo/upatch.h@@ -18,7 +18,7 @@* The PKCS#7 signature covers insns || data (the gen_loader metadata* blob), verified by the kernel at load time; payload_sha256 is SHA-256* of that same concatenation. See the kernel's Documentation/bpf/signing.rst- * and Documentation/upatch-spec.rst in this tree.+ * and Documentation/reference/formats/upatch-format.rst in this tree.*/#define SHIRUDO_UPATCH_VERSION 1u#define SHIRUDO_UPATCH_HEADER_SIZE 360udiff --git a/testing/ci-checks/t0002-check-spdx.sh b/testing/ci-checks/t0002-check-spdx.shindex dd73b90a..2494fd44 100755--- a/testing/ci-checks/t0002-check-spdx.sh+++ b/testing/ci-checks/t0002-check-spdx.sh@@ -52,7 +52,7 @@ put "$R/vendor/libbpf/bpf/bpf_helper_defs.h" '/* This is auto-generated file. */put "$R/vendor/README.md" 'no tag here'put "$R/vendor/linux/vmlinux.h" 'struct task_struct;'put "$R/pkg/vmlinux.h" 'struct task_struct;'-put "$R/Documentation/coding-style.rst" 'Linux kernel coding style'+put "$R/Documentation/contribute/coding-style.rst" 'Linux kernel coding style'put "$R/bpf/lsm.c" '// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause' \'#include "vmlinux.h"' '#include <bpf/bpf_helpers.h>' '#include "common.h"'put "$R/bpf/lib/common.h" '/* SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause */'diff --git a/testing/functional/signing/t2002-mldsa-sign.sh b/testing/functional/signing/t2002-mldsa-sign.shindex f27abca8..eadfb2b2 100755--- a/testing/functional/signing/t2002-mldsa-sign.sh+++ b/testing/functional/signing/t2002-mldsa-sign.sh@@ -87,7 +87,7 @@ test_expect_success 'shirudo-build refuses to sign with an ML-DSA-65 key' 'test_skip_all "build failed (clang/headers?)"# Slice the signature and the signed bytes out of the artifact using the-# fixed v1 header offsets (Documentation/upatch-spec.rst).+# fixed v1 header offsets (Documentation/reference/formats/upatch-format.rst).python3 - "$WORK/u.upatch" "$WORK" <<'PY'import struct, syspath, out = sys.argv[1], sys.argv[2]diff --git a/testing/swtpm.sh b/testing/swtpm.shindex 6ec8f2ea..27c964ab 100755--- a/testing/swtpm.sh+++ b/testing/swtpm.sh@@ -3,8 +3,7 @@# Copyright (c) 2026 Authors of shirudo## testing/swtpm.sh -- spin up a software TPM 2.0 (swtpm) on loopback for-# shirudo dev and CI. Same recipe as Documentation/getting-started.rst-# "TPM in development", packaged so a single command brings the emulator+# shirudo dev and CI, packaged so a single command brings the emulator# up, prints the SHIRUDO_TPM_TCTI line to export, and tears it down.## Usage:diff --git a/tools/gen-initrd/install.sh b/tools/gen-initrd/install.shindex 834f2e51..32b7cf40 100755--- a/tools/gen-initrd/install.sh+++ b/tools/gen-initrd/install.sh@@ -6,8 +6,9 @@# place the operator's certificate, put the kernel parameter the bpf# keyring needs on the boot command line and rebuild the initrd with# shirudo inside, so that the next reboot comes up in the production-# configuration (Documentation/initrd.rst). Runtime and signed config-# images must be provisioned separately before the authenticated UKI is rebuilt.+# configuration (Documentation/internals/boot-flow.rst). Runtime and signed+# config images must be provisioned separately before the authenticated UKI+# is rebuilt.## curl -fsSL https://raw.githubusercontent.com/shirudo-dev/shirudo/main/tools/gen-initrd/install.sh |# bash -s -- --cert https://example.com/shirudo/cert.derdiff --git a/tools/gen-initrd/module-setup.sh b/tools/gen-initrd/module-setup.shindex e107b335..2532899b 100755--- a/tools/gen-initrd/module-setup.sh+++ b/tools/gen-initrd/module-setup.sh@@ -4,7 +4,7 @@## dracut module "shirudo": put shirudo into the initrd so that# shirudo-initrd.service brings enforcement up before the switch to the-# root file system (Documentation/initrd.rst).+# root file system (Documentation/internals/boot-flow.rst).## Everything is taken from the installed system; a dracut.conf(5) file# can point elsewhere, which is how the test VM builds an initrd from a