eBPF-based security platform
init: restore only the archives the eventlog records as loaded
Daniel Borkmannc54a9e4531a4
diff --git a/AGENTS.md b/AGENTS.mdindex 39548e10..553fc436 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -263,7 +263,10 @@ one usually still compiles and passes tests.between its pins and its extend leaves pins without a record: `status`reports them (`UpatchesMeasured`) and the next upatch command undoesthem under the register lock, which a load or an unload holds from- before it touches the pins to its append. The register follows+ before it touches the pins to its append. `init` restores only an+ archive whose load the eventlog records without a later unload; a+ labeled archive root brings back is reported and removed, never+ restored. 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 11hold the values the policy was computed from, which is why `init`diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex 480b59e9..1b12f99e 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -377,6 +377,9 @@ signed config image.* - ``t6143-unmeasured-load``- A load stopped before its extend is counted, reported by statusand undone by the next upatch command+ * - ``t6144-returned-archive``+ - An archive root brings back after its unload is reported, not+ restored by init and removed by the next upatch command``bpm`` (7)~~~~~~~~~~~@@ -592,7 +595,7 @@ Coverage by area``t5003``* - TPM register- ``t4001``, ``t4003``, ``t4101``, ``t4102``, ``t4103``,- ``t6125``, ``t6128``, ``t6143``. Unit: ``chain``+ ``t6125``, ``t6128``, ``t6143``, ``t6144``. Unit: ``chain``* - Attestation- ``t2003``, ``t2005``, ``t4003``, ``t4004``, ``t4102``,``t9105``. Fuzz: ``attest``, ``tpm-wire``diff --git a/Documentation/internals/boot-flow.rst b/Documentation/internals/boot-flow.rstindex 68aa33ff..7c6f9b91 100644--- a/Documentation/internals/boot-flow.rst+++ b/Documentation/internals/boot-flow.rst@@ -93,7 +93,8 @@ the switch to the root file system. It needs``/run/shirudo/config`` with ``ro,nodev,nosuid,noexec``.#. Restore the archived upatches from ``/var/lib/shirudo/upatches`` insorted order through the signed loader path. An entry without the- seal label, or one that is not a valid artifact, is ignored. The+ seal label, one that is not a valid artifact, or one whose load the+ eventlog does not record as still loaded, is ignored. Thefirst failure stops the restore; upatches restored before it stayloaded.#. Bind the measurement register, extend it with one ``init`` event thatdiff --git a/Documentation/operate/run/read-status.rst b/Documentation/operate/run/read-status.rstindex 552297ac..eebe37b1 100644--- a/Documentation/operate/run/read-status.rst+++ b/Documentation/operate/run/read-status.rst@@ -67,7 +67,7 @@ loaded, captured from the test VM:LsmAttached OK lsm/bpf link present and pinnedKeyringSealed OK bpf serial=130847582, dm-verity serial=962472513, pins matchChainIntact OK live register == eventlog replay- UpatchesMeasured OK every pinned upatch is in this boot's records+ UpatchesMeasured OK every pinned or archived upatch is in this boot's recordsTpmMeasured OK NV index 0x01818E00 readableConfigActive OK config dc90bacc356f.. is active@@ -180,11 +180,13 @@ verdict is derived from them.``no register bound this boot (init incomplete)`` or ``no TPManswered, no register to replay``.* - ``UpatchesMeasured``- - Every upatch pinned in the private bpffs is in this boot's- records: loaded with the payload its pin records and not unloaded- since. ``ALERT`` ``<n> pinned without a record of this boot:- <names>`` is what a load stopped between its pins and its extend- leaves, which the next ``upatch load`` or ``upatch unload``+ - Every upatch pinned in the private bpffs or archived under+ ``/var/lib/shirudo/upatches`` is in this boot's records: loaded+ with the payload its pin or archive records and not unloaded+ since. ``ALERT`` ``<n> pinned or archived without a record of+ this boot: <names>`` is what a load stopped between its pins and+ its extend leaves, or an archive root brought back after its+ unload, which the next ``upatch load`` or ``upatch unload``undoes before it acts. ``WARN`` ``no record of this boot to checkthe pins against`` before ``init``, or ``pins not checked againstthe records: <error>``.@@ -417,20 +419,22 @@ record, the eventlog of this boot was altered or hidden, or the index isnot the one ``init`` bound. The ``TPM Measurement`` section shows whichlines disagree.-A upatch is pinned without a record:+A upatch is pinned or archived without a record:.. code-block:: text- Status: tampered (a upatch is pinned without a record of this boot)+ Status: tampered (a upatch is pinned or archived without a record of this boot)...- UpatchesMeasured ALERT 1 pinned without a record of this boot: <name>+ UpatchesMeasured ALERT 1 pinned or archived without a record of this boot: <name>A load was stopped between its pins and its extend, so the upatch runs-while the register does not cover it, or an unload was stopped after-its extend. The next ``upatch load`` or ``upatch unload``, and every-``bpm`` command that loads or unloads, undoes those pins before it acts-and records the undo in the journal. What stopped the load is the-question for the incident.+while the register does not cover it, an unload was stopped after its+extend, or an archive came back after its unload, which ``init`` would+not restore. The next ``upatch load`` or ``upatch unload``, and every+``bpm`` command that loads or unloads, undoes those pins and archives+before it acts and records the undo in the journal. What stopped the+load, or who brought the archive back, is the question for the+incident.The live keyring is not the one ``init`` sealed:diff --git a/Documentation/reference/cli/init.rst b/Documentation/reference/cli/init.rstindex c586a7cc..4f0c7640 100644--- a/Documentation/reference/cli/init.rst+++ b/Documentation/reference/cli/init.rst@@ -52,10 +52,13 @@ Description#. It begins the config ``BOOT`` event: it records the selection aspending, extends the config PCR named in the bootstrap settings andmounts the config image at ``/run/shirudo/config``.-#. It restores every upatch archived in ``/var/lib/shirudo/upatches``,- all or nothing. An upatch already loaded with the archived payload is- kept. An archived upatch that is not loaded after this boot's register- was bound is refused as tampered.+#. It restores every upatch archived in ``/var/lib/shirudo/upatches``+ whose load the eventlog records without a later unload, all or+ nothing. An archive without such a record, one root brought back+ after its unload or one a load stopped before its extend left, is+ ignored with a warning. An upatch already loaded with the archived+ payload is kept. An archived upatch that is not loaded after this+ boot's register was bound is refused as tampered.#. It binds the measurement register under PCRs 9 and 11 and records oneinit event that covers the certificate set, the restored upatches andthe upatch tree root.diff --git a/Documentation/reference/cli/status.rst b/Documentation/reference/cli/status.rstindex f512fbe1..05817612 100644--- a/Documentation/reference/cli/status.rst+++ b/Documentation/reference/cli/status.rst@@ -54,8 +54,8 @@ The report shows six conditions, each ``OK``, ``WARN`` or ``ALERT``:- The live register differs from the eventlog replay, the ``.bpf``or ``.dm-verity`` keyring is not the one ``init`` froze or isgone, a keyring holds a link ``init`` did not freeze, the config- key is gone from ``.dm-verity``, a upatch is pinned without a- record of this boot, or the selected config cannot be verified+ key is gone from ``.dm-verity``, a upatch is pinned or archived+ without a record of this boot, or the selected config cannot be verifiedagainst its records.* - ``lsm-off``- The LSM link is not pinned.@@ -181,7 +181,7 @@ Show the state of a target:LsmAttached OK lsm/bpf link present and pinnedKeyringSealed OK bpf serial=130847582, dm-verity serial=962472513, pins matchChainIntact OK live register == eventlog replay- UpatchesMeasured OK every pinned upatch is in this boot's records+ UpatchesMeasured OK every pinned or archived upatch is in this boot's recordsTpmMeasured OK NV index 0x01818E00 readableConfigActive OK config dc90bacc356f.. is activediff --git a/Documentation/reference/cli/upatch-load.rst b/Documentation/reference/cli/upatch-load.rstindex 18646e1f..a053f349 100644--- a/Documentation/reference/cli/upatch-load.rst+++ b/Documentation/reference/cli/upatch-load.rst@@ -46,10 +46,11 @@ Description#. It refuses when the eventlog would exceed ``eventlog.max_bytes``(``eventlog_full``).#. It takes the register lock, ``/var/lib/shirudo/eventlog.lock``, which- it holds to the end, and undoes the pins of a load that was stopped- before its extend or of an unload stopped after it, the pins- ``status`` reports under ``UpatchesMeasured``. A upatch of the same- name that is loaded is refused (``already_loaded``).+ it holds to the end, and undoes the pins and archives this boot's+ records do not cover: those of a load stopped before its extend, of+ an unload stopped after it, and an archive brought back after its+ unload, which ``status`` reports under ``UpatchesMeasured``. A upatch+ of the same name that is loaded is refused (``already_loaded``).#. It parses the artifact: a LOAD artifact, a safe and signed name, apayload digest that matches the payload, valid attach metadata(``parser_rejected``). For a uprobe it checks each target binarydiff --git a/Documentation/reference/cli/upatch-unload.rst b/Documentation/reference/cli/upatch-unload.rstindex 0911e488..05a19498 100644--- a/Documentation/reference/cli/upatch-unload.rst+++ b/Documentation/reference/cli/upatch-unload.rst@@ -41,8 +41,7 @@ both in signed sections (see :doc:`build`). ``unload``:#. Refuses when the eventlog would exceed ``eventlog.max_bytes``(``eventlog_full``).#. Takes the register lock, which it holds to the end, and undoes the- pins of a load or an unload that was stopped before the register- covered them, as ``load`` does.+ pins and archives this boot's records do not cover, as ``load`` does.#. Loads the directive's loader with ``BPF_PROG_LOAD`` against the``.bpf`` keyring, so that the kernel verifies its signature beforeanything is removed.diff --git a/Documentation/reference/formats/status-json.rst b/Documentation/reference/formats/status-json.rstindex 57a86ef9..1ec868c6 100644--- a/Documentation/reference/formats/status-json.rst+++ b/Documentation/reference/formats/status-json.rst@@ -159,8 +159,8 @@ Verdicts``.bpf`` or ``.dm-verity`` keyring's serial differs from thepinned serial, a keyring ``init`` pinned is gone, a keyring holdsa link ``init`` did not freeze, the config key ``init`` froze is- gone from ``.dm-verity``, a upatch is pinned without a record of- this boot, or the selected config cannot be verified against its+ gone from ``.dm-verity``, a upatch is pinned or archived without+ a record of this boot, or the selected config cannot be verified against itsactivation records.* - ``lsm-off``- The LSM link is not pinned. Enforcement is off.@@ -239,7 +239,7 @@ its details that applies, in the order listed.- ``live register != eventlog replay (tamper?)``* - ``UpatchesMeasured``- ``OK``- - ``every pinned upatch is in this boot's records``+ - ``every pinned or archived upatch is in this boot's records``* -- ``WARN``- ``no record of this boot to check the pins against``@@ -248,7 +248,7 @@ its details that applies, in the order listed.- ``pins not checked against the records: <error>``* -- ``ALERT``- - ``<n> pinned without a record of this boot: <names>``+ - ``<n> pinned or archived without a record of this boot: <names>``* - ``TpmMeasured``- ``OK``- ``NV index 0x01818E00 readable``@@ -719,7 +719,7 @@ indented here:{"type": "UpatchesMeasured","status": "OK",- "detail": "every pinned upatch is in this boot's records"+ "detail": "every pinned or archived upatch is in this boot's records"},{"type": "TpmMeasured",diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rstindex 8971f783..b5e2d84a 100644--- a/Documentation/security/threat-model.rst+++ b/Documentation/security/threat-model.rst@@ -807,7 +807,7 @@ An authorized process is protected against being taken over::Tests: ``t6001``, ``t6006``, ``t6007``, ``t6110``, ``t6111``,``t6112``, ``t6113``, ``t6114``, ``t6115``, ``t6118``, ``t6123``,``t6124``, ``t6127``, ``t6129``, ``t6131``, ``t6133``, ``t6134``,- ``t6135``, ``t6136``, ``t6137``+ ``t6135``, ``t6136``, ``t6137``, ``t6144``:Residual: R2, R15, R19, R22T4 Substituting artifacts@@ -898,7 +898,9 @@ its extend, with ``SIGKILL`` say (counted as ``SealSignal``), leavespins the register does notcover and the upatch attached: ``shirudo status`` reports them(``UpatchesMeasured``, verdict ``tampered``) and the next upatch-command, ``bpm``'s included, undoes them before it acts. A measuring+command, ``bpm``'s included, undoes them, pins and archives, before it+acts; ``init`` restores only an archive whose load the eventlog records+without a later unload. A measuringcommand holds a lock beside the eventlog from its extend to its append,a load or an unload from that undo to its append, so the register andthe log advance in one order and the undo never takes a load in flight@@ -926,7 +928,7 @@ tree operations run without it.``tpm_error`` and ``eventlog_full`` from shirudo:Counters: ``TpmExtend``:Tests: ``t4002``, ``t4003``, ``t4102``, ``t4103``, ``t6115``,- ``t6122``, ``t6128``, ``t6143``+ ``t6122``, ``t6128``, ``t6143``, ``t6144``:Residual: R4, R12, R20, U6, U8, U9T6 Boot window@@ -1434,13 +1436,16 @@ R15 Marks can be evictedreplaces state by rename, so root can keep earlier labeled versionsalive through hard links in an unsealed directory on the same filesystem and bring them back. An unlabeled entry stays inert: shirudo- neither follows nor restores it. A returned labeled entry is taken- for shirudo's own. While a file's mark is absent, root can change+ neither follows nor restores it. A returned archive is not restored+ either: ``init`` restores only an archive whose load the eventlog+ records without a later unload, ``status`` reports it+ (``UpatchesMeasured``) and the next upatch command removes it+ (``t6144``). A returned labeled entry elsewhere in the state is+ taken for shirudo's own. While a file's mark is absent, root can changeits ACL and inode flags, and on a kernel without the carried xattrpatch (A3) a label read it made fail counts as unlabeled (T3).- Detection: only signatures and measurement; an- archived upatch restored at the next boot appears in the init event's- set. Mitigation: D6.+ Detection: a returned archive shows in ``status``; other returned+ entries only through signatures and measurement. Mitigation: D6.R16 Any artifact ever signed loads at any timeThere is no version floor, no expiry and no per-targetdiff --git a/Documentation/upatches/learn/concepts.rst b/Documentation/upatches/learn/concepts.rstindex fcb07f80..94337a27 100644--- a/Documentation/upatches/learn/concepts.rst+++ b/Documentation/upatches/learn/concepts.rst@@ -267,7 +267,7 @@ detach it.It cannot stay loaded unmeasured. A load whose archive copy or registerextend fails is undone, a load stopped before its extend is undone by thenext load or unload and reported by ``status`` until then, and ``init``-refuses to restore an archived upatch the register does not cover.+restores only an archived upatch whose load the eventlog records.It cannot be removed without the signer. A loaded upatch goes away througha signed unload directive bound to its payload, or through a keydiff --git a/builtin-init.c b/builtin-init.cindex 799bddca..1bc0b1ae 100644--- a/builtin-init.c+++ b/builtin-init.c@@ -53,6 +53,7 @@#include "util/nv_writer.h"#include "util/paths.h"#include "util/preflight.h"+#include "util/measured.h"#include "util/seal.h"#include "util/tpm.h"#include "util/upatch.h"@@ -907,19 +908,24 @@ out:/** All or nothing: one failure leaves init incomplete and the register- * unextended. On a re-run an upatch already pinned this boot with the- * archived payload is counted and left alone; loading it again would- * only attach a second link to fail at the pin. Once this boot's init- * event is on record the restore has happened and the register covers- * what it loaded, so an archived artifact that is not loaded cannot be- * applied any more: nothing would measure it. It was renamed into the- * archive since, or left behind by an unload cut short, and either is- * for the operator to resolve.+ * unextended. The eventlog says which archives are shirudo's to+ * restore: those whose load it records without a later unload. One it+ * does not, an archive root brought back through a hard link after its+ * unload or one a stopped load left without a record, carries the+ * label and is ignored. On a re-run an upatch already pinned this boot+ * with the archived payload is counted and left alone; loading it again+ * would only attach a second link to fail at the pin. Once this boot's+ * init event is on record the restore has happened and the register+ * covers what it loaded, so an archived artifact that is not loaded+ * cannot be applied any more: nothing would measure it. It was renamed+ * into the archive since, or left behind by an unload cut short, and+ * either is for the operator to resolve.*/static int boot_restore(bool recorded,struct measured_upatch **out_set, size_t *out_n){struct measured_upatch *set = NULL;+ struct measured_set *measured = NULL;struct dirent **names = NULL;int n, i, ret = 0;size_t cnt = 0;@@ -948,6 +954,16 @@ static int boot_restore(bool recorded,libc_free(names);return -ENOMEM;}+ ret = measured_set_log(&measured);+ if (ret) {+ pr_err("boot-restore: cannot read the eventlog's loads: %s",+ strerror(-ret));+ for (i = 0; i < n; i++)+ libc_free(names[i]);+ libc_free(names);+ xfree(set, (size_t)n * sizeof(*set));+ return ret;+ }pr_info("boot-restore: re-applying %d upatch%s from %s",n, n == 1 ? "" : "es", UPATCHES_DIR);@@ -983,6 +999,13 @@ static int boot_restore(bool recorded,hex_encode(u.hdr.payload_sha256, UPATCH_PAYLOAD_HASH_LEN,set[cnt].payload_hex);upatch_close(&u);+ if (!measured_holds(measured, set[cnt].name,+ set[cnt].payload_hex)) {+ pr_warn("boot-restore: %s is archived without a "+ "record of its load (returned or foreign "+ "entry); ignored", names[i]->d_name);+ goto next;+ }fd = upatch_open_first_link(set[cnt].name);if (fd >= 0) {close(fd);@@ -1019,6 +1042,7 @@ next:libc_free(names[i]);}libc_free(names);+ measured_set_free(measured);if (ret) {xfree(set, (size_t)n * sizeof(*set));diff --git a/builtin-status.c b/builtin-status.cindex fd5d2288..1bff679b 100644--- a/builtin-status.c+++ b/builtin-status.c@@ -78,6 +78,12 @@ static int note_unmeasured(const char *name, void *ctx)return 0;}+static int note_unmeasured_archive(const char *name, const char *path,+ void *ctx)+{+ return note_unmeasured(name, ctx);+}+static int notdot(const struct dirent *e){return strcmp(e->d_name, ".") != 0 && strcmp(e->d_name, "..") != 0;@@ -899,6 +905,7 @@ int cmd_status(int argc, const char **argv)const char *otel_status = NULL;bool otel_endpoint_configured = false;char unmeasured_names[UNMEASURED_NAMES] = "";+ struct measured_set *mset = NULL;char config_root_hex[65] = "";__u8 config_root[32];int unmeasured, lock;@@ -1017,8 +1024,21 @@ int cmd_status(int argc, const char **argv)if (n_ups < 0)n_ups = 0;lock = eventlog_lock();- unmeasured = lock < 0 ? lock :- measured_unmeasured_pins(note_unmeasured, unmeasured_names);+ unmeasured = lock < 0 ? lock : measured_set_boot(&mset);+ if (!unmeasured) {+ unmeasured = measured_unmeasured_pins(mset, note_unmeasured,+ unmeasured_names);+ if (unmeasured >= 0) {+ int archived;++ archived = measured_unmeasured_archives(mset,+ note_unmeasured_archive,+ unmeasured_names);+ unmeasured = archived < 0 ? archived :+ unmeasured + archived;+ }+ measured_set_free(mset);+ }eventlog_unlock(lock);gather_assets(&assets);diff --git a/builtin-upatch.c b/builtin-upatch.cindex caa4937b..420b6daf 100644--- a/builtin-upatch.c+++ b/builtin-upatch.c@@ -2813,20 +2813,46 @@ static int undo_unmeasured_pin(const char *name, void *ctx)return 0;}+static int undo_unmeasured_archive(const char *name, const char *path,+ void *ctx)+{+ if (unlink(path) != 0 && errno != ENOENT)+ pr_err("upatch: %s is archived without a record of its load and could not be removed: %s; operator must reconcile",+ name, strerror(errno));+ else+ pr_audit("upatch: %s was archived without a record of its load; the archive was removed",+ name);+ return 0;+}+/** A load that a signal stopped between its pins and its extend, or an* unload stopped between its append and its detach, left pins the- * register does not cover, which status reports meanwhile. Every upatch- * command undoes them before it acts, under the register lock a load- * holds from before its pins to its append, so that the scan never- * takes a load in flight for one that was stopped.+ * register does not cover, and an archive root brought back after its+ * unload is one the records do not cover either; status reports both+ * meanwhile. Every upatch command undoes them before it acts, under the+ * register lock a load holds from before its pins to its append, so that+ * the scan never takes a load in flight for one that was stopped.*/-static void undo_unmeasured_pins(void)+static void undo_unmeasured(void){- int ret = measured_unmeasured_pins(undo_unmeasured_pin, NULL);+ struct measured_set *set;+ int ret;- if (ret < 0 && ret != -ENOENT)- pr_warn("upatch: cannot check the pins against this boot's records: %s",+ ret = measured_set_boot(&set);+ if (ret) {+ if (ret != -ENOENT)+ pr_warn("upatch: cannot read this boot's records: %s",+ strerror(-ret));+ return;+ }+ ret = measured_unmeasured_pins(set, undo_unmeasured_pin, NULL);+ if (ret >= 0)+ ret = measured_unmeasured_archives(set, undo_unmeasured_archive,+ NULL);+ measured_set_free(set);+ if (ret < 0)+ pr_warn("upatch: cannot check the pins and archives against this boot's records: %s",strerror(-ret));}@@ -2908,7 +2934,7 @@ static int cmd_upatch_load(int argc, const char **argv)"cannot take the register lock");goto done;}- undo_unmeasured_pins();+ undo_unmeasured();/** Only a completed load records the payload and only an unload* removes it. A load over a live upatch rebinds its serializer pins@@ -3092,7 +3118,7 @@ static int cmd_upatch_unload(int argc, const char **argv)"cannot take the register lock");goto done;}- undo_unmeasured_pins();+ undo_unmeasured();/* A bad signature fails here, before anything is removed. */if (__upatch_apply(file, true, &rep) != 0) {pr_err("upatch unload: signature verification failed; refusing");diff --git a/testing/functional/tamperproof/t6004-conditions.sh b/testing/functional/tamperproof/t6004-conditions.shindex 62be9b6a..2380c257 100755--- a/testing/functional/tamperproof/t6004-conditions.sh+++ b/testing/functional/tamperproof/t6004-conditions.sh@@ -109,14 +109,14 @@ test_expect_success 'a bound register is measured' 'test_expect_success 'every pinned upatch in the records is OK' './$H 1 bpf 100 100 match |- grep -qx "UpatchesMeasured OK every pinned upatch is in this boot.s records"+ grep -qx "UpatchesMeasured OK every pinned or archived upatch is in this boot.s records"'test_expect_success 'a pin without a record of this boot is tampered' 'out=$(SHIRUDO_TEST_PINS=unmeasured:shirudo-test-basic,kernel-obs ./$H 1 bpf 100 100 match) &&echo "$out" | grep -qx "status=tampered" &&- echo "$out" | grep -qx "reason=a upatch is pinned without a record of this boot" &&- echo "$out" | grep -qx "UpatchesMeasured ALERT 2 pinned without a record of this boot: shirudo-test-basic,kernel-obs"+ echo "$out" | grep -qx "reason=a upatch is pinned or archived without a record of this boot" &&+ echo "$out" | grep -qx "UpatchesMeasured ALERT 2 pinned or archived without a record of this boot: shirudo-test-basic,kernel-obs"'test_expect_success 'pins that cannot be checked are a warning, not a verdict' 'diff --git a/testing/functional/tamperproof/t6144-returned-archive.sh b/testing/functional/tamperproof/t6144-returned-archive.shnew file mode 100755index 00000000..d53f2a3e--- /dev/null+++ b/testing/functional/tamperproof/t6144-returned-archive.sh@@ -0,0 +1,109 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t6144 -- an archive root brings back is not shirudo's to restore. A+# labeled archive hard-linked out before its unload and back into the+# archive directory while the directory's mark is evicted (R15) carries+# the label, but the eventlog records its unload: status reports it,+# init does not restore it and the next upatch command removes it.++cd "$(dirname "$0")/../.."+. ./integration-lib.sh+target_guard+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"+FIXTURES=$SHIRUDO_TEST_FIXTURES_DIR+NAME=shirudo-test-basic+OTHER=shirudo-test-marker+LOAD="$FIXTURES/$NAME.upatch"+UNLOAD="$FIXTURES/$NAME.unload.upatch"+PINDIR="/run/shirudo/bpffs/upatches/$NAME"+OTHERDIR="/run/shirudo/bpffs/upatches/$OTHER"+ARCHIVE="/var/lib/shirudo/upatches/$NAME.upatch"+KEEPDIR=/var/lib/t6144+KEEP="$KEEPDIR/keep.upatch"+W=$(mktemp -d)+cleanup() {+ [ ! -e "$OTHERDIR" ] ||+ "$SHIRUDO_BIN" upatch unload "$FIXTURES/$OTHER.unload.upatch" \+ >/dev/null 2>&1 || :+ [ ! -e "$PINDIR" ] ||+ "$SHIRUDO_BIN" upatch unload "$UNLOAD" >/dev/null 2>&1 || :+ # The kept link carries the label, so root cannot unlink it: the+ # directory stays behind with it.+ rm -rf "$KEEPDIR" "$W" 2>/dev/null || :+}+trap cleanup EXIT+for f in "$LOAD" "$UNLOAD" "$FIXTURES/$OTHER.upatch" \+ "$FIXTURES/$OTHER.unload.upatch"; do+ [ -s "$f" ] || test_skip_all "missing fixture $f"+done+[ ! -e "$PINDIR" ] || "$SHIRUDO_BIN" upatch unload "$UNLOAD" >/dev/null 2>&1+[ ! -e "$OTHERDIR" ] ||+ "$SHIRUDO_BIN" upatch unload "$FIXTURES/$OTHER.unload.upatch" \+ >/dev/null 2>&1+for d in "$PINDIR" "$OTHERDIR"; do+ [ ! -e "$d" ] || test_skip_all "$(basename "$d") cannot be unloaded"+done+[ ! -e "$ARCHIVE" ] || test_skip_all "$NAME is archived already"+mkdir -p "$KEEPDIR"++label_len() {+ python3 -c 'import os, sys+print(len(os.getxattr(sys.argv[1], "security.bpf.shirudo")))' "$1"+}++# The verdict and the UpatchesMeasured condition of a status document.+measured_condition() {+ python3 - "$1" <<'PY'+import json, sys+d = json.load(open(sys.argv[1], encoding="utf-8"))+c = [c for c in d["conditions"] if c["type"] == "UpatchesMeasured"]+print(d["status"], c[0]["status"] if c else "-", c[0]["detail"] if c else "-")+PY+}++test_expect_success 'a labeled archive can be hard-linked out of the archive directory' '+ "$SHIRUDO_BIN" upatch load "$LOAD" >/dev/null 2>&1 &&+ [ -s "$ARCHIVE" ] &&+ ln "$ARCHIVE" "$KEEP" &&+ [ "$(label_len "$KEEP")" = 64 ]+'+test_expect_success 'after its unload the archive returns through the link once the mark is evicted' '+ "$SHIRUDO_BIN" upatch unload "$UNLOAD" >/dev/null 2>&1 &&+ [ ! -e "$ARCHIVE" ] &&+ ! ln "$KEEP" "$ARCHIVE" 2>/dev/null &&+ sync &&+ echo 2 >/proc/sys/vm/drop_caches &&+ ln "$KEEP" "$ARCHIVE" &&+ [ "$(label_len "$ARCHIVE")" = 64 ]+'+test_expect_success 'status reports the returned archive as tampered' '+ "$SHIRUDO_BIN" status --json >"$W/status.json" 2>/dev/null &&+ measured_condition "$W/status.json" >"$W/cond" &&+ read -r verdict cond detail <"$W/cond" &&+ [ "$verdict" = tampered ] &&+ [ "$cond" = ALERT ] &&+ case "$detail" in *"$NAME"*) true ;; *) false ;; esac+'+test_expect_success 'init does not restore the returned archive' '+ "$SHIRUDO_BIN" init >/dev/null 2>"$W/init.err" &&+ grep -q "$NAME.upatch is archived without a record of its load" \+ "$W/init.err" &&+ [ ! -e "$PINDIR" ] &&+ [ -e "$ARCHIVE" ]+'+test_expect_success 'the next upatch command removes the returned archive' '+ "$SHIRUDO_BIN" upatch load "$FIXTURES/$OTHER.upatch" >/dev/null 2>&1 &&+ [ ! -e "$ARCHIVE" ] &&+ [ -e "$OTHERDIR/link" ] &&+ "$SHIRUDO_BIN" status --json >"$W/status.json" 2>/dev/null &&+ measured_condition "$W/status.json" >"$W/cond" &&+ read -r verdict cond detail <"$W/cond" &&+ [ "$verdict" != tampered ] &&+ [ "$cond" = OK ] &&+ "$SHIRUDO_BIN" upatch unload "$FIXTURES/$OTHER.unload.upatch" \+ >/dev/null 2>&1 &&+ [ ! -e "$OTHERDIR" ]+'+test_donediff --git a/util/conditions.c b/util/conditions.cindex 5c931c7c..46cf5bc2 100644--- a/util/conditions.c+++ b/util/conditions.c@@ -149,12 +149,12 @@ size_t conditions(const struct conditions_input *in,strerror(-in->pins_rc));else if (in->pins_unmeasured)set_detail(&c[n], "ALERT",- "%d pinned without a record of this boot: %s",+ "%d pinned or archived without a record of this boot: %s",in->pins_unmeasured,in->pins_detail ? in->pins_detail : "?");elseset_detail(&c[n], "OK",- "every pinned upatch is in this boot's records");+ "every pinned or archived upatch is in this boot's records");n++;}if (n < cap) {@@ -250,7 +250,7 @@ void status_reason(const struct conditions_input *in,if (in->cm_seen && !in->chain_matches)strscpy(buf, "live register != eventlog replay", cap);else if (in->pins_unmeasured)- strscpy(buf, "a upatch is pinned without a record of this boot",+ strscpy(buf, "a upatch is pinned or archived without a record of this boot",cap);else if (config_untrusted(in))strscpy(buf, "the selected config cannot be verified against its records",diff --git a/util/conditions.h b/util/conditions.hindex ce04ab39..0b4d327f 100644--- a/util/conditions.h+++ b/util/conditions.h@@ -47,7 +47,7 @@ struct conditions_input {int config_state; /* image_config_state() */const char *config_root; /* hex, when config_seen */int pins_rc; /* 0 when the pins were checked, else -errno */- int pins_unmeasured; /* pinned without a record this boot */+ int pins_unmeasured; /* pinned or archived without a record this boot */const char *pins_detail; /* their names, when any */};diff --git a/util/eventlog.c b/util/eventlog.cindex dc185b10..48ff1828 100644--- a/util/eventlog.c+++ b/util/eventlog.c@@ -179,8 +179,9 @@ out:* This boot's records from its last init line on; the callback learns* which line that is so a replay can start from zero.*/-static int walk_lines(char *buf, int (*cb)(const char *line, size_t len,- bool is_init, void *ctx), void *ctx)+static int walk_lines(char *buf, bool all,+ int (*cb)(const char *line, size_t len, bool is_init,+ void *ctx), void *ctx){char boot_id[64], line_boot[64], type[32];bool in_boot = false;@@ -204,22 +205,23 @@ static int walk_lines(char *buf, int (*cb)(const char *line, size_t len,ret = -EINVAL;break;}- if (!f[0].seen || !boot_id[0] || strcmp(line_boot, boot_id))+ if (!all &&+ (!f[0].seen || !boot_id[0] || strcmp(line_boot, boot_id)))continue;is_init = f[1].seen && strcmp(type, "init") == 0;if (is_init)in_boot = true;- if (!in_boot)+ if (!all && !in_boot)continue;ret = cb(line, strlen(line), is_init, ctx);}- if (!ret && !in_boot)+ if (!all && !ret && !in_boot)return -ENOENT;return ret;}-static int walk_boot(int (*cb)(const char *line, size_t len, bool is_init,- void *ctx), void *ctx)+static int walk_log(bool all, int (*cb)(const char *line, size_t len,+ bool is_init, void *ctx), void *ctx){char *buf = NULL;size_t len = 0;@@ -228,11 +230,17 @@ static int walk_boot(int (*cb)(const char *line, size_t len, bool is_init,ret = read_log(&buf, &len);if (ret)return ret;- ret = walk_lines(buf, cb, ctx);+ ret = walk_lines(buf, all, cb, ctx);xfree(buf, len + 1);return ret;}+static int walk_boot(int (*cb)(const char *line, size_t len, bool is_init,+ void *ctx), void *ctx)+{+ return walk_log(false, cb, ctx);+}+struct adopt_ctx {const char *line;size_t len;@@ -261,7 +269,7 @@ static int log_holds(const char *line, size_t len)return 0;if (ret)return ret;- ret = walk_lines(buf, adopt_seen, &a);+ ret = walk_lines(buf, false, adopt_seen, &a);xfree(buf, blen + 1);if (ret && ret != -ENOENT)return ret;@@ -544,6 +552,16 @@ int eventlog_boot_upatches(int (*cb)(enum eventlog_upatch_event event,return walk_boot(upatches_line, &u);}+int eventlog_upatches(int (*cb)(enum eventlog_upatch_event event,+ const char *name, const char *payload_hex,+ void *ctx),+ void *ctx)+{+ struct upatches_ctx u = { .cb = cb, .ctx = ctx };++ return walk_log(true, upatches_line, &u);+}+void eventlog_timestamp(char *out, size_t cap){iso8601(time(NULL), out, cap);diff --git a/util/eventlog.h b/util/eventlog.hindex 1d78408b..03d016d5 100644--- a/util/eventlog.h+++ b/util/eventlog.h@@ -81,14 +81,19 @@ enum eventlog_upatch_event {};/*- * The loads and unloads this boot's records measure, in order. An init- * record gives EVENTLOG_UPATCH_INIT with no name, which starts the set- * over, then each upatch of its set as a load.+ * The loads and unloads the records measure, in order: this boot's, or+ * every boot's since the log began. An init record gives+ * EVENTLOG_UPATCH_INIT with no name, which starts the set over, then+ * each upatch of its set as a load.*/int eventlog_boot_upatches(int (*cb)(enum eventlog_upatch_event event,const char *name,const char *payload_hex, void *ctx),void *ctx);+int eventlog_upatches(int (*cb)(enum eventlog_upatch_event event,+ const char *name, const char *payload_hex,+ void *ctx),+ void *ctx);/** 1 if appending one more event would push the eventlog past max_bytes;diff --git a/util/measured.c b/util/measured.cindex 85079509..d564ab53 100644--- a/util/measured.c+++ b/util/measured.c@@ -16,6 +16,8 @@#include "malloc.h"#include "measured.h"#include "paths.h"+#include "seal.h"+#include "upatch.h"#define MEASURED_MAX 4096@@ -61,8 +63,45 @@ static int measured_event(enum eventlog_upatch_event event, const char *name,return 0;}-static bool measured_holds(const struct measured_set *s, const char *name,- const char *payload_hex)+static int measured_set_fold(struct measured_set **out, bool all)+{+ struct measured_set *s;+ int ret;++ *out = NULL;+ s = xmalloc(sizeof(*s));+ if (!s)+ return -ENOMEM;+ s->n = 0;+ s->entries = xcalloc(MEASURED_MAX, sizeof(*s->entries));+ if (!s->entries) {+ xfree(s, sizeof(*s));+ return -ENOMEM;+ }+ ret = all ? eventlog_upatches(measured_event, s) :+ eventlog_boot_upatches(measured_event, s);+ if (ret == -ENOENT && all)+ ret = 0;+ if (ret) {+ measured_set_free(s);+ return ret;+ }+ *out = s;+ return 0;+}++int measured_set_boot(struct measured_set **out)+{+ return measured_set_fold(out, false);+}++int measured_set_log(struct measured_set **out)+{+ return measured_set_fold(out, true);+}++bool measured_holds(const struct measured_set *s, const char *name,+ const char *payload_hex){size_t i;@@ -74,24 +113,33 @@ static bool measured_holds(const struct measured_set *s, const char *name,return false;}-int measured_unmeasured_pins(int (*cb)(const char *name, void *ctx),+void measured_set_free(struct measured_set *s)+{+ if (!s)+ return;+ xfree(s->entries, MEASURED_MAX * sizeof(*s->entries));+ xfree(s, sizeof(*s));+}++static void free_names(struct dirent **names, int n)+{+ int i;++ for (i = 0; i < n; i++)+ libc_free(names[i]);+ libc_free(names);+}++int measured_unmeasured_pins(const struct measured_set *s,+ int (*cb)(const char *name, void *ctx),void *ctx){- struct measured_set s = {};struct dirent **pins = NULL;- int n, i, ret, unmeasured = 0;+ int n, i, ret = 0, unmeasured = 0;- s.entries = xcalloc(MEASURED_MAX, sizeof(*s.entries));- if (!s.entries)- return -ENOMEM;- ret = eventlog_boot_upatches(measured_event, &s);- if (ret)- goto out;n = scandir(BPFFS_UPATCHES_DIR, &pins, NULL, alphasort);- if (n < 0) {- ret = errno == ENOENT ? 0 : -errno;- goto out;- }+ if (n < 0)+ return errno == ENOENT ? 0 : -errno;for (i = 0; i < n; i++) {char payload_hex[2 * UPATCH_PAYLOAD_HASH_LEN + 1] = "";__u8 payload[UPATCH_PAYLOAD_HASH_LEN];@@ -108,7 +156,7 @@ int measured_unmeasured_pins(int (*cb)(const char *name, void *ctx),if (getxattr(dir, XATTR_PAYLOAD, payload, sizeof(payload)) ==(ssize_t)sizeof(payload))hex_encode(payload, sizeof(payload), payload_hex);- if (measured_holds(&s, name, payload_hex))+ if (measured_holds(s, name, payload_hex))continue;unmeasured++;if (cb) {@@ -117,10 +165,45 @@ int measured_unmeasured_pins(int (*cb)(const char *name, void *ctx),break;}}- for (i = 0; i < n; i++)- libc_free(pins[i]);- libc_free(pins);-out:- xfree(s.entries, MEASURED_MAX * sizeof(*s.entries));+ free_names(pins, n);+ return ret ? ret : unmeasured;+}++int measured_unmeasured_archives(const struct measured_set *s,+ int (*cb)(const char *name,+ const char *path, void *ctx),+ void *ctx)+{+ struct dirent **names = NULL;+ int n, i, ret = 0, unmeasured = 0;++ n = scandir(UPATCHES_DIR, &names, upatch_select, alphasort);+ if (n < 0)+ return errno == ENOENT ? 0 : -errno;+ for (i = 0; i < n; i++) {+ char payload_hex[2 * UPATCH_PAYLOAD_HASH_LEN + 1];+ char name[UPATCH_NAME_MAX + 1];+ char path[PATH_MAX];+ struct upatch u;++ if (strsprintf(path, sizeof(path), "%s/%s", UPATCHES_DIR,+ names[i]->d_name) < 0 ||+ !seal_owns(path) || upatch_open(path, &u))+ continue;+ memcpy(name, u.hdr.name, UPATCH_NAME_MAX);+ name[UPATCH_NAME_MAX] = '\0';+ hex_encode(u.hdr.payload_sha256, UPATCH_PAYLOAD_HASH_LEN,+ payload_hex);+ upatch_close(&u);+ if (measured_holds(s, name, payload_hex))+ continue;+ unmeasured++;+ if (cb) {+ ret = cb(name, path, ctx);+ if (ret)+ break;+ }+ }+ free_names(names, n);return ret ? ret : unmeasured;}diff --git a/util/measured.h b/util/measured.hindex 16fd00de..fddcd741 100644--- a/util/measured.h+++ b/util/measured.h@@ -4,16 +4,40 @@#ifndef SHIRUDO_MEASURED_H#define SHIRUDO_MEASURED_H+#include <stdbool.h>++/*+ * The set of upatches the eventlog records as loaded, each with the+ * payload of its load: an init record's set, with every later load+ * added and every unload removed, in order. measured_set_boot() folds+ * this boot's records and is -ENOENT when there are none;+ * measured_set_log() folds every boot's, an empty set when there is no+ * log yet.+ */+struct measured_set;++int measured_set_boot(struct measured_set **out);+int measured_set_log(struct measured_set **out);+bool measured_holds(const struct measured_set *s, const char *name,+ const char *payload_hex);+void measured_set_free(struct measured_set *s);+/*- * The upatches pinned in the private bpffs that this boot's records do- * not measure as loaded with the payload their pin records: what a load- * stopped between its attach and its extend leaves, or an unload stopped- * after its extend. cb runs for each with its name, and a non-zero- * return ends the walk with that value. The number found, or -errno- * when the pins or the records cannot be read; -ENOENT when this boot- * has no record.+ * The upatches pinned in the private bpffs, or archived with the seal+ * label, that the set does not hold with the payload their pin or+ * archive records: what a load stopped between its pins and its extend+ * leaves, an unload stopped after its extend, or an archive root+ * brought back after its unload. cb runs for each with its name, and+ * the archive's path, and a non-zero return ends the walk with that+ * value. The number found, or -errno when the pins or archives cannot+ * be read.*/-int measured_unmeasured_pins(int (*cb)(const char *name, void *ctx),+int measured_unmeasured_pins(const struct measured_set *s,+ int (*cb)(const char *name, void *ctx),void *ctx);+int measured_unmeasured_archives(const struct measured_set *s,+ int (*cb)(const char *name,+ const char *path, void *ctx),+ void *ctx);#endif /* SHIRUDO_MEASURED_H */