eBPF-based security platform
docs: explain image setup and config updates
KP Singh07264af27319
diff --git a/AGENTS.md b/AGENTS.mdindex 89d70713..9756dfd0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -167,22 +167,27 @@ building and passing on its own.Each of these is enforced by the design, not by a compiler. Breakingone usually still compiles and passes tests.-- **No subprocesses, no daemons.** The core `shirudo` binary never- forks or execs on either side; every external operation goes through- a linked library. The single exception is the operator-only dispatch- in `builtin-build.c`: `shirudo build` and the operator bpm commands- exec the separate `shirudo-build` binary, which signs in-process and- execs `clang`. `shirudo-build` and `clang` ship only in the operator- package, so the invariant is absolute on every target-side path. A- feature that seems to need a shell-out needs a library binding, not- `system(3)`.+- **No target subprocesses, no daemons.** Target operations in the core+ `shirudo` binary use linked libraries and kernel APIs. Operator commands+ dispatch to the separate `shirudo-build` helper. That helper signs+ in-process, executes `clang` for BPF compilation and executes the standard+ `veritysetup` tool for image formatting and offline verification. Those+ external tools are operator-only dependencies. Target image preflight+ checks the standard verity superblock and root. The kernel verifies config+ signatures through its dm-verity trust path; runtime acceptance requires+ the exact UKI root. A strict read-only mapping is read completely before+ parsing contents or extending the activation PCR. Config signatures cover+ exactly the 64 lowercase ASCII root bytes and never authorize executables.+ Do not add a target shell-out or a custom userspace verity hash-tree+ implementation.- **Operator code does not ship to targets.** Signing (`util/sign.c`)and the package builder and publisher (`tools/shirudo-build/`) arelinked only into `shirudo-build`. The core binary only dispatches.-- **The signature-gated `BPF_PROG_LOAD` is the trust boundary.** Every- signed artifact (the LSM bootstrap, every load and unload directive)- goes through the same load path; a second loading path is wrong.- Userspace may attach, pin and run the signed-loader data-map+- **The signature-gated `BPF_PROG_LOAD` is the upatch trust boundary.**+ Every signed load and unload directive goes through the same load path.+ The embedded LSM bootstrap loads during `init`, before its admission+ gates attach. Production deployments authenticate it through the initrd.+ Authorized Shirudo tasks may attach, pin and run the signed-loader data-mappattern, because none of those can introduce unsigned code; detach,update and corruption of BPF objects from userspace are denied by theLSM. In the `lsm/bpf` hook the `bool kernel` argument is the@@ -190,9 +195,9 @@ one usually still compiles and passes tests.userspace calls are filtered.- **The operator never touches the kernel keyring or the TPM; thetarget never touches the private key.**-- **The bpf keyring is the trust anchor; the user keyring is staging.**- `init` enrols the trusted set in the kernel's `.bpf` keyring and- seals it, which needs the kernel booted with `bpf.keyring_unsealed=1`+- **The bpf keyring is the trust anchor.** In ordinary mode, the user+ keyring provides staging. `init` enrols the trusted set in the kernel's+ `.bpf` keyring and seals it, which needs the kernel booted with `bpf.keyring_unsealed=1`and `init` run from the initrd; a kernel that sealed it empty at bootmakes `init` stage the primary certificate alone in a sealed`shirudo` user keyring until the next reboot. The set (`util/keys.c`)@@ -206,18 +211,24 @@ one usually still compiles and passes tests.keyring that record says, `lsm/bpf_prog_load` admits only that kind,and for a staged user keyring only that serial (the kernel recordsnone for its own bpf keyring), and `lsm/key_permission` lets shirudo- alone write, unlink, revoke or invalidate the keyring and its keys.- `keys revoke` is the only way a key leaves during a boot: marker in+ alone write, unlink or revoke the keyring and its keys. Staging has a+ reproduced invalidation exception through possessed `KEY_NEED_SEARCH`+ references.+ `keys revoke` is the ordinary authorized revocation path: marker in`revoked/` first, then the unlink, the measured `key_revoke` eventand the purge of everything the key signed. There is no file pin to- forge or lose.+ forge or lose. Image mode requires the `.bpf` keyring and refuses+ staging. It enrols the verified config's signer set at boot. Live+ signed config activation can revoke an enrolled signer and purge its+ upatches, but cannot enrol a new signer. Local `keys add` and+ `keys revoke` are refused in image mode.- **The operator is stateless.** It writes only the keypair (`genkey`)and the artifacts or reports the caller names. No hidden caches,state files, logs or staging directories; `--expect-chain` comesfrom the caller or from `shirudo attest predict`.-- **Every target state change extends the TPM measurement register**- with a domain-separated tag, in deterministic order, and refuses on- drift (`tampered`) rather than retrying. Boot restore is exactly one+- **Upatch state changes extend the TPM measurement register**+ with a domain-separated tag, in deterministic order. Commands refuse+ on drift (`tampered`) rather than retrying. Boot restore is exactly oneregister event and a re-run of `init` adds none. The register followssystemd's NvPCR construction (`util/chain.c`): an NV extend index thatclears at TPM reset, a first write only possible while PCRs 9 and 11@@ -227,7 +238,12 @@ one usually still compiles and passes tests.persistent index oran auth value derived from the certificate; the upatch tree measuresinto the same register. A TPM 2.0 is mandatory; there is no- unmeasured mode.+ unmeasured mode. Image config activation extends the separate PCR+ selected in authenticated bootstrap settings. A durable pending selection+ requires manual reboot after any interruption; Shirudo never reboots the+ node automatically. There is no same-boot recovery or+ ambiguous-extension retry. Trusted startup verifies that selection and+ records a fresh BOOT event before completing initialization.- **Evidence is signed by the TPM, verified by the operator.** Theattestation key is a fixed-template primary under the endorsementhierarchy, pinned by name and tied to the endorsement key by@@ -239,7 +255,7 @@ one usually still compiles and passes tests.value the target wrote about itself is not a check.- **Pin the bpf_link before anything else fallible** in `shirudo init`,or a crash leaves an attached, unowned link that the kernel detaches.-- **init runs twice in production and the two halves are fixed.** The+- **init runs twice in production.** In ordinary mode, theinitrd run (`shirudo-initrd.service`, detected by `/etc/initrd-release`with the root at `/sysroot`) enrols the initrd's own`/etc/shirudo/keys/cert.der`, attaches the LSM with its pins under@@ -250,17 +266,40 @@ one usually still compiles and passes tests.root run labels the tree and adopts that record. Anything else theinitrd would write to the root is wrong: the root is read-only there,and `/run` is the only thing systemd carries across switch-root- besides the API file systems. Non-systemd initrds are unsupported.+ besides the API file systems. Image mode instead requires writable+ persistent state during initrd startup, binds it writable and labels+ it before attaching enforcement. Config activation writes its durable+ image cache and pending selection there. The initrd enrolls the config+ certificate into the kernel's .dm-verity keyring and seals it; built-in+ dm-verity trust remains accepted. Executable authority comes from a task+ mark committed after successful exec from the trusted runtime image;+ the authenticated bootstrap task has temporary authority to complete+ initialization. Non-systemd initrds are unsupported.+- **Seal labels mark targets, not caller authority.** Ordinary mode+ authorizes the frozen executable device/inode or its initrd copy; image+ mode authorizes the committed task mark. A copied label grants neither.+ Only an authorized caller may set the exact seal xattr. The seal checks+ labelled targets on write open, unlink, both rename endpoints, setattr+ and xattr changes. Ordinary mode allows replacing the recorded primary+ executable for upgrades without granting its replacement authority.+ Label read errors require authority except ENODATA, EOPNOTSUPP, EACCES+ and EPERM; scratch allocation failure also requires authority. The seal+ labels new inodes during creation when the parent has a cached directory+ mark. Writers hold an open parent directory to retain that mark. Directory+ eviction and foreign link/rename entries remain limitations; existing+ writable descriptors and mappings are not revoked.- **Single shirudo instance per host.** Keyring name, private bpffs,`/var/lib/shirudo`, the `security.bpf.shirudo` xattr namespace andthe NV index are single-tenant by design.- **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.** Linux v7.4 or newer- and current clang/LLVM are hard prerequisites. No legacy-kernel detection, no- runtime feature-probe fallbacks; a missing kernel feature fails the- build or the load. x86-64, arm64 and riscv64 are the supported- architectures.+- **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.- **BPF is CO-RE.** Hard-coded struct offsets sign fine and fail on thewrong kernel as `btf_mismatch`.- **Upatch state lives in BPF arenas where possible.** A upatch thatdiff --git a/Documentation/architecture.rst b/Documentation/architecture.rstindex 02289d84..e067231e 100644--- a/Documentation/architecture.rst+++ b/Documentation/architecture.rst@@ -35,9 +35,11 @@ runs. The payload program is hash-locked to the loader(``excl_prog_hash``), so a signature over a few kilobytes of loadercovers every instruction that ends up attached.-Everything else follows from that. The kernel-side enforcement is a-set of BPF LSM programs that shirudo loads through the same signed-path. Every state change extends a per-boot TPM measurement register+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 registeranchored in a PCR, so an operator predicts from the signed set what atarget must report and has the TPM certify that it does.The userspace side is one binary with git-like subcommands; on the@@ -117,11 +119,12 @@ 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 execs clang; the core binary only execs the helper with the-argument vector. That exec is the single subprocess in shirudo, and it-exists only in the operator package. The operator never opens the TPM-or the kernel keyring, and persists nothing but the keypair and the-files the caller names.+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 canresolve ``shirudo-build``. The installed operator package provides the@@ -205,10 +208,21 @@ target ELF's GNU build ID. The format specification has the encoding.6) Enforcement in the kernel-----------------------------Two BPF objects are embedded in the binary and loaded by ``shirudo-init`` through the signed path: ``bpf/bpf2.c`` guards the ``bpf()``-syscall and the private bpffs, ``bpf/seal.c`` guards shirudo's files-and processes. Both are BPF LSM programs. Their verdicts compose with+The ordinary installation uses the executable identities and seal described+below. The opt-in dm-verity mode uses an authenticated executable image+and committed task authority instead; its differences follow at the end of+this section and in `config-images <config-images.rst>`__.++Two BPF objects are embedded in the binary: ``bpf/bpf2.c`` guards the+``bpf()`` syscall and the private bpffs; ``bpf/seal.c`` guards shirudo's+files and processes. ``shirudo init`` opens these embedded objects and loads+them with ``bpf_object__load()`` before attaching the BPF admission gates.+They 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+bootstrap 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 withSELinux, AppArmor, SMACK and Yama to the most restrictive result, andthey never override another LSM's deny.@@ -225,12 +239,12 @@ its maps. Allowed without a signature are the commandsthat cannot introduce code: map create only from the executable``init`` recorded as shirudo (signed-loader map creation runs in kernelcontext and is already allowed), map update and freeze only from-shirudo's executable, object pin, link create and raw tracepoint open-(a program fd is only obtainable from a signed load or from an-already-vetted program), and the read-only commands (``*_GET_FD_BY_ID``,+shirudo's executable, and object pin, link create and raw tracepoint open+only from shirudo's executable. In image mode these operations require+committed task authority instead. 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``) that keep+``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@@ -294,49 +308,58 @@ keys from being added; this stops root from taking them away, so thatunlinking a key is ``shirudo keys revoke`` and nothing else.``lsm/sb_umount``, ``lsm/move_mount``,``lsm/sb_mount`` and ``lsm/sb_remount`` deny unconditionally, for every-caller including shirudo, any unmount, relocation, mount-over or-remount of that superblock. This last set is load-bearing, not-defence in depth: shirudo is agentless, the pins are the only thing+caller including shirudo, direct unmount, relocation, mount-over and+remount of that superblock. A lazy unmount of a parent mount is not covered;+see residual risk 3 in the threat model and+`issue 22 <https://github.com/shirudo-dev/shirudo/issues/22>`__.+The pins are the only thingkeeping the enforcement programs alive, and one ``umount`` would-otherwise detach everything. Every guard counts what it refuses, by-point, in a frozen map pinned beside the identity map-(``bpf/lib/shirudo_tamper.h``); ``shirudo status`` reads it back.--Filesystem seal. ``bpf/seal.c`` relies on every inode under-``/var/lib/shirudo/`` and the installed binary carrying the xattr-``security.bpf.shirudo`` with one fixed 64-byte value, the same for-every build. The label says what is protected, not who may touch it:-its value is public, and a binary that carries it proves nothing, since-any file system root mounts can present it. The ``file_open`` (for-write), ``inode_unlink``, ``inode_rename``, ``inode_setattr``,-``inode_setxattr`` and ``inode_removexattr`` hooks read the label of the-target inode, both ends of a rename, and, when there is one, allow only-the task that runs the executable ``init`` recorded in the frozen-identity map, the same ``(dev, ino)`` test the bpffs guards use.-``inode_setxattr`` also lets only that task set the label itself, so-root cannot mark files of its choosing. No ``bpf_d_path()``, no path-strings, nothing a bind mount or a mount namespace can confuse.-``bprm_check_security`` and ``bprm_committed_creds`` mark tasks that-exec a labelled binary in task-local storage, ``task_alloc`` inherits-the mark, and ``ptrace_access_check`` and ``perf_event_alloc`` deny-against marked tasks, so a root debugger cannot attach to a running-shirudo and a profiler cannot bind an event to one; a forged label can-only mark its forger. An inode-created under a labelled directory is born with the label:-``inode_init_security`` hands it to the file system inside the-transaction that creates the inode, through-``bpf_inode_init_xattr()``, so a new file of shirudo's never exists-unlabelled. That hook sees the parent as a bare inode and cannot-sleep to read its label, so the seal remembers a labelled directory in-inode storage from the hooks that hold a trusted handle on it:-``file_open`` of the directory, ``inode_post_setxattr`` and-``inode_post_removexattr`` on it, and the creation of a directory-under a marked parent, which marks the child in turn. The label a new-inode gets is its parent's. shirudo's own writers (``util/seal.c``)-open the directory before creating in it, so that it is marked and its-inode stays in memory for the duration, create relative to it, and put-the label on afterwards where the kernel could not, with no seal-attached or on a file system that takes no xattrs at creation.+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. Image-only+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.++Filesystem seal. Initialization labels existing state under+``/var/lib/shirudo/`` and, in ordinary mode, the installed binary with+``security.bpf.shirudo``. The fixed 64-byte label marks a protected target;+its public value does not identify an authorized caller. The ``file_open``+(for write), ``inode_unlink``, ``inode_rename``, ``inode_setattr``,+``inode_setxattr`` and ``inode_removexattr`` hooks require the ordinary+caller's executable to match the frozen ``(dev, ino)`` identity or its+initrd copy. Image mode instead requires committed task authority.+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 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. Ordinary mode permits replacement of+the recorded primary executable for package upgrades; its replacement has+no authority until a later initialization records it. ``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, and+link or rename can introduce an existing unlabelled inode. This does not+authorize every directory-entry change against the parent or revoke+existing writable descriptors and mappings.++In ordinary mode, ``bprm_check_security`` and ``bprm_committed_creds`` mark+tasks that successfully exec a labelled binary, and ``task_alloc`` inherits+the mark. These marks protect processes from observation and do not grant+filesystem mutation authority. ``ptrace_access_check`` and+``perf_event_alloc`` deny against tasks already marked when those hooks+run. The perf allocation check is not serialized with the exec transition;+the separate `perf/exec race investigation <https://github.com/shirudo-dev/shirudo/issues/11>`__+records the source-derived limitation.Process hardening. ``util/harden.c`` runs at startup on the target:``PR_SET_DUMPABLE`` off, ``PR_SET_NO_NEW_PRIVS``, ``PR_SET_PTRACER`` to@@ -349,9 +372,69 @@ either; ``/etc/hosts`` and ``/etc/resolv.conf``, a local resolver stubincluded, still apply. The zeroing allocator in ``util/malloc.c``wipes freed memory; the libc allocators are poisoned project-wide.+Image-mode 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. ``bdev_free_security`` attempts cleanup, but upstream+can omit the notification.+The existing ``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 in image mode.+Trusted image tasks retain control access. No kernel patches are included.+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. Image mode uses the task mark for 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.+7) Target state---------------+The sequence below describes the ordinary installation. Image mode first+verifies and measures the selected config, uses the runtime image's initial+BPF certificate and the config image's vouched keys, and keeps the state+filesystem writable in the initrd for its durable activation journal.+``shirudo init`` is idempotent and runs on every boot from``systemd/shirudo.service`` (``Type=oneshot``, ``KeyringMode=inherit``,extra arguments from ``/etc/shirudo/init.env``), from the initrd in@@ -394,7 +477,8 @@ instead, and the target stays in staging. It does, in order:appends the record an initrd run left under ``/run`` to theeventlog; the initrd run itself skips both, its root beingread-only;-6. loads bpf2 and, unless ``--no-seal``, seal through the signed path,+6. loads the embedded bpf2 object and, unless ``--no-seal``, seal during+ trusted bootstrap, before attaching the BPF admission gates;freezes and pins the identity map (the bpffs, the executable thatkeeps running the target, from the initrd also the initrd's owncopy for that run, the keyring kind and serial, and the serials of@@ -518,7 +602,7 @@ the registry's detached-CMS-signed index at``shirudo/bpm-index:stable``. Published versions are immutable; anindex that already lists a version with other digests is refused.-On the target, ``shirudo bpm config register add <name> oci://host+In the ordinary installation, ``shirudo bpm config register add <name> oci://host--key-file cert.der`` records the registry and the certificate thatmust sign its index. ``shirudo bpm repo update`` fetches and verifiesthe index; ``shirudo bpm install <name>/<pkg>[@ver]`` (or an ``oci://``@@ -530,6 +614,15 @@ 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.+In image mode, 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 JSONdocument (``application/vnd.shirudo.upatch.tree.v2+json``), each@@ -656,10 +749,11 @@ hashes the source tree and build configuration, not binary bytes, sothe same source yields the same identity on x86-64, arm64 and riscv64;the pre-flight refuses a ``version_mismatch``.-shirudo requires Linux v7.4 or newer and the current upstream clang.-There are no fallbacks for older kernels: a missing feature-fails the build or the pre-flight with a message, never a degraded-mode.+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------------------diff --git a/Documentation/config-images.rst b/Documentation/config-images.rstnew file mode 100644index 00000000..fb50b1d6--- /dev/null+++ b/Documentation/config-images.rst@@ -0,0 +1,518 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++Executable and configuration images+===================================++Image mode puts Shirudo's executable and configuration on two separate+read-only dm-verity filesystems. It keeps the host root filesystem and+retains live signed upatch updates. Authenticated bootstrap settings+explicitly select this mode; the ordinary installation remains available.++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 target binary, its ELF interpreter and+libraries, 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 generator packages the ELF interpreter and complete library closure.+The runtime invocation names that interpreter explicitly, disables its+host cache and supplies library paths inside the runtime image. Executable+mappings from elsewhere are denied. A missing runtime library fails the+operation instead of falling back to a host library.++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 and TPM configuration belong in the runtime+image. Config settings that try to override bootstrap settings are refused.+Unknown settings, invalid values and inconsistent export limits are rejected+before the config PCR is extended.+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. It requires ``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 library closure 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 a trusted native input binary: the operator's library inspection runs+its ELF interpreter. Never put private keys in either image.++The helper 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.+It 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.+++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. 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 runtime binary+through its packaged interpreter and library paths. 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 loader 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 ordinary installation's read-only state+bind is unchanged.+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 ordinary 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. This limitation also affects the existing upatch NV register.+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+------------------------++Image mode 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+mode query used to keep commands inside image policy.++The LSM observes dm-verity metadata through the existing+``bdev_setintegrity`` hook. Lookup checks the block-device pointer, device+number and disk sequence. The free hook attempts to delete the record,+but upstream dispatch can skip that notification. Device identity checks+and cleanup are distinct concerns.++The existing ``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. The mount-tree check+was reverted because it blocked systemd service startup. A lazy unmount of+a parent can still detach the bpffs and release its pins when the last+references disappear; `issue 22+<https://github.com/shirudo-dev/shirudo/issues/22>`__ tracks this gap.+The image mount hooks also 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 kernel patches are included.++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 dm-verity implementation uses APIs present at bpf-next commit+``0867b7bfa9de65674c6e599fa21b762b71011b14`` and adds no kernel patches.+Shirudo also requires the signed-BPF kernel interfaces listed in+`requirements <requirements.rst>`__.++The host 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.+Run the existing target suite on an ordinary installation and the+image-mode fixtures on an image installation. The final interruption case+leaves pending state and ends the VM run; it does not automate a reboot. A skipped fixture is not evidence that its protection+passed.+++7) Run both policy modes+-------------------------++The standard harness builds and signs fixtures on the operator and deploys+only public artifacts. Run the complete target suites separately::++ make -C testing test-tgt TEST_VM_MODE=legacy+ sudo make -C testing test-tgt TEST_VM_MODE=verity++Image mode defaults to ``TEST_VM_INITRD=1`` and requires dracut and root on+the host. It refuses disabled sealing and partial suite selections. The+legacy initrd path can also be tested explicitly::++ sudo make -C testing test-tgt TEST_VM_MODE=legacy TEST_VM_INITRD=1++The two modes use separate host bundle caches. Image mode seeds all signed+images into the disposable guest and selects ``config-boot-keys`` for its+initial boot. The runtime test image contains the authority probe and a test-only+interrupted-activation executable. Do not ship these helpers in a deployment+runtime: every runtime executable is eligible for authority.++.. list-table::+ :header-rows: 1+ :widths: 27 36 37++ * - Coverage+ - Legacy mode+ - Image mode+ * - Upatch lifecycle, version and payload checks, TPM replay, uprobes,+ maps and keyring controls+ - Existing target suites+ - Shared target suites using the runtime command+ * - Tree selection, sequential sync, delete and restore+ - Writable fixture configuration+ - Signed tree config activation between publications+ * - OTLP maps, timer service and serializer output+ - Writable fixture configuration+ - Signed telemetry config and runtime service invocation+ * - Local key and repository mutations+ - Existing mutation suites+ - Explicit refusal and guidance; boot enrollment and signed revocation+ * - Executable and config integrity+ - Existing seal and executable-identity suites+ - Task authority, executable mappings, device controls, observers,+ hidden bpffs, signed A/B activation and measured revocation/purge+ * - Interrupted activation+ - Existing host journal tests+ - One exit after PCR measurement; further mutations and attestation+ refuse, then the VM run ends++Required image fixtures and helpers are failures when absent. A whole suite+that skips in image mode fails the runner. Test ordering matters:+boot-signer assertions run before config changes. Revocation removes a+signer for the remainder of the boot; the interruption case runs last+because it leaves the activation pending. Use a fresh test+VM and state for another complete 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_TEST_MODE=verity+ 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++``contrib/verity-vm-config-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, library closure and test helper. The+``image-shirudo`` test wrapper executes the image interpreter explicitly,+with the host loader cache disabled. 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/getting-started.rst b/Documentation/getting-started.rstindex 1be5447e..4e00e84a 100644--- a/Documentation/getting-started.rst+++ b/Documentation/getting-started.rst@@ -10,9 +10,18 @@ checkout to a loaded, measured upatch, and then to packages pulled froma 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-first if the target kernel is older than Linux v7.4 or not built with-the BPF LSM, BTF and ML-DSA enabled. For local development one host-can play both roles.+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.++The target setup and writable configuration examples below describe the+ordinary installation. For image mode, use `config-images+<config-images.rst>`__: authenticated bootstrap selects runtime and config+images, and services and commands invoke the packaged runtime interpreter.+Target-local signer and repository mutations are refused in that mode;+configuration changes arrive as signed images. Signed upatch load/unload,+package updates, tree sync, export and attestation remain available.1) Build--------diff --git a/Documentation/index.rst b/Documentation/index.rstindex 4141b6bb..5048ae38 100644--- a/Documentation/index.rst+++ b/Documentation/index.rst@@ -41,6 +41,12 @@ Deploying shirudocreating a signing key, initialising a target, loading an upatchand publishing packages to a registry.+Using executable and config images+ `config-images <config-images.rst>`__ describes the opt-in dm-verity+ mode: 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: theBPF side of a upatch, building and signing, testing on a target,diff --git a/Documentation/initrd.rst b/Documentation/initrd.rstindex bd23840e..3505efc9 100644--- a/Documentation/initrd.rst+++ b/Documentation/initrd.rst@@ -13,6 +13,14 @@ and how the pieces survive the switch from one to the other. The``threat-model`` document says why it matters; ``tpm`` describes theregister the initrd binds.+The opt-in dm-verity mode keeps the same systemd handoff, with two+additional image mounts under ``/run/shirudo``. It requires the runtime image+hash and startup settings in authenticated boot, and writable state available+inside the initrd for the config activation journal. See+`config-images <config-images.rst>`__ for image generation and activation.+The read-only state bind and inode identities below describe the ordinary+installation.+1) Two runs of init-------------------@@ -155,8 +163,8 @@ The generatorresult::sudo shirudo-gen-initrd # the running kernel- sudo shirudo-gen-initrd --kver 7.4.0 --output /boot/initrd.img-7.4.0- shirudo-gen-initrd --check /boot/initrd.img-7.4.0+ sudo shirudo-gen-initrd --kver <kernel-release> --output /boot/initrd-shirudo.img+ shirudo-gen-initrd --check /boot/initrd-shirudo.imgshirudo-gen-initrd --print-cmdline # bpf.keyring_unsealed=1Run from a checkout it installs the module into dracut's directory@@ -218,3 +226,41 @@ with a vTPM gets the bpf-next kernel packages, reboots into them, runs``install.sh`` with a local target package and certificate, rebootsagain and must come up in the production configuration, with ``t1122``passing on the installed system.++6) Image-mode boot+------------------++The authenticated initrd first verifies the runtime root and selected+config to determine the authorized boot signer set. It enrolls and seals that+set, attaches device and task protection, mounts the runtime under those+guards and completes measured config activation and upatch restore. The root+filesystem's service invokes the image binary through its packaged ELF+interpreter and libraries; ``shirudo-gen-runtime --unit-output`` writes that+invocation. The config is mounted ``ro,nodev,nosuid,noexec``; runtime+is ``ro,nodev,nosuid``. The host root filesystem is not replaced.++Image mode must be able to persist the config bundle and activation record+before extending the PCR. Make ``/var/lib/shirudo`` writable and available+in the initrd, including a separate state filesystem when used. The ordinary+installation continues to use its read-only state bind. Config and runtime+mounts live under ``/run`` to survive switch-root, as bpffs does.++The selected config is checked again at every boot. After a TPM reset it+receives a fresh BOOT measurement. A same-boot repeat of init does not add+another config event. An interrupted activation is completed from its saved+record; the target cannot silently use an invalid candidate and report+success. Updating the runtime image or config verification certificate+requires rebuilding authenticated boot and rebooting.++An existing activation journal selects its cached config prefix before the+runtime's initial ``config.image`` default. A live update requiring a new+BPF signer is refused before measurement; it is not queued for reboot.+Provision the signed boot selection through the authenticated boot rollout.+The current CLI has no separate next-boot staging command; changing only the+bootstrap default cannot replace a journaled selection. See the operational+limitation in `config-images <config-images.rst>`__.++The standard image-mode integration run is ``sudo make -C testing test-tgt+TEST_VM_MODE=verity``. It requires the initrd and seeds a disposable target+with public fixtures. A direct QEMU kernel/initrd boot tests the handoff but+does not establish a measured UKI boot or its PCR 11 phase distinction.diff --git a/Documentation/key-lifecycle.rst b/Documentation/key-lifecycle.rstindex 1fc7ba48..c851c75d 100644--- a/Documentation/key-lifecycle.rst+++ b/Documentation/key-lifecycle.rst@@ -13,6 +13,10 @@ in protection, and what to do when one is compromised. The`threat-model <threat-model.rst>`__ says why the mechanisms are shapedthe way they are; this document says what to do.+The procedures below describe the ordinary installation. Image mode uses+signed config images for boot-time key enrollment and live revocation; its differences+are in section 8 and `config-images <config-images.rst>`__.+1) The keys in the system-------------------------@@ -326,3 +330,57 @@ A compromised keycopied: into the initrd, into a registry registration, into aninventory.* Treat a key that left the operator host, even once, as compromised.++8) Keys in image mode+---------------------++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.++Image mode 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. Image-mode ``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.++Image mode 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.diff --git a/Documentation/operations.rst b/Documentation/operations.rstindex 0fcb5c67..34c017b0 100644--- a/Documentation/operations.rst+++ b/Documentation/operations.rst@@ -13,6 +13,10 @@ The `getting-started <getting-started.rst>`__ document brings a targetup; the `initrd <initrd.rst>`__ document describes the productionconfiguration; this one is about the time after that.+For the opt-in image mode, see `config-images <config-images.rst>`__+and section 8 below. The ordinary installation's paths and executable-upgrade+procedure remain as documented here.+1) The moving parts-------------------@@ -58,9 +62,12 @@ 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/``, all labelled with the seal xattr so that only-shirudo can change them, each from the instant it is created: a new-inode gets the label of the directory it is created in.+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 theLSM pins, the frozen identity map and the pending init record betweenthe initrd run and the root's.@@ -128,8 +135,8 @@ Conditionsagain, which only a TPM reset should allow.``tamper_attempts``- What the guards refused this boot: ``total`` and one counter per- point of refusal under ``counters`` (``LoadNotLoader``,+ 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,@@ -138,7 +145,8 @@ Conditionscounters that are not zero with what each means under ``Tamperattempts``. A count is an attempt that was refused, so theconditions stay ``OK``; it is the operator's cue to look at the- journal and the host.+ 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 OTLPkeepalive, so a collector sees a target go ``WARN`` or ``ERROR``, or go@@ -413,3 +421,60 @@ success, ``1`` on any refusal or failure and ``2`` on a usage error;* - ``unknown``- An error without a closer category; errno is in the report.- Read the report.++8) Operating image mode+-----------------------++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. They refuse a pending activation or PCR/history inconsistency;+attestation follows the same rule.++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/requirements.rst b/Documentation/requirements.rstindex 6e529f5e..476ba3b3 100644--- a/Documentation/requirements.rst+++ b/Documentation/requirements.rst@@ -8,19 +8,24 @@ System requirementsThis is the single list of what a host needs before shirudo is built,installed or initialised on it. The operator and target roles havedifferent needs; a development host that plays both needs the union.-shirudo requires Linux v7.4 or newer and a current toolchain and has-no fallback paths for older ones, so a missing item here fails loudly at-build or pre-flight time rather than degrading silently.+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 target runs Linux v7.4 or newer. That release is the base-minimum: it carries the signed BPF loader support shirudo builds on,-and shirudo tracks current upstream from there. The ``shirudo init``-pre-flight checks that the running kernel has that support-(``signed_loader_kernel_abi``) and refuses otherwise; a load on an-older kernel reports ``kernel_abi_unsupported``.+The validated source baseline is upstream bpf-next commit+``0867b7bfa9de65674c6e599fa21b762b71011b14``, which reports a+``7.3.0-rc5``-based release string in the validation build. No kernel patches+are applied. 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@@ -68,8 +73,9 @@ fixture.and sealed it. The kernel is booted with``bpf.keyring_unsealed=1`` so that the keyring takes thecertificate from the initrd; booted without, it is sealed- empty and a ``shirudo`` keyring under the user keyring stages- the certificate until the next reboot.+ empty. Ordinary installations then stage the certificate in a+ ``shirudo`` user keyring until the next reboot. Image mode+ refuses initialization instead of staging.* - ``CONFIG_X509_CERTIFICATE_PARSER``,``CONFIG_PKCS7_MESSAGE_PARSER``,``CONFIG_SYSTEM_DATA_VERIFICATION``@@ -107,6 +113,39 @@ fixture.only relaxes module-signature checks, and BPF signature verificationaccepts the signed-attributes form.+Image-mode requirements+~~~~~~~~~~~~~~~~~~~~~~~++The opt-in dm-verity mode additionally 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. 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 mode uses existing upstream kernel APIs and carries no kernel+patches. 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. Ordinary installations do not enable+image mode implicitly.++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~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -170,6 +209,10 @@ kernel that a current clang and OpenSSL 3.5 run on will do.* - 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,@@ -275,8 +318,13 @@ since the libguestfs appliance resolves names through DNS alone.committed), so neither a submodule nor bpftool is needed. ``makebpf-deps`` refreshes the vendored copy from a kernel tree ondemand.-* Nothing else: packages, indexes and trees are built and published- through the same ``shirudo-build`` helper.+* ``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``; onlythe private key under ``/var/lib/shirudo/keys/``.@@ -345,7 +393,17 @@ sysroot, and run ``make target``. Retain that source, the build rulesand the dependency sources/notices with the distribution's relinkingmaterials. Rebuild the initrd and reboot after replacing the targetbinary, as described in `operations <operations.rst>`__.-7) Documentation and tests++7) Development kernel baseline+-------------------------------++Use the upstream development-tree ABI and options described above. Image+mode uses existing LSM hooks and adds no kernel patches. 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 withdiff --git a/Documentation/telemetry.rst b/Documentation/telemetry.rstindex eb9c670d..7cc11b15 100644--- a/Documentation/telemetry.rst+++ b/Documentation/telemetry.rst@@ -18,6 +18,15 @@ that give a record its shape, the documents on the wire, the transportand its configuration, and how to land the data in the OpenTelemetryCollector, ClickHouse, Splunk or a collector of your own.+In image mode, persistent ``map_export.*`` settings belong in+``etc/shirudo/shirudo.conf`` inside the signed config image. Build and activate+that config with ``shirudo image update``; editing the host's file does not+change image-mode settings. Configure the export and keepalive services to+invoke the runtime binary through its packaged interpreter and libraries.+The map, serializer, decoder and OTLP flows below are shared by both modes.+Bootstrap TPM and trust-path environment overrides are refused in image+mode; ordinary export options do not authorize changes to those inputs.+1) The pipeline---------------diff --git a/Documentation/threat-model.rst b/Documentation/threat-model.rstindex e12fe3ba..e7028484 100644--- a/Documentation/threat-model.rst+++ b/Documentation/threat-model.rst@@ -22,8 +22,9 @@ enforcement programs. The property it provides: from that point on,the BPF programs running in the target kernel are exactly the set theholder of the signing key authorised, every change to that set isrecorded in a TPM measurement an operator can check from one value, and-the target-local state shirudo depends on cannot be altered by anyone-but shirudo itself.+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:@@ -50,7 +51,8 @@ which the measured boot records in PCRs 9 and 11. Every other processon the target, including root with every capability, is outside theTCB and constrained by it.-Two configurations exist and ``status`` names them. In production the+Ordinary installations have two configurations and ``status`` names them.+In production thekernel is booted with ``bpf.keyring_unsealed=1`` and ``init`` runs fromthe initrd: the certificate goes into the kernel's bpf keyring, which``init`` seals and nothing can replace, and the register binds while@@ -59,13 +61,26 @@ can bring back. Staging is what a target gets when ``init`` runs fromthe root file system on a kernel that sealed the bpf keyring empty atboot: the certificate sits in a ``shirudo`` keyring under the userkeyring, sealed, and the register binds under the post-initrd phase-value. Everything below holds in both; where the-staging configuration is weaker, the residual risk says so, and the+value. The mechanisms below apply to both; the residual risks describe+staging weaknesses, including certificate invalidation, and theverifier can refuse staged evidence outright.+The opt-in image mode requires production initialization and refuses+user-keyring staging. It adds authenticated runtime and config images to+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. An upatch does what its author wrote; shirudo guarantees-provenance, not correctness.+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 ofregistries and collectors, and whatever remote access an administrator@@ -109,8 +124,11 @@ T1 Loading unsigned BPF``BPF_SIG_VERIFIED`` from exactly that keyring kind and, whilestaging, that serial (the kernel records none for its own bpfkeyring). Userspace ``BPF_MAP_CREATE`` is restricted to the- executable ``init`` recorded as shirudo; signed loader map creation- runs in kernel context. The payload is hash-locked to the loader by+ executable ``init`` recorded as shirudo in ordinary mode, or a+ trusted task in image mode. Image task authority is 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``.@@ -119,54 +137,55 @@ 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 shirudo's own executable, so root cannot re-attach a vetted- kprobe program at a site its signer never meant it for, nor pin- anything into the private bpffs.- The links are kept alive by pins in that bpffs;- ``inode_unlink`` and ``inode_rename`` on it allow only shirudo's own- executable (the VFS unlinks the victim of a rename without- ``inode_unlink``, so a rename over a link's pin would otherwise- drop its only reference), and ``sb_umount``, ``move_mount``,- ``sb_mount`` and ``sb_remount`` deny everyone, so neither ``rm``- nor ``mv`` nor ``umount`` nor mounting over the directory removes a- pin. Infrastructure maps are+ to Shirudo authority: the recorded executable in ordinary mode or a+ trusted task in image mode. Root cannot re-attach a vetted program+ at a site its signer never meant it for, nor pin objects of its own.+ 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.+ Unmounting a parent mount and legacy mount moves remain gaps,+ described in residual risk 3. Infrastructure maps arefrozen at creation, so even with the LSM gone userspace could notrewrite the identity map. ``lsm/bpf_map`` denies writable map fdsto every process except shirudo; map updates and freezes have the- same executable gate. Userspace ``BPF_PROG_TEST_RUN`` is restricted- to shirudo's recorded executable; kernel-context loader calls remain- allowed. Root therefore cannot invoke a signed+ same authority check. Userspace ``BPF_PROG_TEST_RUN`` requires that+ authority too; kernel-context loader calls remain allowed. Root therefore cannot invoke a signedserializer to drain or clear map state. Root may inspect pinned mapsbut cannot alter serializer arrays or writable-mmap arena state- through the syscall interface. From the initrd, the identity records+ through the syscall interface. In ordinary mode, the initrd recordsthe root's binary as the executable that lasts and the initrd'sown copy beside it for that one run; the copy is gone with theinitrd, and its inode is on a file system nothing can reach afterthe switch.T3 Tampering with shirudo's files and process- Every inode under ``/var/lib/shirudo`` carries the- ``security.bpf.shirudo`` label; the seal program allows write open,- attribute changes such as truncate, unlink, rename and xattr changes- only to the process that runs the executable ``init`` recorded, by- device and inode and never by path, and only that process may set- the label. The label marks what is protected and is public; it is- not what identifies the caller, as a file system root mounts can- present it on any binary.- An inode created under a labelled directory is born with the- label, written by the seal inside the transaction that creates it,- so there is no instant at which a new file of shirudo's can be- opened, unlinked or renamed by anyone else; what another process- creates there is sealed from the same instant, out of its own- reach as well.- Marked shirudo tasks cannot be ptraced, which also closes the- ``/proc`` files that need ptrace access, and no perf event can be- bound to one of them; a system-wide profile still sees them as it- sees every task. No traced task can exec shirudo either, so no- tracer carries over into it. The process drops dumpability, forbids new- privileges and locks sensitive buffers, and it runs in secure-exec- mode, so the dynamic loader takes no code from the environment of- whoever started it (residual risk 2). The bpf keyring is sealed with+ 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.+ Ordinary mode authorizes the frozen executable identity or its initrd+ copy, by device and inode; image mode uses the trusted task mark.+ 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. Ordinary mode permits replacing the+ recorded primary executable, but its replacement gains no authority+ until a later initialization records it.+ New inodes inherit their parent's label in the creation transaction+ when the parent has a cached seal mark. Shirudo's writers hold the+ parent directory open to populate and retain that mark. Directory+ eviction and foreign link or rename operations remain subject to+ residual risk 15; existing writable references are not revoked.+ 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>`__.+ Recorded Shirudo 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+ sensitive buffers. The bpf keyring is sealed with``KEYCTL_RESTRICT_KEYRING`` so no key can be linked into it for therest of the boot, ``lsm/key_permission`` leaves writing, unlinking,revoking, invalidating and re-permissioning it and the keys it@@ -176,7 +195,8 @@ T3 Tampering with shirudo's files and processsealed with ``KEYCTL_SETPERM``. The kind and serial of the keyring``init`` sealed are frozen into the identity map, pinned in thebpffs and read back by every later command, so a swapped same-name- keyring makes every load refuse ``tampered``.+ keyring makes every load refuse ``tampered``. Staged certificates have+ a separate invalidation exception described in residual risk 6.T4 Substituting artifactsThe signature covers the loader instructions and data, so the kernel@@ -270,7 +290,7 @@ T9 A target lying about its stateevidence explain them.T10 An attempt that leaves no trace- Every guard counts what it refuses, by the point of refusal (a+ The named guard points count their refusals (aload that is no signed loader, one without a signature, one whosesignature was verified against the wrong kind of keyring or thewrong keyring, a writable map descriptor, a rename of a pin, an@@ -283,7 +303,59 @@ T10 An attempt that leaves no tracetotal as the ``shirudo.tamper_attempts`` attribute, so an attemptis seen where it was made and not only where it failed. A counteris evidence of an attempt, not of a compromise: the refusal is what- moved it.+ 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. 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. Existing ioctl hooks restrict DM-control mutations to trusted+ image tasks, including through old or inherited FDs; this restriction+ applies to unrelated DM devices too. No kernel patches are included,+ and 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. 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-----------------@@ -327,21 +399,30 @@ Each of these is known, documented and bounded; none is silent.them. Enforcement continues, but state-changing commands refuse``lsm_detached`` while their pins are hidden.-4. Register denial of service. A process that can open- ``/dev/tpmrm0`` can extend PCR 9 or the written register with- garbage, and with the owner auth (empty on most TPMs) undefine the- index. None of it is hidden: a garbage event fails the replay, a- recreated index cannot be written and fails the name check, and- ``status``, every state-changing command and ``attest verify``- report ``tampered``, and ``init`` binds no other register before- the next TPM reset; the attacker still cannot load BPF. It costs- the operator a reboot and an investigation.--5. The binary on disk. shirudo cannot defend its own executable- against substitution or patching before it runs; that belongs to- the distribution layer (signed packages, IMA appraisal, fs-verity,- measured boot). ``SHIRUDO_VERSION_ID`` is a skew guard, not an- integrity check: a malicious binary can lie about it.+ 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. TPM measurement writers are not yet bound to completed Shirudo+ operations. A caller with direct TPM-command access can append to the+ written NV register or 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.+ Restricting measurement writers and handling operation/measurement+ ordering remain separate work; no IMA integration is added.++5. In the ordinary installation, executable integrity before init belongs+ to the distribution and authenticated boot. Image mode authenticates+ and verifies runtime files, including their loader and libraries, but+ still trusts the UKI, kernel and its own trusted process memory.+ ``SHIRUDO_VERSION_ID`` remains a skew guard, not authentication.6. While the certificate is staged in the user keyring, a keyringswap degrades to denial of service. Root can unlink the sealed@@ -350,7 +431,12 @@ Each of these is known, documented and bounded; none is silent.refusal, for the rest of the boot, instead of abypass. The bpf keyring, the production anchor, can be neitherunlinked nor substituted, and the kernel refuses every other- keyring once it is sealed.+ keyring once it is sealed. A fresh upstream VM also reproduced root+ invalidating its possessed staged certificate through ``keyctl``.+ The key-permission hook permits possessed ``KEY_NEED_SEARCH``+ references, which the kernel also uses for invalidation. This removes+ the certificate despite the mutation guards. Image mode refuses+ user-keyring staging.7. The boot window before ``init`` has run. Run from the initrd itis the initrd itself, which the measured boot records in PCRs 9 and@@ -410,18 +496,27 @@ Each of these is known, documented and bounded; none is silent.no push channel by design. Evidence tells the two apart: arevoked node's register carries the ``key_revoke`` event, and``attest predict --event=revoke:...`` names the value to expect.- The set itself is guarded: the ``key_permission`` hook denies root- the unlink, clear, revoke and invalidate that would otherwise empty- the sealed keyring, so what used to be a denial of service with- one keyctl is now shirudo's revocation primitive and nothing else.--14. The label at creation follows a mark the seal keeps on a directory+ The production set is guarded by ``key_permission`` checks against+ unlink, clear, revoke and invalidate. User-keyring staging has the+ reproduced invalidation exception in residual risk 6.+ Image mode instead receives revocations through a signed config. Its+ config PCR records the selection, and purged upatches have their unload+ events in the NV register. It has no local ``keys revoke`` override and+ still depends on delivery and activation of the intended config.++14. Image mode 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 directoryit has seen since the inode came into memory: one opened, onerelabelled, or one created under a marked parent. shirudo opens adirectory before creating in it and puts the label on afterwards- where the kernel could not, so its own files never exist- unlabelled; another process creating under a labelled directory- the seal has not seen since the inode was evicted gets an+ where the kernel could not. Another process creating under a labelled+ directory the seal has not seen since the inode was evicted gets anunlabelled inode, as every creation did before, until the next``init`` labels the tree. Rename and link bring an existing inodein without creating one, so they bring it in unlabelled.@@ -429,7 +524,9 @@ Each of these is known, documented and bounded; none is silent.Deferred mitigations~~~~~~~~~~~~~~~~~~~~-In scope and not yet built: registering the register as a systemd+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 systemdNvPCR, so that its name follows the UKI signing key instead of the PCRvalues of each boot and systemd-aware verifiers find it in PCR 9 beforethe separator, and measuring the anchor through ``systemd-pcrextend`` so@@ -440,7 +537,7 @@ signed ``.rodata`` (residual risk 1); and refusing creation, renameand link into a labelled directory from any process but shirudo, whichwould keep foreign entries out of the tree altogether, and a``d_instantiate`` hook the BPF LSM can sleep in, which would mark a-directory the moment its dentry is bound (residual risk 14).+directory the moment its dentry is bound (residual risk 15).6) Out of scope---------------diff --git a/Documentation/tpm.rst b/Documentation/tpm.rstindex 55f1e82e..dd1fb0f8 100644--- a/Documentation/tpm.rst+++ b/Documentation/tpm.rst@@ -588,3 +588,38 @@ exercises binding, extending, replay, recreation, a TPM reset andsimulator's ``volatile`` state file is a TPM reset. The target suiteruns the same path against swtpm in the QEMU VM (``make -C testing test-tgt``);``contrib/swtpm.sh`` starts a software TPM for a development target.+++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 both the config+PCR and the existing NV register; no IMA integration is added.diff --git a/Documentation/upatch.rst b/Documentation/upatch.rstindex 1648fc5e..598e0b7b 100644--- a/Documentation/upatch.rst+++ b/Documentation/upatch.rst@@ -15,6 +15,16 @@ load path and the registry formats, and the `telemetry<telemetry.rst>`__ document covers decoders and the export pipeline indepth. This guide is the workflow that ties them together.+Operator build, sign and publish commands are the same for both target+policy modes. The writable repository-registration examples below describe+the ordinary installation. Image-mode targets instead receive repository+definitions, public verification certificates, the tree subscription and node+labels in a signed config image. Local ``bpm config register`` mutations and+``bpm key add`` are refused there. Package installation, upgrades and tree+sync still run on the target; they read the selected authenticated config.+New BPF signers require boot enrollment, while signed revocation configs and+upatch updates remain live. See `config-images <config-images.rst>`__.+1) What an upatch is--------------------@@ -267,7 +277,7 @@ A package is a directory with a ``Beefile`` next to the sources::unload_artifact = "upatches/shield.unload.upatch"[upatches.tree.selector]- kernel_release_prefix = ["7.4"]+ kernel_release_prefix = ["7.3.0-rc5"]kernel_build_id = ["534043106db415bc0a983a3393e06c81b431bd39"]architecture = ["x86_64"]diff --git a/tools/gen-image/README.md b/tools/gen-image/README.mdnew file mode 100644index 00000000..1b5267e7--- /dev/null+++ b/tools/gen-image/README.md@@ -0,0 +1,91 @@+# Building Shirudo images++`shirudo-gen-image` runs on the operator. It uses `mkfs.ext4` from+`e2fsprogs`, then calls the operator-only `shirudo-build` helper to construct+and sign the dm-verity tree. The helper invokes `veritysetup format` from+`cryptsetup-bin` (Debian/Ubuntu) or `cryptsetup` (Fedora/RHEL), and the+generator verifies the result with `veritysetup verify`. Targets use kernel+APIs and do not need these programs. Offline `shirudo image verify` also+requires the operator helper and `veritysetup`; it checks the signed+root signature and exact file sizes before verifying the retained data and+hash files.++The source directory becomes the image root. A config source contains+`etc/shirudo/` and additional `keys/trusted/` and `keys/revoked/` directories;+bootstrap settings and the initial BPF certificate belong in the executable+image. Keep private operator keys outside both images. Config symlinks and+special files are refused.++```sh+tools/gen-image/shirudo-gen-image --source config-root --output config \+ --keys-dir operator-keys --builder tools/shirudo-build/shirudo-build+```++Use `--kind runtime` for the executable image. The deployment must arrange+for the dynamic loader and libraries to come from that image too. The host+root filesystem is not replaced.++The four outputs are `config.img`, `config.verity`, `config.roothash` and+`config.p7s`. Download the complete set before requesting activation. The+printed SHA-256 root is also suitable for authenticating a runtime image+from the UKI. Existing outputs are never overwritten.++The standard verity superblock occupies the first 4096-byte block; the+hash tree starts at block one. Format 1, SHA-256, 4096-byte blocks and a+32-byte salt are fixed. The `.roothash` file contains exactly 64 lowercase+ASCII hex bytes with no newline. The detached ML-DSA-87 CMS signature covers+those root bytes. `--kind` is a packaging hint only. The runtime must match+the exact UKI root, regardless of a config signature; config images never+grant executable authority.++The trusted initrd enrolls the config certificate into the kernel's+`.dm-verity` keyring and seals it before host startup. Boot requires+`dm_verity.keyring_unsealed=1`. Kernel built-in dm-verity trust remains+accepted. After interrupted config activation, Shirudo refuses further+updates and attestation while the node keeps running. The operator chooses+when to reboot; Shirudo never reboots automatically and has no same-boot+recovery command.++For a target binary linked against glibc, `shirudo-gen-runtime` packages the+ELF interpreter and its complete library closure without modifying the+binary. Use a trusted, native target binary on the operator. It prints the+explicit loader invocation to use after mounting the runtime image. The+invocation disables the host loader cache and supplies only library paths+inside the image. The LSM also denies executable mappings from outside the+approved image, so missing libraries fail instead of falling back to the host.++```sh+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+```++The packaged config-verification certificate is+`/run/shirudo/runtime/etc/shirudo/config-cert.der`; use that absolute path+for `config.verification_key` in the bootstrap configuration. The initial+BPF certificate is `keys/cert.der` inside the image. Runtime images have no+shell or debugger unless the operator explicitly supplies one.++Pass `--unit-output runtime-service.conf` to generate a systemd drop-in for+the root phase. Install it as+`/etc/systemd/system/shirudo.service.d/verity.conf`. It clears the writable+`init.env` file and starts the loader and Shirudo binary from the runtime+image. Generate the initrd with `shirudo-gen-initrd --bootstrap-conf <file>`;+this bootstrap file carries `runtime.image` and `runtime.root_hash`, while+the file inside the runtime image carries config verification settings.+The initrd's first invocation still uses its authenticated bootstrap binary.+The state filesystem at `/sysroot/var/lib/shirudo` must be mounted writable+in the initrd for durable pending config selection; the legacy mode keeps+its existing read-only bind. Image mode is bootstrapped exclusively by the+trusted initrd before untrusted workloads start. It does not migrate a+running unprotected system: pre-existing writable mappings and held file+descriptors would fall outside that bootstrap guarantee. State entries must+be regular files or directories; symlinks, special files and failed labels+stop initialization. After attaching guards, initialization re-applies the+state labels to populate the inode protection cache.++`--extra-binary <trusted-ELF>` adds a deliberately trusted executable and its+library dependencies, for example a test probe. Every executable+in this image has equal authority; omit this option in deployment unless+that additional authority is intended.