eBPF-based security platform
status: quote the keepalive and send it once a minute as a string body
John Fastabend163ff4e40d28
diff --git a/Documentation/concepts/background/opentelemetry.rst b/Documentation/concepts/background/opentelemetry.rstindex 1dd3f87d..fab7379d 100644--- a/Documentation/concepts/background/opentelemetry.rst+++ b/Documentation/concepts/background/opentelemetry.rst@@ -105,17 +105,19 @@ Figure 1 shows the two paths from a target to a collector... figure:: /images/background-telemetry-export.svg:alt: Map snapshots pass from a BPF map through a serializer or direct- read and a signed decoder into OTLP JSON; the status report- becomes a keepalive log; both are posted to a collector.+ read and a signed decoder into OTLP JSON; the keepalive body,+ quoted by the TPM, becomes a keepalive log; both are posted to a+ collector.Figure 1. Telemetry export. Two one-shot commands, each started by asystemd timer, build OTLP JSON documents and post them to thecollector. Nothing on the target listens for connections.-``shirudo-keepalive.timer`` runs ``shirudo status --otel---include-system``, and ``shirudo-map-export.timer`` runs ``shirudo-upatch map --all``. Each timer starts its service five seconds after boot-and again five seconds after the previous run finished.+``shirudo-keepalive.timer`` runs ``shirudo status --otel``, and+``shirudo-map-export.timer`` runs ``shirudo upatch map --all``. Each+timer starts its service five seconds after boot. The keepalive timer+starts it again a minute after the previous run finished, the map-export+timer five seconds after.shirudo speaks OTLP over HTTP with the JSON encoding only and refuses an``OTEL_EXPORTER_OTLP_PROTOCOL`` other than ``http/json``. Every request@@ -124,14 +126,19 @@ carries the resource attributes ``service.name`` (``shirudo``),``gethostname()`` returns.The keepalive is one log record with the event name-``shirudo.keepalive``. Its body is the ``shirudo status --json``-document. Its attributes are ``shirudo.status``, ``shirudo.version_id``-and ``shirudo.tamper_attempts``, the number of refusals the guards counted-this boot. The severity follows the status: ``INFO`` for ``ok``,-``WARN`` for ``degraded``, ``init-pending`` and ``reboot-pending``, and-``ERROR`` for every other status. ``shirudo status --otel`` sends the-keepalive only when the signed config or the environment names an-endpoint, and never falls back to the default ``localhost`` endpoint.+``shirudo.keepalive``. Its body is a string, a compact JSON status+record of about a kilobyte: the verdict, the conditions, the tamper+counters, the build, the config and image, the tree the target follows+and the upatches it has loaded. Its one attribute, ``shirudo.quote``, is+a TPM quote of the SHA-256 of those bytes by the attestation key of+``shirudo attest``. The body travels as a string because a collector may+re-encode a structure, and the quote covers the exact bytes. The+severity follows the verdict: ``INFO`` for ``ok``, ``WARN`` for+``degraded``, ``init-pending`` and ``reboot-pending``, and ``ERROR`` for+every other verdict. ``shirudo status --otel`` sends the keepalive only+when the signed config or the environment names an endpoint, never falls+back to the default ``localhost`` endpoint, and sends nothing when the+TPM does not quote.A map snapshot goes through the decoder the upatch signed for that map,which declares whether the map becomes a log record or metrics. A log@@ -176,17 +183,20 @@ target.Limits-------Telemetry carries no proof of origin. The documents are not signed and-not bound to the TPM. The host name in them is whatever the host-reports. The credentials and the CA certificate for the collector come+Map snapshots carry no proof of origin: they are not signed and not+bound to the TPM. The keepalive's quote shows that its body is unchanged+since the attestation key signed it, and its clock orders the+keepalives of one key. It does not show that the key lives in a genuine+TPM, and the body is still what the target reports. The host name in a+document is whatever the host reports. The credentials and the CA certificate for the collector comefrom ``/etc/shirudo/map-export.env``, a file root on the target canchange, and ``map_export.otel_insecure`` turns off certificateverification.Root on the target can therefore stop the timers, drain a map by running``shirudo upatch map`` itself, point the keepalive at another collector-when the signed config names none, or post a keepalive of its own that-reports ``ok`` with no refusals. A missing keepalive, or one at+when the signed config names none, or have the TPM quote a body of its+own that reports ``ok`` with no refusals. A missing keepalive, or one at``ERROR``, is worth acting on. A keepalive that reports ``ok`` provesnothing.diff --git a/Documentation/concepts/background/siem-export.rst b/Documentation/concepts/background/siem-export.rstindex 1c6f8903..c8d8bbdb 100644--- a/Documentation/concepts/background/siem-export.rst+++ b/Documentation/concepts/background/siem-export.rst@@ -45,21 +45,23 @@ The target keeps no spool. A map export that fails loses what the mapcollected in that interval, and a keepalive that fails leaves a gapuntil the next one. The collector's sending queue is the only buffer onthe way. A collector can also filter or rewrite records before export,-for example to drop the kernel configuration from keepalives, as-:doc:`/operate/run/telemetry` shows.+but it must leave a keepalive's body as it arrived: its quote covers+those exact bytes.Where the fields land---------------------Every record carries the resource attribute ``host.name``, which namesthe target. The event name tells a keepalive, ``shirudo.keepalive``,-from a map snapshot, ``shirudo.bpf.map.snapshot``. The record's-attributes hold the few fields worth filtering and alerting on, among-them ``shirudo.status`` and ``shirudo.tamper_attempts`` on a keepalive.-The body holds the whole document: the ``shirudo status --json`` report,-or what a map's decoder returned.+from a map snapshot, ``shirudo.bpf.map.snapshot``. A map snapshot's+attributes name its upatch and map, and its body holds what the map's+decoder returned. A keepalive's body is a string, the compact JSON+status record that the target's TPM quoted, with the verdict, the+conditions and the tamper counters among its keys+(:doc:`/reference/cli/status`). Its one attribute is the quote.-Each exporter keeps that split in its own way:+Each exporter keeps the body in its own way, and each backend reads the+keys of a keepalive out of it with a function of its own:.. list-table:::header-rows: 1@@ -71,26 +73,25 @@ Each exporter keeps that split in its own way:- Body* - ClickHouse- ``ResourceAttributes['host.name']``- - ``LogAttributes['shirudo.status']``+ - ``JSONExtractString(Body, 'verdict')``- ``Body``, as JSON text* - Elasticsearch- ``host.name``- - ``shirudo.status``- - ``body.structured``+ - ``GROK`` on ``body.text``+ - ``body.text`` for a keepalive, ``body.structured`` for a snapshot* - Loki- Label ``host_name``- - Structured metadata ``shirudo_status``+ - The ``json`` parser on the log line- Log line* - Splunk- ``host``- - Indexed field ``shirudo.status``+ - ``rex`` on the event- EventLoki makes ``host_name`` a label only when configured to, as-:doc:`/operate/integrations/grafana` shows. Rules work best on the-attributes, which every backend keeps as fields of their own, while the-body is large, stored as text by some backends and refused above a size-limit by others.+:doc:`/operate/integrations/grafana` shows. The keys of a keepalive+always come in the same order and its body is about a kilobyte, so a+pattern finds a key in it as reliably as a JSON parser does.What to detect--------------@@ -105,22 +106,23 @@ match an event that does not exist, so the query compares the lastkeepalive of every target it knows against the current time. It knowsthe targets that reported within a longer window, such as a day, so atarget silent for longer drops out of the alert. A-keepalive runs five seconds after the previous run ends and may wait up-to 30 seconds for the config operation lock, so two minutes without one-spans several missed intervals.+keepalive runs a minute after the previous run ends and may wait up to+30 seconds for the config operation lock, so five minutes without one+spans several missed intervals. A tree sync holds that lock for as long+as it runs, so a target whose syncs take minutes needs a longer+window.A verdict other than ``ok`` is the second. The keepalive's severityfollows the verdict, ``WARN`` or ``ERROR``, so a rule on severitycatches the same records.-A rise of ``shirudo.tamper_attempts`` is the third. The attribute counts-the refusals of the guards since boot, so a rise means something on the-target tried an operation the guards refused. The counters start at-zero each boot. A rule that took the largest count in a window minus the-smallest would fire on every reboot. The examples subtract the earliest-count from the latest instead, which a reboot makes negative. The price-is that a rise close to a reboot can go unreported; the count in each-keepalive still shows it.+A rise of a tamper counter is the third. The body's ``tamper`` lists+every counter of the guards' refusals since boot, so a change means+something on the target tried an operation the guards refused. The+counters start at zero each boot. A rule that compared any two+keepalives of a target would fire on every reboot, so the examples+compare only the keepalives of one ``boot_id``, within which the+counters only grow.Map snapshots carry what upatches observe, such as the programs that``kernel-obs`` saw run. Their fields depend on the upatch's decoder, so@@ -130,23 +132,23 @@ record join it to events from other sources.Volume-------The keepalive's body includes the system section, and with it the-kernel configuration, so a keepalive from a distribution kernel is a-few hundred kilobytes. At one keepalive every five seconds that adds up-to several gigabytes a day for each target. That matters to a SIEM-priced or capped by ingested volume, and to backends that limit the size-of a record or the rate of a stream. Dropping the kernel configuration-at the collector cuts a keepalive to a few kilobytes, and-``kernel_release`` and ``kernel_build_id`` still name the kernel.+A keepalive's body is about a kilobyte, and with its quote and resource+attributes a record is about two. At one keepalive a minute that adds up+to a few megabytes a day for each target. Map snapshots are what a SIEM+priced or capped by ingested volume, or a backend that limits the size+of a record or the rate of a stream, has to size for: their volume+depends on the loaded upatches and their decoders.Limits-------Telemetry is the target's own account of itself. It is not signed and-not bound to the TPM, and root on a target can stop it or send a-keepalive that reports ``ok`` with no refusals. A SIEM alert on a-keepalive tells you where to look. The silence alert catches a target-whose export was stopped, but not one whose root sends forged+Telemetry is the target's own account of itself. A keepalive's quote+shows that its body is unchanged since the target's attestation key+signed it, but not that the key lives in a genuine TPM, and root on a+target can stop the keepalive or have the TPM quote a body that reports+``ok`` with no refusals. Map snapshots are not signed at all. A SIEM+alert on a keepalive tells you where to look. The silence alert catches+a target whose export was stopped, but not one whose root sends forgedkeepalives instead.Evidence of what a target runs is the TPM-signed record that ``shirudodiff --git a/Documentation/concepts/comparisons.rst b/Documentation/concepts/comparisons.rstindex 83cc17a0..cfce4904 100644--- a/Documentation/concepts/comparisons.rst+++ b/Documentation/concepts/comparisons.rst@@ -165,7 +165,8 @@ For delivering and enforcing BPF on a target, shirudo takes thismodel's place. The target runs no daemon and listens on no socket.Enforcement stays in links pinned in a private bpffs after ``init``exits. Packages arrive by pull, from timers. The status keepalive is the-target's own, unauthenticated account, and only TPM-signed evidence that+target's own account, quoted by a key no one has tied to a TPM, and only+TPM-signed evidence thatthe operator verifies off the target is proof(:doc:`/concepts/operator-and-target`). shirudo has no inventory,rollout orchestration or remote response; those stay with thediff --git a/Documentation/concepts/glossary.rst b/Documentation/concepts/glossary.rstindex 550a03ec..1de0bfa6 100644--- a/Documentation/concepts/glossary.rst+++ b/Documentation/concepts/glossary.rst@@ -182,11 +182,12 @@ it.keepaliveAn OTLP log record named ``shirudo.keepalive`` that carries a- target's status. ``shirudo-keepalive.timer`` runs ``shirudo status- --otel --include-system`` about every five seconds, which sends one- when an OTLP endpoint is configured. A missing keepalive tells a- collector that a target stopped reporting; a present one is still- the target's own account. See :doc:`/operate/run/telemetry`.+ target's status record and the TPM quote of it.+ ``shirudo-keepalive.timer`` runs ``shirudo status --otel`` about+ every minute, which sends one when an OTLP endpoint is configured+ and the TPM quotes. A missing keepalive tells a collector that a+ target stopped reporting; a present one is still the target's own+ account. See :doc:`/operate/run/telemetry`.load artifactA ``.upatch`` file that installs an upatch: a header with the namediff --git a/Documentation/concepts/operator-and-target.rst b/Documentation/concepts/operator-and-target.rstindex fae5df9e..9326355f 100644--- a/Documentation/concepts/operator-and-target.rst+++ b/Documentation/concepts/operator-and-target.rst@@ -186,8 +186,8 @@ Agentless targetA target runs no daemon and listens on no socket. Every operation is aone-shot command, started by root or by a systemd unit, that does its workand exits: ``init`` at boot from the initrd and again from the root file-system, package and tree updates every minute, and map export and status-keepalives every five seconds.+system, package and tree updates and status keepalives every minute,+and map export every five seconds.:doc:`/reference/systemd-units` lists the units and timers.What must outlive a command is pinned in the private bpffs, and what mustdiff --git a/Documentation/contribute/code/develop-locally.rst b/Documentation/contribute/code/develop-locally.rstindex 179341a4..cfe1cb41 100644--- a/Documentation/contribute/code/develop-locally.rst+++ b/Documentation/contribute/code/develop-locally.rst@@ -235,7 +235,7 @@ from the config the target runs, and activate it.The services read ``/etc/shirudo/bpm/environment``. Your shell needsthe variable as well.-8. Check the collector's terminal. Every five seconds, the target's+8. Check the collector's terminal. Every minute, the target'skeepalive timer sends a record with ``EventName:shirudo.keepalive``.diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex a597fa2f..755d71c1 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -275,6 +275,11 @@ signed config image.- The ``tpm_command`` guard: root without authority cannot extendthe register, through inherited and nonblocking descriptorstoo+ * - ``t4104-keepalive-quote``+ - The keepalive quote under ``shirudo-quote-check``: it covers the+ body, its signer is the attestation key of ``attest`` under the+ endorsement hierarchy, a later quote has a later clock, and a+ body altered by one byte is ``body_mismatch````image`` (5)~~~~~~~~~~~~~@@ -561,6 +566,10 @@ signed config image.export* - ``t8105-export-tls``- CA and client certificate selection, the S3 CA+ * - ``t8106-status-otel-quote``+ - ``status --otel`` on a target: one record, the body as a string+ with its keys in order, the quote as the one attribute and the+ severity of the verdict``end2end`` (9)~~~~~~~~~~~~~~~@@ -729,7 +738,7 @@ Coverage by area``t6125``, ``t6128``, ``t6143``, ``t6144``. Unit: ``chain``* - Attestation- ``t2003``, ``t2005``, ``t4003``, ``t4004``, ``t4102``,- ``t9105``. Fuzz: ``attest``, ``tpm-wire``+ ``t4104``, ``t9105``. Fuzz: ``attest``, ``tpm-wire``* - Eventlog- ``t4002``, ``t4102``, ``t5007``, ``t6114``, ``t6128``. Fuzz:``eventlog``. Unit: ``eventlog``, ``io``@@ -758,8 +767,8 @@ Coverage by areaUnauthorized policy-xattr changes: ``t6111``. Task and socketinheritance: ``t6141``, ``t6142``* - Telemetry- - ``t6139``, ``t7109``, ``t8001`` to ``t8007``, ``t8101`` to- ``t8105``, ``t9101`` to ``t9105``. Fuzz: ``otel``,+ - ``t4104``, ``t6139``, ``t7109``, ``t8001`` to ``t8007``,+ ``t8101`` to ``t8106``, ``t9101`` to ``t9105``. Fuzz: ``otel``,``quote-check``, ``serializer``. Unit: ``keepalive``,``sysinfo``* - Decodersdiff --git a/Documentation/images/background-telemetry-export.svg b/Documentation/images/background-telemetry-export.svgindex b1effa23..6be0a354 100644--- a/Documentation/images/background-telemetry-export.svg+++ b/Documentation/images/background-telemetry-export.svg@@ -37,8 +37,8 @@<text x="472" y="88" font-size="13">OTLP JSON</text><text x="472" y="106" font-size="11">log record or</text><text x="472" y="119" font-size="11">metrics</text>- <text x="210" y="198" font-size="13">status report</text>- <text x="210" y="216" font-size="11">conditions, TPM, tamper counters</text>+ <text x="210" y="198" font-size="13">keepalive body</text>+ <text x="210" y="216" font-size="11">quoted by the TPM</text><text x="472" y="198" font-size="13">OTLP JSON</text><text x="472" y="216" font-size="11">keepalive log</text><text x="672" y="135" font-size="13">collector</text>diff --git a/Documentation/internals/design-decisions.rst b/Documentation/internals/design-decisions.rstindex 38063769..60bf2c1d 100644--- a/Documentation/internals/design-decisions.rst+++ b/Documentation/internals/design-decisions.rst@@ -243,6 +243,24 @@ would read it once, at the price of a change to the node's parser andto the ``bpm-tree-reader`` and ``bpm-tree-sync-model`` proofs thatinclude it; it is left for later.+A keepalive key for each run+----------------------------++``status --otel`` creates the attestation key it quotes the keepalive+with at every run, with ``TPM2_CreatePrimary`` under the endorsement+hierarchy, and flushes it after the quote. The key comes from a fixed+template, so every run gets the same key and the backend the same name;+nothing about it is kept on the target between runs.++The cost is a primary key derivation once a minute, which a slow+hardware TPM can take hundreds of milliseconds for+(:doc:`/operate/plan/overhead`). The optimisation to take up if that+cost matters is to keep the key under a persistent handle,+``TPM2_EvictControl`` once and a lookup at every run. The rule against+a persistent index concerns the measurement register and does not+forbid it, but it adds TPM state that outlives a boot: a handle to+allocate, to find taken, and to clear on decommission.+Related-------diff --git a/Documentation/operate/deploy/boot-integration.rst b/Documentation/operate/deploy/boot-integration.rstindex 689087d9..7698de6a 100644--- a/Documentation/operate/deploy/boot-integration.rst+++ b/Documentation/operate/deploy/boot-integration.rst@@ -273,7 +273,7 @@ the initrd, from the binary the UKI authenticates.[Service]ExecStart=- ExecStart=/run/shirudo/runtime/usr/bin/shirudo status --otel --include-system+ ExecStart=/run/shirudo/runtime/usr/bin/shirudo status --otel3. Write ``/etc/systemd/system/shirudo-map-export.service.d/runtime.conf``:diff --git a/Documentation/operate/integrations/clickhouse.rst b/Documentation/operate/integrations/clickhouse.rstindex 74c85fe9..339cc536 100644--- a/Documentation/operate/integrations/clickhouse.rst+++ b/Documentation/operate/integrations/clickhouse.rst@@ -91,21 +91,24 @@ Check the dataSELECT Timestamp,ResourceAttributes['host.name'] AS host,- LogAttributes['shirudo.status'] AS status+ JSONExtractString(Body, 'verdict') AS verdictFROM shirudo.otel_logsWHERE ServiceName = 'shirudo' AND EventName = 'shirudo.keepalive'ORDER BY Timestamp DESCLIMIT 10;- A target sends a keepalive every few seconds, so each target shows up- within a minute of the restart.+ ``Body`` holds the keepalive body, the JSON string the target's TPM+ quoted, and the queries read its keys with ``JSONExtract`` and its+ kin. :doc:`/reference/cli/status` lists the keys. A target sends a+ keepalive every minute, so each target shows up within a minute or+ two of the restart.#. Show the last verdict of every target and when it last reported:.. code-block:: sqlSELECT ResourceAttributes['host.name'] AS host,- argMax(LogAttributes['shirudo.status'], Timestamp) AS status,+ argMax(JSONExtractString(Body, 'verdict'), Timestamp) AS verdict,max(Timestamp) AS last_seenFROM shirudo.otel_logsWHERE ServiceName = 'shirudo' AND EventName = 'shirudo.keepalive'@@ -113,7 +116,7 @@ Check the dataORDER BY last_seen;A target at the top whose ``last_seen`` falls behind has stopped- sending, and a ``status`` other than ``ok`` needs a look, as+ sending, and a ``verdict`` other than ``ok`` needs a look, as:doc:`/operate/run/telemetry` describes under what to alert on.#. Read the map snapshots of one upatch:@@ -140,9 +143,10 @@ from Grafana with its ClickHouse data source or from any tool that canrun SQL. :doc:`/operate/run/telemetry` explains each signal under whatto alert on.-#. Find targets that stopped sending keepalives. Two minutes covers+#. Find targets that stopped sending keepalives. Five minutes coversseveral keepalive intervals and the 30 seconds a keepalive may wait- for the config operation lock:+ for the config operation lock; a target whose tree syncs run for+ longer needs a longer threshold:.. code-block:: sql@@ -151,7 +155,7 @@ to alert on.FROM shirudo.otel_logsWHERE ServiceName = 'shirudo' AND EventName = 'shirudo.keepalive'GROUP BY host- HAVING last_seen < now() - INTERVAL 2 MINUTE;+ HAVING last_seen < now() - INTERVAL 5 MINUTE;#. Find targets that reported a verdict other than ``ok`` in the lastfive minutes:@@ -159,13 +163,13 @@ to alert on... code-block:: sqlSELECT ResourceAttributes['host.name'] AS host,- LogAttributes['shirudo.status'] AS status,+ JSONExtractString(Body, 'verdict') AS verdict,max(Timestamp) AS last_seenFROM shirudo.otel_logsWHERE ServiceName = 'shirudo' AND EventName = 'shirudo.keepalive'AND Timestamp > now() - INTERVAL 5 MINUTE- AND LogAttributes['shirudo.status'] != 'ok'- GROUP BY host, status;+ AND verdict != 'ok'+ GROUP BY host, verdict;#. Find targets whose guards refused operations in the last tenminutes:@@ -173,20 +177,20 @@ to alert on... code-block:: sqlSELECT ResourceAttributes['host.name'] AS host,- argMax(toInt64OrZero(LogAttributes['shirudo.tamper_attempts']), Timestamp)- - argMin(toInt64OrZero(LogAttributes['shirudo.tamper_attempts']), Timestamp)+ JSONExtractString(Body, 'boot_id') AS boot,+ max(arraySum(JSONExtract(Body, 'tamper', 'Array(UInt64)')))+ - min(arraySum(JSONExtract(Body, 'tamper', 'Array(UInt64)')))AS new_attemptsFROM shirudo.otel_logsWHERE ServiceName = 'shirudo' AND EventName = 'shirudo.keepalive'AND Timestamp > now() - INTERVAL 10 MINUTE- GROUP BY host+ GROUP BY host, bootHAVING new_attempts > 0;- The query subtracts the earliest count in the window from the latest.- The counters start at zero each boot, so a target that rebooted in- the window yields a negative difference and no row, where the- difference between the largest and smallest count would report every- reboot.+ ``tamper`` lists every counter, so their sum is the number of+ refusals since boot. The counters only grow within a boot and start+ at zero at the next, so the query compares the keepalives of one boot,+ ``boot_id``, and a reboot in the window reports nothing.Next steps----------diff --git a/Documentation/operate/integrations/elasticsearch.rst b/Documentation/operate/integrations/elasticsearch.rstindex 157b7b7c..97265e67 100644--- a/Documentation/operate/integrations/elasticsearch.rst+++ b/Documentation/operate/integrations/elasticsearch.rst@@ -26,8 +26,8 @@ Before you beginbuilt with Go 1.24 or later. The contrib distribution includes theElasticsearch exporter; Go 1.24 offers the hybrid key exchange thetargets require.-- Elasticsearch 9.4 or later, whose ES|QL has the ``FIRST`` and ``LAST``- functions that the alert on tamper attempts uses, and Kibana.+- Elasticsearch 9.4 or later, whose ES|QL has the ``LAST`` function+ that the query of the last verdict uses, and Kibana.The exporter's log and metric support is beta.@@ -87,9 +87,15 @@ The exporter writes in its default ``otel`` mapping mode: log records goto the data stream ``logs-generic.otel-default`` and metrics to``metrics-generic.otel-default``. A document keeps the OTLP layout, withthe attributes under ``attributes``, the resource attributes under-``resource.attributes`` and a structured body under ``body.structured``.-Elasticsearch's OpenTelemetry templates also offer each attribute under-its own name, so ``host.name`` and ``shirudo.status`` work in queries.+``resource.attributes``, a string body under ``body.text`` and a+structured body under ``body.structured``. Elasticsearch's OpenTelemetry+templates also offer each attribute under its own name, so ``host.name``+works in queries.++A keepalive's body is a string, the JSON object the target's TPM quoted,+so it lands in ``body.text``. The queries below take the keys they need+out of it with ``GROK``; :doc:`/reference/cli/status` lists the keys,+which always come in the same order.Check the data--------------@@ -100,12 +106,13 @@ Check the dataFROM logs-generic.otel-default| WHERE event_name == "shirudo.keepalive"+ | GROK body.text "\"verdict\":\"%{DATA:verdict}\""| SORT @timestamp DESC- | KEEP @timestamp, host.name, shirudo.status, shirudo.tamper_attempts+ | KEEP @timestamp, host.name, verdict, body.text| LIMIT 10- A target sends a keepalive every few seconds, so each target shows up- within a minute of the restart.+ A target sends a keepalive every minute, so each target shows up+ within a minute or two of the restart.#. Show the last verdict of every target and when it last reported:@@ -113,7 +120,8 @@ Check the dataFROM logs-generic.otel-default| WHERE event_name == "shirudo.keepalive"- | STATS status = LAST(shirudo.status, @timestamp),+ | GROK body.text "\"verdict\":\"%{DATA:verdict}\""+ | STATS verdict = LAST(verdict, @timestamp),last_seen = MAX(@timestamp) BY host.name| SORT last_seen@@ -142,16 +150,17 @@ rows. In Elastic Security, use the query in a detection rule of typeES|QL instead. :doc:`/operate/run/telemetry` explains each signal underwhat to alert on.-#. Find targets that stopped sending keepalives. Two minutes covers+#. Find targets that stopped sending keepalives. Five minutes coversseveral keepalive intervals and the 30 seconds a keepalive may wait- for the config operation lock:+ for the config operation lock; a target whose tree syncs run for+ longer needs a longer threshold:.. code-block:: textFROM logs-generic.otel-default| WHERE event_name == "shirudo.keepalive" AND @timestamp > NOW() - 1 day| STATS last_seen = MAX(@timestamp) BY host.name- | WHERE last_seen < NOW() - 2 minutes+ | WHERE last_seen < NOW() - 5 minutesA target silent for longer than a day drops out of the query.@@ -162,8 +171,9 @@ what to alert on.FROM logs-generic.otel-default| WHERE event_name == "shirudo.keepalive" AND @timestamp > NOW() - 5 minutes- AND shirudo.status != "ok"- | STATS reports = COUNT(*) BY host.name, shirudo.status+ | GROK body.text "\"verdict\":\"%{DATA:verdict}\""+ | WHERE verdict != "ok"+ | STATS reports = COUNT(*) BY host.name, verdict#. Find targets whose guards refused operations in the last tenminutes:@@ -172,15 +182,15 @@ what to alert on.FROM logs-generic.otel-default| WHERE event_name == "shirudo.keepalive" AND @timestamp > NOW() - 10 minutes- AND shirudo.tamper_attempts IS NOT NULL- | STATS first_count = FIRST(shirudo.tamper_attempts, @timestamp),- last_count = LAST(shirudo.tamper_attempts, @timestamp) BY host.name- | EVAL new_attempts = last_count - first_count- | WHERE new_attempts > 0-- The query subtracts the earliest count in the window from the latest.- The counters start at zero each boot, so a reboot in the window gives- a negative difference and no row.+ | GROK body.text "\"boot_id\":\"%{DATA:boot_id}\""+ | GROK body.text "\"tamper\":%{DATA:tamper},\"tree_id\""+ | STATS counts = COUNT_DISTINCT(tamper) BY host.name, boot_id+ | WHERE counts > 1++ ``tamper`` lists every counter since boot. The counters only grow+ within a boot and start at zero at the next, so more than one list in+ the keepalives of one ``boot_id`` means a counter rose, and a reboot+ in the window reports nothing.Next steps----------diff --git a/Documentation/operate/integrations/grafana.rst b/Documentation/operate/integrations/grafana.rstindex c3a1661c..ef88f144 100644--- a/Documentation/operate/integrations/grafana.rst+++ b/Documentation/operate/integrations/grafana.rst@@ -48,21 +48,13 @@ Set up Loki and Prometheus- host.nameLoki 3 enables structured metadata by default; an older configuration- may turn it off. A keepalive carries the target's kernel- configuration, a few hundred kilobytes for a distribution kernel,- which can exceed Loki's default limit of 256 KB; Loki then refuses it- and the collector drops it. 4 MB is the largest request a target sends,+ may turn it off. A keepalive is about a kilobyte, but a map snapshot+ can exceed Loki's default limit of 256 KB; Loki then refuses it and+ the collector drops it. 4 MB is the largest request a target sends,``map_export.otlp_max_bytes`` by default, so every record fits.Without the label, every target writes to the one stream``{service_name="shirudo"}`` and shares its rate limit.- With a distribution kernel, every target sends about 60 KB a second- in keepalives, and Loki accepts 4 MB a second per tenant by default.- For a fleet of more than a few dozen targets, raise- ``ingestion_rate_mb`` and ``ingestion_burst_size_mb``, or drop the- kernel configuration at the collector as- :doc:`/operate/run/telemetry` shows.-#. Start Prometheus with ``--web.enable-otlp-receiver``, and in``prometheus.yml`` promote the target's host name to a label and acceptsamples that arrive late:@@ -112,19 +104,21 @@ Check the data.. code-block:: text- {service_name="shirudo"} | shirudo_status != "" | shirudo_status != "ok"+ {service_name="shirudo"} |= `"schema":"shirudo.keepalive/1"` | json verdict="verdict" | verdict != "ok"Loki turns ``service.name`` and ``host.name`` into the labels``service_name`` and ``host_name`` and stores the other attributes as- structured metadata, with dots turned into underscores:- ``shirudo.status`` becomes ``shirudo_status``. Only keepalives carry- ``shirudo.status``.+ structured metadata, with dots turned into underscores. A+ keepalive's body is a string, the JSON object the target's TPM+ quoted, and becomes the log line: the line filter keeps the+ keepalives and ``json`` takes keys out of them.+ :doc:`/reference/cli/status` lists the keys.#. List the keepalives of one target:.. code-block:: text- {service_name="shirudo", host_name="<target>"} | shirudo_status != ""+ {service_name="shirudo", host_name="<target>"} |= `"schema":"shirudo.keepalive/1"`#. Read the map snapshots of one upatch:@@ -158,28 +152,31 @@ on.rules:- alert: ShirudoTargetSilentexpr: |- sum by (host_name) (count_over_time({service_name="shirudo"} | shirudo_status != "" [1d]))+ sum by (host_name) (count_over_time({service_name="shirudo"} |= `"schema":"shirudo.keepalive/1"` [1d]))unless- sum by (host_name) (count_over_time({service_name="shirudo"} | shirudo_status != "" [2m]))+ sum by (host_name) (count_over_time({service_name="shirudo"} |= `"schema":"shirudo.keepalive/1"` [5m]))- alert: ShirudoTargetNotOkexpr: |- sum by (host_name) (count_over_time({service_name="shirudo"} | shirudo_status != "" | shirudo_status != "ok" [5m])) > 0+ sum by (host_name) (count_over_time({service_name="shirudo"} |= `"schema":"shirudo.keepalive/1"` | json verdict="verdict" | verdict != "ok" [5m])) > 0- alert: ShirudoTamperAttemptsexpr: |- last_over_time({service_name="shirudo"} | shirudo_tamper_attempts != "" | unwrap shirudo_tamper_attempts [10m]) by (host_name)- -- first_over_time({service_name="shirudo"} | shirudo_tamper_attempts != "" | unwrap shirudo_tamper_attempts [10m]) by (host_name)- > 0+ count by (host_name, boot_id) (+ sum by (host_name, boot_id, tamper) (+ count_over_time({service_name="shirudo"} |= `"schema":"shirudo.keepalive/1"` | json boot_id="boot_id" | regexp `"tamper":(?P<tamper>\[[^\]]*\]|null)` [10m])+ )+ ) > 1``ShirudoTargetSilent`` fires for a target that sent keepalives in- the last day but none in the last two minutes, which covers several+ the last day but none in the last five minutes, which covers severalkeepalive intervals and the 30 seconds a keepalive may wait for the- config operation lock. A target silent for longer than a day drops- out of the rule. ``ShirudoTargetNotOk`` fires for a verdict other- than ``ok`` in the last five minutes. ``ShirudoTamperAttempts``- subtracts the earliest refusal count in ten minutes from the latest.- The counters start at zero each boot, so a reboot in the window gives- a negative difference and no alert.+ config operation lock; a target whose tree syncs run for longer needs+ a longer window. A target silent for longer than a day drops out of+ the rule. ``ShirudoTargetNotOk`` fires for a verdict other than+ ``ok`` in the last five minutes. ``ShirudoTamperAttempts`` counts the+ different lists of counters, ``tamper``, in the keepalives of one+ boot in ten minutes. The counters only grow within a boot and start+ at zero at the next, so more than one list means a counter rose, and+ a reboot in the window gives no alert.#. Point the ruler at the directory and at your Alertmanager in Loki'sconfiguration:diff --git a/Documentation/operate/integrations/splunk.rst b/Documentation/operate/integrations/splunk.rstindex 76290ffa..7105b276 100644--- a/Documentation/operate/integrations/splunk.rst+++ b/Documentation/operate/integrations/splunk.rst@@ -69,9 +69,11 @@ Set up the exporterThe exporter takes each event's host from the ``host.name`` resourceattribute, so every event carries the name of the target that sentit. The record's body becomes the event, and its attributes become- indexed fields under their own names, ``shirudo.status`` and- ``shirudo.tamper_attempts`` among them, next to ``otel.log.name``- for the event name.+ indexed fields under their own names, next to ``otel.log.name`` for+ the event name. A keepalive's body is a string, the JSON object the+ target's TPM quoted, so the event is that text, and the searches+ below take the keys they need out of it with ``rex``;+ :doc:`/reference/cli/status` lists the keys.#. Restart the collector.@@ -84,8 +86,8 @@ Check the dataindex=shirudo sourcetype=shirudo host=<target>- A target sends a keepalive every few seconds, so each target shows up- within a minute of the restart.+ A target sends a keepalive every minute, so each target shows up+ within a minute or two of the restart.#. List when each target last reported:@@ -107,15 +109,16 @@ the number of results is greater than zero.:doc:`/operate/run/telemetry` explains each signal under what to alerton.-#. Find targets that stopped sending. Two minutes covers several+#. Find targets that stopped sending. Five minutes covers severalkeepalive intervals and the 30 seconds a keepalive may wait for the- config operation lock:+ config operation lock; a target whose tree syncs run for longer needs+ a longer threshold:.. code-block:: text| tstats latest(_time) AS last_seenWHERE index=shirudo sourcetype=shirudo earliest=-1d BY host- | where last_seen < relative_time(now(), "-2m")+ | where last_seen < relative_time(now(), "-5m")A target silent for longer than a day drops out of the search.@@ -124,26 +127,26 @@ on... code-block:: text- index=shirudo sourcetype=shirudo shirudo.status!=ok earliest=-5m- | stats count AS reports BY host, shirudo.status-- ``!=`` matches only events that carry the field, so map snapshots- do not match.+ index=shirudo sourcetype=shirudo otel.log.name=shirudo.keepalive earliest=-5m+ | rex "\"verdict\":\"(?<verdict>[^\"]+)\""+ | where verdict != "ok"+ | stats count AS reports BY host, verdict#. Find targets whose guards refused operations in the last tenminutes:.. code-block:: text- index=shirudo sourcetype=shirudo shirudo.tamper_attempts=* earliest=-10m- | stats earliest(shirudo.tamper_attempts) AS first_count,- latest(shirudo.tamper_attempts) AS last_count BY host- | eval new_attempts = last_count - first_count- | where new_attempts > 0+ index=shirudo sourcetype=shirudo otel.log.name=shirudo.keepalive earliest=-10m+ | rex "\"boot_id\":\"(?<boot_id>[^\"]+)\""+ | rex "\"tamper\":(?<tamper>\[[^\]]*\]|null)"+ | stats dc(tamper) AS counts BY host, boot_id+ | where counts > 1- The search subtracts the earliest count in the window from the- latest. The counters start at zero each boot, so a reboot in the- window gives a negative difference and no row.+ ``tamper`` lists every counter since boot. The counters only grow+ within a boot and start at zero at the next, so more than one list in+ the keepalives of one ``boot_id`` means a counter rose, and a reboot+ in the window reports nothing.Next steps----------diff --git a/Documentation/operate/plan/overhead.rst b/Documentation/operate/plan/overhead.rstindex a5b9da60..7ac30dd0 100644--- a/Documentation/operate/plan/overhead.rst+++ b/Documentation/operate/plan/overhead.rst@@ -152,6 +152,7 @@ until it exits. The units set ``LimitMEMLOCK=infinity`` for this, see- 20.5 MiB- 72 ms* - ``shirudo status --otel --include-system``, the keepalive timer+ before it quoted its body- 20.5 MiB- 72 ms* - ``shirudo upatch map --all``, the map export timer, no upatch@@ -292,9 +293,9 @@ TPM attestation key, see `TPM commands`_.- CPU per run- Runs per minute* - ``shirudo-keepalive.service``- - 5 s after the previous run ends- - 17.9 ms- - 11.8+ - 60 s after the previous run ends+ - 17.9 ms before it quoted its body+ - 1* - ``shirudo-map-export.service``- 5 s after the previous run ends- 14.5 ms with no upatch loaded@@ -309,8 +310,11 @@ TPM attestation key, see `TPM commands`_.- 1Together they used 0.43 s of CPU time per minute in the test VM, 0.71 %-of one vCPU, in about 27 process starts. Figure 3 shows the keepalive-and map export timers taking most of it.+of one vCPU, in about 27 process starts, when the keepalive ran every+5 seconds and sent no quote. Figure 3 shows that measurement, with the+keepalive and map export timers taking most of it. The keepalive now+runs once a minute, which leaves it one run of the 11.8 the figure+counts, plus the quote below, which the measurement does not include... figure:: /images/operate-timer-cpu.svg:alt: Per minute, keepalive uses 212 ms of CPU time, map export 172 ms,@@ -340,6 +344,10 @@ TPM commandsconfig PCR.* - ``status``- Adds reads of the measurement register's NV index.+ * - ``status --otel``+ - Adds a second attestation key, created with+ ``TPM2_CreatePrimary`` for the quote and flushed after it, and+ ``TPM2_Quote`` of the keepalive body.* - ``upatch load``, ``upatch unload``- One register extension: about 20 commands, among them a newRSA-3072 primary key (the NV writer key), a new attestation key, a@@ -356,13 +364,20 @@ TPM commandsregister and the endorsement key.With the default timers an idle target creates its attestation key about-27 times per minute. The register is an orderly NV index, so an+17 times per minute, twice in each keepalive. The register is an orderly NV index, so anextension updates it in TPM RAM rather than writing NV memory each time.``init`` defines the index again at every boot. In the test VM, withswtpm, the extension took 0.44 s of a 0.50 s load, binding the registerat boot 0.56 s and ``attest`` 0.46 s.:doc:`/concepts/background/tpm` explains the objects involved.+The keepalive's ``TPM2_CreatePrimary`` derives the P-256 key from the+endorsement seed at every run. A firmware or discrete TPM can take+hundreds of milliseconds for it, which the keepalive spends once a+minute. Keeping the key under a persistent handle would avoid it, at the+price of TPM state shirudo does not keep today;+:doc:`/internals/design-decisions` records the choice.+Network~~~~~~~diff --git a/Documentation/operate/plan/scalability.rst b/Documentation/operate/plan/scalability.rstindex cb3d9285..4c6bd78f 100644--- a/Documentation/operate/plan/scalability.rst+++ b/Documentation/operate/plan/scalability.rst@@ -100,10 +100,11 @@ Staged rolloutsCollectors~~~~~~~~~~-With an endpoint configured, every target sends one keepalive and one-request per map of every loaded upatch every 5 seconds after the previous-run ends, about 12 a minute each. A collector serves N targets with M-exported maps each about 12 × N × (M + 1) requests a minute. A request+With an endpoint configured, every target sends one keepalive a minute+after the previous one ends, and one request per map of every loaded+upatch 5 seconds after the previous export ends, about 12 a minute. A+collector serves N targets with M exported maps each about+N × (12 × M + 1) requests a minute. A requestwaits 10 seconds by default and is retried 3 times. See:doc:`/operate/run/telemetry`.diff --git a/Documentation/operate/run/read-status.rst b/Documentation/operate/run/read-status.rstindex 159227fe..f2f2b100 100644--- a/Documentation/operate/run/read-status.rst+++ b/Documentation/operate/run/read-status.rst@@ -768,15 +768,17 @@ Monitor with ``status --json``------------------------------``status --json`` prints the same data as one JSON document. The-keepalive timer sends it to your collector, see-:doc:`/operate/run/telemetry`.+keepalive timer sends a compact record of it, the keepalive body that+``status --keepalive`` prints, to your collector with the TPM's quote,+see :doc:`/operate/run/telemetry`... warning::``shirudo status`` exits 0 whatever the verdict, ``tampered``included, unless you pass ``--check``, which exits 1 on ``tampered``and 0 on every other verdict. It exits 1 also when it cannot load its- configuration, runs out of memory or fails to send a keepalive, and 2+ configuration, runs out of memory, or cannot quote or send a+ keepalive, and 2on a usage error or an invalid ``map_export`` setting. Alert on the``status`` field of the JSON document, not on the exit code.diff --git a/Documentation/operate/run/telemetry.rst b/Documentation/operate/run/telemetry.rstindex ac0ae906..d76f6056 100644--- a/Documentation/operate/run/telemetry.rst+++ b/Documentation/operate/run/telemetry.rst@@ -15,9 +15,12 @@ systemd timers start. Nothing connects to the target. This page showshow to choose the destination, set up the collector, check the pipelineand decide what to alert on.-Telemetry is the target's own account of itself. It carries no proof of-origin, so it tells you where to look, not what is true. Evidence that a-target cannot forge comes from the TPM, through :doc:`/operate/run/attest`.+Telemetry is the target's own account of itself, so it tells you where+to look, not what is true. The keepalive carries a quote by the target's+TPM attestation key, which shows that its body is unchanged since that+key signed it, but not that the key lives in a genuine TPM. Map+snapshots carry no proof of origin at all. Evidence that a target cannot+forge comes from the TPM, through :doc:`/operate/run/attest`.What a target sends-------------------@@ -30,17 +33,18 @@ What a target sends- Runs- Sends* - ``shirudo-keepalive.timer``- - ``shirudo status --otel --include-system``- - One log record, ``shirudo.keepalive``, when an OTLP endpoint is- configured. Nothing otherwise.+ - ``shirudo status --otel``+ - One log record, ``shirudo.keepalive``: the keepalive body and its+ TPM quote, when an OTLP endpoint is configured. Nothing otherwise.* - ``shirudo-map-export.timer``- ``shirudo upatch map --all``- One record per pinned map to every destination the config names:JSON lines, OTLP, or both. With no destination, the dump goes tothe journal.-Both timers start their service 5 seconds after boot and again 5 seconds-after each run ends. ``shirudo-map-export.service`` runs only while+Both timers start their service 5 seconds after boot. The keepalive+timer starts it again 60 seconds after each run ends, the map-export+timer 5 seconds after. ``shirudo-map-export.service`` runs only while``/run/shirudo/bpffs/lsm_link`` exists.A keepalive and a ``bpm tree sync`` stall each other rather than run at@@ -54,12 +58,14 @@ node's keepalives, which a backend's threshold for a stale node mustallow for. See :doc:`/reference/systemd-units`.The keepalive record has the event name ``shirudo.keepalive``. Its body-is the ``shirudo status --json`` document with the system section, and-its attributes are ``shirudo.status`` (the verdict),-``shirudo.version_id`` and ``shirudo.tamper_attempts`` (the refusals the-guards counted this boot). The system section includes the kernel-configuration, so a keepalive from a distribution kernel is a few hundred-kilobytes. Its severity follows the verdict:+is a string, the keepalive body that ``shirudo status --keepalive``+prints: one compact JSON object of about a kilobyte with the verdict,+the conditions, the tamper counters, the build, the config and image,+the tree the target follows and the upatches it has loaded+(:doc:`/reference/cli/status`). Its one attribute, ``shirudo.quote``, is+the TPM quote of the SHA-256 of the body by the attestation key of+``shirudo attest``. A target whose TPM does not answer sends no+keepalive. Its severity follows the verdict:.. list-table:::header-rows: 1@@ -282,33 +288,9 @@ reboot.Grafana and Splunk. A collector built with Go 1.24 or later offers``X25519MLKEM768`` by default.-#. Optionally, drop the kernel configuration from the keepalives before- the collector exports them. It makes up most of a keepalive, and- every keepalive repeats it:-- .. code-block:: yaml-- processors:- transform/drop-kernel-config:- log_statements:- - context: log- conditions:- - log.event_name == "shirudo.keepalive"- statements:- - delete_key(log.body["system"], "kernel_config")-- service:- pipelines:- logs:- receivers: [otlp]- processors: [transform/drop-kernel-config]- exporters: [debug]-- The ``transform`` processor is part of the contrib distribution,- ``otelcol-contrib``. ``kernel_release`` and ``kernel_build_id`` stay- in the system section and still name the kernel.--#. Restart the collector.+#. Restart the collector. Keep the keepalive body a string on its way+ to storage: a processor that parses it into a structure or rewrites+ it breaks the quote.Any HTTPS server that accepts those two requests works as a destination.It answers ``200`` to accept. A ``200`` whose ``partialSuccess`` reports@@ -319,19 +301,28 @@ connection errors and the statuses ``429``, ``502``, ``503`` andCheck the pipeline-------------------#. Send one keepalive by hand and print it:+#. Print the keepalive body the target reports, without quoting or+ sending it:++ .. code-block:: console++ target# shirudo status --keepalive++#. Send one keepalive by hand:.. code-block:: console- target# shirudo status --otel --include-system --json+ target# shirudo status --otel- The command prints the status document and sends it. ``--otel``- without ``--json`` prints nothing. When the send fails, the command- prints ``status: OTEL export failed: <reason>`` and exits 1. When no- endpoint is configured, it sends nothing and exits 0.+ The command prints nothing. When no TPM answers or the quote fails,+ it prints ``status: quote the keepalive: <reason>; nothing is sent``+ and exits 1. When the send fails, it prints ``status: send the+ keepalive: <reason>`` and exits 1. When no endpoint is configured, it+ sends nothing and exits 0.#. Check that the collector printed a record with the event name- ``shirudo.keepalive`` and the attribute ``shirudo.status``.+ ``shirudo.keepalive``, a ``stringValue`` body and the one attribute+ ``shirudo.quote``.#. List the maps the loaded upatches pin:@@ -392,9 +383,11 @@ decoder to build the metric and prints ``upatch map: OTLP exportWhat to alert on-----------------The keepalive body is the ``shirudo status --json`` document.-:doc:`/operate/run/read-status` explains each field and-:doc:`/reference/formats/status-json` lists them.+The keys below are those of the keepalive body,+:doc:`/reference/cli/status` lists them and+:doc:`/operate/run/read-status` explains what each condition and verdict+means. What only the full report carries, such as the size of the+eventlog, is read with ``shirudo status --json`` on the target... list-table:::header-rows: 1@@ -408,54 +401,58 @@ The keepalive body is the ``shirudo status --json`` document.another ``shirudo`` command holds the config operation lock formore than 30 seconds, during a long package download forexample.- * - ``shirudo.status`` other than ``ok``+ * - ``verdict`` other than ``ok``- Read :doc:`/operate/run/read-status` for each verdict.- * - A condition with ``status`` ``ALERT``+ ``reboot-pending`` is a config activation that waits for a+ reboot; every command except ``status`` and ``image status`` is+ refused until then.+ * - A pair of ``cond`` at ``11``, ``ALERT``- ``LsmAttached``, ``KeyringSealed``, ``ChainIntact``,``UpatchesMeasured`` or ``ConfigActive`` found tampering or lost- enforcement.- * - ``XdpCovered`` with ``status`` ``WARN`` in several keepalives+ enforcement. ``ChainIntact`` at ``ALERT`` is a register the+ eventlog does not explain; handle it as in+ :doc:`/operate/troubleshoot/incident-tampered`.+ * - ``XdpCovered``, the seventh pair of ``cond``, at ``10``, ``WARN``,+ in several keepalives- A device an XDP upatch selects runs without it: its driverrefuses the program or its XDP was turned off. Each reconcilepass retries it at a cost to the target until the device changesor the upatch is unloaded. Alert on it, and end it as:doc:`/operate/run/read-status` describes.- * - ``shirudo.tamper_attempts`` rises+ * - A counter of ``tamper`` rises- Something on the target tried an operation the guards refused.The counters start at zero each boot. See:doc:`/security/tamper-counters`.- * - ``config.activation_pending`` is ``true``- - A config activation waits for a reboot. Every command except- ``status`` and ``image status`` is refused until then.- * - ``tpm.chain_matches_eventlog`` is ``false``- - The register holds a value the eventlog does not explain. Handle- it as in :doc:`/operate/troubleshoot/incident-tampered`.- * - ``tpm.register_rebound`` is ``true``+ * - Bit 0 of ``flags``, ``register_rebound``- The register was bound twice in one TPM reset.- * - ``tpm.bound_in`` is not ``initrd``+ * - Bit 1 of ``flags``, ``bound_late``- ``init`` bound the register from the root file system, not fromthe initrd.- * - ``assets.eventlog_bytes`` nears 8388608- - The eventlog approaches the size that readers refuse. See- :doc:`/operate/maintain/backup-recovery`.+ * - Bit 2 of ``flags``, ``tree_log_mismatch``+ - The tree eventlog or the outcomes record does not agree with the+ tree state.* - ``version_id`` is not the build you deployed- The target runs another shirudo build.Limits-------- Telemetry has no proof of origin. Root on a target, or anyone who can- reach the collector with valid credentials, can send records in a- target's name. Use :doc:`/operate/run/attest` for evidence.+- A map snapshot has no proof of origin. Root on a target, or anyone who+ can reach the collector with valid credentials, can send records in a+ target's name. A keepalive's quote ties its body to an attestation+ key, but a key in software can sign a quote too, so a backend that+ has not tied the key to the target's TPM treats the target as+ untrusted. Use :doc:`/operate/run/attest` for evidence.- While the config cannot be verified, ``status`` uses only the runtimeimage's settings and the environment. While an activation is pending,it uses the pending config's settings only when that config is the onemounted. To keep keepalives arriving in those states, also set``OTEL_EXPORTER_OTLP_ENDPOINT`` in ``/etc/shirudo/map-export.env``.The map export is refused in those states.-- The keepalive interval is 5 seconds after the previous run ends, not a- fixed schedule. Size the alert for a missing keepalive to several- intervals plus the 30-second lock wait.+- The keepalive interval is 60 seconds after the previous run ends, not+ a fixed schedule. Size the alert for a missing keepalive to several+ intervals plus the 30-second lock wait, and to the longest tree sync+ your targets run.Next steps----------diff --git a/Documentation/reference/cheat-sheet.rst b/Documentation/reference/cheat-sheet.rstindex 21583fac..e94abcda 100644--- a/Documentation/reference/cheat-sheet.rst+++ b/Documentation/reference/cheat-sheet.rst@@ -406,12 +406,14 @@ Export every map to the configured destinations, astarget# shirudo upatch map --all-Send a keepalive and print it with :doc:`cli/status`. Nothing is sent-without a configured endpoint:+Print the keepalive body, then quote it and send it, with+:doc:`cli/status`. Nothing is sent without a configured endpoint or a+TPM that quotes:.. code-block:: console- target# shirudo status --otel --include-system --json+ target# shirudo status --keepalive+ target# shirudo status --otelDeveloping shirudo------------------diff --git a/Documentation/reference/cli/status.rst b/Documentation/reference/cli/status.rstindex 402bec4c..f5a9208a 100644--- a/Documentation/reference/cli/status.rst+++ b/Documentation/reference/cli/status.rst@@ -9,7 +9,8 @@ shirudo status==============Report the local readiness and state of this host, and optionally send the-report as an OTLP keepalive or print the keepalive body.+keepalive, the status record the TPM quotes, as an OTLP log, or print+its body.Runs on: any host, and on a target as root with the runtime binary. It is theonly command that runs while a config activation is pending or cannot be@@ -78,18 +79,27 @@ key that holds each one, the TPM measurement state and the assets undersections that stayed folded. :doc:`/operate/run/read-status` explainseach field and :doc:`/reference/formats/status-json` the JSON document.-With ``--otel``, ``status`` builds the JSON report and sends it as one-OTLP log record named ``shirudo.keepalive``, only when an endpoint is-configured: ``map_export.otel_endpoint``, else+With ``--otel``, ``status`` sends the keepalive, only when an endpoint+is configured: ``map_export.otel_endpoint``, else``OTEL_EXPORTER_OTLP_LOGS_ENDPOINT``, else-``OTEL_EXPORTER_OTLP_ENDPOINT``. Without an endpoint it sends nothing and-says nothing, except while a config activation is pending or unverifiable,-when it prints a warning. ``--otel`` alone prints nothing on standard-output. Add ``--json`` to print the document too.+``OTEL_EXPORTER_OTLP_ENDPOINT``. It builds the keepalive body described+below, has the TPM's attestation key quote the SHA-256 of the body, and+sends one OTLP log record named ``shirudo.keepalive`` with the body as a+string and the quote as its one attribute, ``shirudo.quote``+(:doc:`/reference/formats/otlp`). The attestation key is the one+:doc:`attest` uses, created for the quote and flushed after it. When no+TPM answers or the quote fails, ``status`` sends nothing, says why on+standard error and exits 1: a keepalive without a quote is worth nothing+to the backend. Without an endpoint it sends nothing, quotes nothing and+says nothing, except while a config activation is pending or+unverifiable, when it prints a warning. ``--otel`` alone prints nothing+on standard output. Add ``--json`` to print the JSON report too; it is+the full document, not the keepalive body, and ``--include-system`` and+``--include-eventlog`` change only it.With ``--keepalive``, ``status`` prints the keepalive body, the compact-status record a node's TPM is to quote, as one line on standard output.-It neither quotes nor sends it and needs no TPM, so an operator can see+status record a node's TPM quotes, as one line on standard output. It+neither quotes nor sends it and needs no TPM, so an operator can seewhat a node reports. The body has 22 keys in a fixed order: ``schema``(``shirudo.keepalive/1``), ``boot_id``, ``version_id``, ``config_root``,``kernel_release``, ``image_id``, ``image_version``, ``image_root``,@@ -102,6 +112,13 @@ A key that does not apply is ``null``:- the seven tree keys, ``tree_id`` to ``mask``, when the node follows notree or its tree state cannot be read.+``cond`` holds two bits per condition, condition *i* of the order above+at bits ``2i`` and ``2i+1``, ``LsmAttached`` first and ``XdpCovered``+last: ``00`` not evaluated, ``01`` ``OK``, ``10`` ``WARN``, ``11``+``ALERT``. All seven ``OK`` is ``5461``. ``tamper`` lists every counter+of :doc:`/security/tamper-counters`, zeros included, in the order of+that page.+``mask`` holds two bits per operation from ``base_seq + 1`` to the headof the recorded publication, read from the outcomes record of:doc:`/reference/formats/bpm-formats`: ``01`` applied, ``10`` passed@@ -145,7 +162,7 @@ The bits of ``flags``:``status`` holds the config operation lock for its whole run, as everytarget command does, a ``bpm tree sync`` included. It therefore neverreads a tree a sync is changing: while one runs, ``status`` waits up to-30 seconds for the lock and then fails, and no body is printed. A sync+30 seconds for the lock and then fails, and no body is printed or sent. A syncwrites ``pending.json`` before it loads or unloads anything and removesit only after ``state.json`` has the new ``last_seq``, so bit 4 says async stopped in the middle of an operation and the next sync completes@@ -176,7 +193,8 @@ Options* - ``--otel``- none- off- - Send the JSON report as an OTLP keepalive log record.+ - Quote the keepalive body with the TPM and send it as an OTLP log+ record.* - ``--keepalive``- none- off@@ -220,7 +238,8 @@ reads ``.status`` and the conditions from the JSON document.- The report was produced.* - 1- With ``--check``: the verdict is ``tampered``. With ``--otel``:- the configuration cannot be loaded or the OTLP request failed.+ the configuration cannot be loaded, the body cannot be built, no+ TPM answered, the quote failed or the OTLP request failed.With ``--json``: the document does not fit the output buffer.With ``--keepalive``: the body cannot be built. Also an allocationfailure.@@ -236,13 +255,13 @@ Files and environment``/var/lib/shirudo/eventlog``, ``/var/lib/shirudo/keys``, the configcertificate the runtime image's bootstrap names and the configactivation records-- With ``--keepalive``: ``state.json``, ``pending.json``, ``outcomes``,+- With ``--keepalive`` or ``--otel``: ``state.json``, ``pending.json``, ``outcomes``,``tree-eventlog`` and ``status/`` under``/var/lib/shirudo/bpm/upatch-tree``, ``/etc/os-release`` (else``/usr/lib/os-release``), ``/proc/cmdline`` and``/proc/sys/kernel/random/boot_id``-- With ``--otel``: ``map_export.*`` and the ``OTEL_EXPORTER_OTLP_*``- variables (see :doc:`/reference/environment`).+- With ``--otel``: the TPM, ``map_export.*`` and the+ ``OTEL_EXPORTER_OTLP_*`` variables (see :doc:`/reference/environment`).``shirudo-keepalive.service`` reads them from``/etc/shirudo/map-export.env``diff --git a/Documentation/reference/formats/otlp.rst b/Documentation/reference/formats/otlp.rstindex e9c7e64d..bbc1200d 100644--- a/Documentation/reference/formats/otlp.rst+++ b/Documentation/reference/formats/otlp.rst@@ -216,18 +216,56 @@ One log record in ``resourceLogs[0].scopeLogs[0].logRecords``:* - ``eventName``- ``shirudo.keepalive``* - ``body``- - The :doc:`status-json` document as an OTLP value: objects as- ``kvlistValue``, arrays as ``arrayValue``, strings as- ``stringValue``, integers as ``intValue``, other numbers as- ``doubleValue``, booleans as ``boolValue``, ``null`` as an empty- value. The timer adds ``--include-system``.- * - Attribute ``shirudo.status``- - The verdict.- * - Attribute ``shirudo.version_id``- - ``SHIRUDO_VERSION_ID`` of the binary.- * - Attribute ``shirudo.tamper_attempts``- - ``tamper_attempts.total``. Absent when the counters cannot be- read.+ - ``{"stringValue": <body>}``: the keepalive body that ``status+ --keepalive`` prints (:doc:`/reference/cli/status`), the compact+ JSON object as one string, never a ``kvlistValue``. A collector+ may re-encode a structure, and the quote covers these exact+ bytes.+ * - Attribute ``shirudo.quote``+ - The one attribute, a string: the TPM quote of the body, below.++``timeUnixNano`` and the resource attributes are for display only. They+identify nothing and order nothing; the quote does both.++``shirudo.quote`` has three fields in this order, separated by ``;``+with no blanks, each in standard base64 with padding:++.. code-block:: none++ attest=<TPMS_ATTEST>;sig=<TPMT_SIGNATURE>;ak=<TPMT_PUBLIC>++.. list-table::+ :header-rows: 1+ :widths: 14 86++ * - Field+ - Value+ * - ``attest``+ - The ``TPMS_ATTEST`` the TPM signed, without the ``TPM2B`` size: a+ ``TPM2_Quote`` whose qualifying data is the SHA-256 of the body+ bytes and whose PCR selection is one SHA-256 bank with no PCR set.+ Its clock information, ``resetCount`` and ``clock``, orders the+ keepalives of one node.+ * - ``sig``+ - The marshalled ``TPMT_SIGNATURE`` over ``attest``: ECDSA with+ SHA-256.+ * - ``ak``+ - The marshalled ``TPMT_PUBLIC`` of the attestation key, without+ the ``TPM2B`` size: the fixed-template P-256 ECDSA primary under+ the endorsement hierarchy that :doc:`/reference/cli/attest` uses.+ ``000b`` and the SHA-256 of these bytes is the key's name, which+ identifies the node. The quote's signer is the key's qualified+ name under the endorsement hierarchy.++:doc:`/reference/cli/quote-check` checks a quote against its body without+a TPM. An attestation quote always selects a PCR, so it cannot pass as+a keepalive quote. A quote that checks proves that the body is+unchanged since the key signed it, not that the key lives in a TPM.++When no TPM answers or the quote fails, ``status --otel`` sends nothing.+A body that JSON cannot carry unchanged, one with a NUL byte or+malformed UTF-8, is not sent either; the body ``status`` builds is never+one.The keepalive uses ``map_export.otel_endpoint``,``map_export.tenant_id``, ``map_export.otel_insecure``,@@ -440,8 +478,8 @@ Keepalive structure-------------------The keepalive of a target with verdict ``ok``, as the code builds it.-Angle brackets mark values that vary, and the ``body`` values are-shortened to the first entries:+Angle brackets mark values that vary, and the body string is shortened+to its first keys:.. code-block:: json@@ -466,18 +504,10 @@ shortened to the first entries:"severityText": "INFO","eventName": "shirudo.keepalive","body": {- "kvlistValue": {- "values": [- {"key": "schema", "value": {"intValue": "1"}},- {"key": "version_id", "value": {"stringValue": "<version-id>"}},- {"key": "is_target", "value": {"boolValue": true}}- ]- }+ "stringValue": "{\"schema\":\"shirudo.keepalive/1\",\"boot_id\":\"<boot-id>\",\"version_id\":\"<version-id>\",...}"},"attributes": [- {"key": "shirudo.status", "value": {"stringValue": "ok"}},- {"key": "shirudo.version_id", "value": {"stringValue": "<version-id>"}},- {"key": "shirudo.tamper_attempts", "value": {"intValue": "<total>"}}+ {"key": "shirudo.quote", "value": {"stringValue": "attest=<base64>;sig=<base64>;ak=<base64>"}}]}]@@ -492,6 +522,7 @@ Related- :doc:`/operate/run/telemetry`- :doc:`/reference/cli/status`+- :doc:`/reference/cli/quote-check`- :doc:`/reference/cli/upatch-map`- :doc:`/upatches/write/decoders`- :doc:`status-json`diff --git a/Documentation/reference/formats/status-json.rst b/Documentation/reference/formats/status-json.rstindex c34a2ff3..3caa7252 100644--- a/Documentation/reference/formats/status-json.rst+++ b/Documentation/reference/formats/status-json.rst@@ -8,9 +8,10 @@status JSON===========-``shirudo status --json`` prints one JSON object on one line. The same-object is the body of the status keepalive that ``status --otel``-sends, see :doc:`otlp`. Options and exit status are in+``shirudo status --json`` prints one JSON object on one line. The+status keepalive that ``status --otel`` sends carries a smaller record,+the keepalive body that ``status --keepalive`` prints, see :doc:`otlp`.+Options, exit status and the keys of the keepalive body are in:doc:`/reference/cli/status`. How to read a report is in:doc:`/operate/run/read-status`.@@ -698,8 +699,9 @@ Optional blocks``status`` sizes its output buffer from the options, the eventlog sizeand the number of loaded upatches, at most 8 MiB. A document that doesnot fit is not printed: ``status`` writes ``status: json encode failed:-<reason>`` to standard error, nothing to standard output, sends no-keepalive and exits 1.+<reason>`` to standard error, nothing to standard output, and exits 1.+With ``--otel`` the keepalive is sent all the same: it does not carry+this document.Fields to alert on------------------diff --git a/Documentation/reference/systemd-units.rst b/Documentation/reference/systemd-units.rstindex 39225f7e..e3165e70 100644--- a/Documentation/reference/systemd-units.rst+++ b/Documentation/reference/systemd-units.rst@@ -32,7 +32,7 @@ Unitsruntime drop-in- ``sysinit.target``, once per boot* - ``shirudo-keepalive.service``- - ``@bindir@/shirudo status --otel --include-system``+ - ``@bindir@/shirudo status --otel``- ``shirudo-keepalive.timer``* - ``shirudo-xdp-reconcile.service``- ``@bindir@/shirudo upatch reconcile``@@ -180,7 +180,7 @@ shirudo-keepalive.service* - Setting- Value* - ``ExecStart``- - ``@bindir@/shirudo status --otel --include-system``+ - ``@bindir@/shirudo status --otel``* - ``EnvironmentFile``- ``-/etc/shirudo/map-export.env`` (optional)* - ``After``@@ -192,7 +192,9 @@ shirudo-keepalive.serviceThe keepalive is sent only when ``map_export.otel_endpoint``,``OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`` or ``OTEL_EXPORTER_OTLP_ENDPOINT``-names an endpoint. See :doc:`/reference/formats/otlp`.+names an endpoint, and only with its TPM quote: a run whose TPM does not+answer or does not quote fails and sends nothing. See+:doc:`/reference/formats/otlp`.A keepalive and a ``bpm tree sync`` do not run at once. Every targetcommand holds the config operation lock for its whole run, and a sync@@ -330,7 +332,7 @@ Timers* - Timer- Schedule* - ``shirudo-keepalive.timer``- - ``OnBootSec=5s``, ``OnUnitInactiveSec=5s``, ``AccuracySec=1s``+ - ``OnBootSec=5s``, ``OnUnitInactiveSec=60s``, ``AccuracySec=1s``* - ``shirudo-xdp-reconcile.timer``- ``OnBootSec=5s``, ``OnUnitInactiveSec=60s``, ``AccuracySec=1s``* - ``shirudo-map-export.timer``diff --git a/Documentation/security/security-model.rst b/Documentation/security/security-model.rstindex ddb45672..12400e12 100644--- a/Documentation/security/security-model.rst+++ b/Documentation/security/security-model.rst@@ -60,7 +60,8 @@ What shirudo provides* - Attempts leave a trace- Guards count their refusals in a frozen map that ``shirudostatus`` and the keepalive report.- - Some refusals move no counter; telemetry is not authenticated.+ - Some refusals move no counter; telemetry is the target's own+ account.- :ref:`T10 <tm-t10>`, R17* - Delivered content is authentic- Indexes, tree publications and configs are signed; the kerneldiff --git a/Documentation/security/tamper-counters.rst b/Documentation/security/tamper-counters.rstindex 664aabdf..c6e76ca2 100644--- a/Documentation/security/tamper-counters.rst+++ b/Documentation/security/tamper-counters.rst@@ -283,10 +283,10 @@ count and its meaning. It prints ``none`` when every counter is zero,in ``counters``, so a collector's keys stay the same from one record tothe next. The value is ``null`` before ``init`` has pinned the map.-The keepalive, ``shirudo status --otel``, sends the same status as an-OTLP log record and adds the total as the attribute-``shirudo.tamper_attempts``. The attribute is absent when the counters-cannot be read.+The keepalive, ``shirudo status --otel``, carries every counter in the+``tamper`` list of its body, zeros included and in the order of this+page, and the TPM quotes the body. The list is ``null``, and bit 3 of+the body's ``flags`` set, when the counters cannot be read.What a non-zero counter means-----------------------------diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rstindex d29668a4..89eeb4f7 100644--- a/Documentation/security/threat-model.rst+++ b/Documentation/security/threat-model.rst@@ -375,7 +375,10 @@ Assets- The config signature (T11).* - Status, reports and telemetry- The target's output and the collector- - Nothing. They are the target's own account (R17).+ - Nothing for reports and map snapshots. A keepalive's body is quoted+ by the TPM's attestation key, which shows it unchanged on the way+ but not that the key is a TPM's. All of them are the target's own+ account (R17)... _tm-trust-boundaries:@@ -472,8 +475,10 @@ ADV-D, network and registryADV-E, malicious collectorReceives keepalives and map snapshots. It can refuse or delay themand put a short error message into the target's log. It cannot- change enforcement or state. What it receives is unauthenticated- (R17).+ change enforcement or state. A map snapshot it receives is+ unauthenticated; a keepalive it changes no longer matches its quote,+ but it can replay an old one to a backend that does not order them+ by the quote's clock (R17).ADV-F, holder of a compromised or revoked signing keyIts blast radius: every target whose ``.bpf`` keyring holds the key@@ -1162,8 +1167,8 @@ point counts what it lets through: a signal to an authorized task froma task without authority (``SealSignal``, T3). Only thehooks add to it, and no task resets it from userspace. ``shirudostatus`` lists the counters that are not zero with their meaning,-``status --json`` carries them all, and the keepalive carries the total-as the attribute ``shirudo.tamper_attempts``.+``status --json`` carries them all, and so does the keepalive body,+which the TPM quotes, in its ``tamper`` list.A counter is evidence of an attempt, not of a compromise. Somerefusals move no counter: the kernel's signature errors, the guards of@@ -1521,12 +1526,20 @@ R16 Any artifact ever signed loads at any timeway to retire one artifact is to revoke the key that signed it.R17 Telemetry has no proof of origin- Keepalives, map snapshots and the tamper counters they carry are- unsigned and not bound to the TPM. ``host.name`` is the target's- host name, and the credentials come from files root reads.- ``map_export.otel_insecure`` turns certificate verification off.- Root can withhold, drain or forge telemetry. Only ``attest verify``- is evidence.+ Map snapshots are unsigned and not bound to the TPM. A keepalive+ carries a quote of the SHA-256 of its body by the attestation key of+ ``attest``, created for each keepalive, over no PCR, and+ ``shirudo-quote-check`` verifies it without a TPM. A quote that+ checks proves that the body is unchanged since that key signed it,+ and its clock orders the keepalives of one key. It does not prove+ that the key lives in a genuine TPM: only ``attest challenge`` ties+ the key to an endorsement key, and a backend treats every node as+ ``untrusted`` until a future workflow does that. Nor does it vouch+ for the body: root on the target can have the TPM quote a body of+ its own. ``host.name`` is the target's host name, and the+ credentials come from files root reads. ``map_export.otel_insecure``+ turns certificate verification off. Root can withhold, drain or+ forge telemetry. Only ``attest verify`` is evidence.R18 BPF outside the gates``lsm/bpf`` and ``lsm/bpf_prog_load`` admit every call whosediff --git a/Documentation/start/how-it-works.rst b/Documentation/start/how-it-works.rstindex ca120e6d..170ae578 100644--- a/Documentation/start/how-it-works.rst+++ b/Documentation/start/how-it-works.rst@@ -167,14 +167,16 @@ Two more timers send telemetry while upatches run.``shirudo-map-export.timer`` runs ``shirudo upatch map --all``, which readsthe maps of every loaded upatch, runs their serializers and signed Luadecoders, and sends the records to the destinations the config image's-``map_export`` settings name. ``shirudo-keepalive.timer`` runs ``shirudo-status --otel --include-system``, which sends the target's status as an-OTLP log record when an endpoint is configured. Both run five seconds after-the previous run ends.--Telemetry carries no proof of origin. It is the target's own account, and-the TPM-signed evidence of step 7 is the check. :doc:`/operate/run/telemetry`-covers the export settings.+``map_export`` settings name. It runs five seconds after the previous run+ends. ``shirudo-keepalive.timer`` runs ``shirudo status --otel`` a minute+after the previous run ends, which sends the target's status record and+the TPM's quote of it as an OTLP log record when an endpoint is+configured.++Telemetry carries no proof of origin. The quote shows that a keepalive+arrived as the target's attestation key signed it, but the record is+still the target's own account, and the TPM-signed evidence of step 7+is the check. :doc:`/operate/run/telemetry` covers the export settings.Unload------diff --git a/builtin-status.c b/builtin-status.cindex 53af3ab0..474423d5 100644--- a/builtin-status.c+++ b/builtin-status.c@@ -337,7 +337,8 @@ static void print_system_human(const struct sysinfo *si)static const struct help_item status_options[] = {{ "--json", "print the report as one JSON document" },- { "--otel", "send the JSON report as an OTLP keepalive log" },+ { "--otel", "quote the keepalive body with the TPM and send "+ "it as an OTLP log" },{ "--keepalive", "print the keepalive body, unquoted and unsent" },{ "--check", "exit 1 when the verdict is tampered" },{ "--show-full", "print every section, folded or not, and the "@@ -628,27 +629,27 @@ static __u32 keepalive_flags(const struct chain_status *cst, int tamper_rc,/* A tree state that cannot be read is a node that follows no tree. */static noinline_for_stack int-print_keepalive(const struct conditions_input *cin,- const struct chain_status *cst,- const struct tamper_counts *tamper, int tamper_rc,- const char *config_root_hex)+keepalive_body(const struct conditions_input *cin,+ const struct chain_status *cst,+ const struct tamper_counts *tamper, int tamper_rc,+ const char *config_root_hex, char body[KEEPALIVE_BODY_MAX],+ size_t *len){struct condition conds[CONDITIONS_MAX];struct keepalive_input in = {};struct keepalive_view v = {};- char body[KEEPALIVE_BODY_MAX];struct sysinfo_image img;struct tree_state state;struct sysinfo si = {};int state_rc, ret;__u32 flags = 0;- size_t nc, len;+ size_t nc;ret = keepalive_snapshot(&keepalive_ops, &v, &state, &state_rc,&flags);if (ret) {pr_err("status: read the keepalive inputs: %s", strerror(-ret));- return 1;+ return ret;}sysinfo_gather(&si);sysinfo_image_read(&img);@@ -680,13 +681,118 @@ print_keepalive(const struct conditions_input *cin,in.projection_root = state.projection_root;in.mask = v.outcomes_rc ? NULL : v.mask;}- ret = keepalive_emit(&in, body, sizeof(body), &len);- if (ret) {+ ret = keepalive_emit(&in, body, KEEPALIVE_BODY_MAX, len);+ if (ret)pr_err("status: build the keepalive body: %s", strerror(-ret));+ return ret;+}++#define BASE64_SIZE(n) (4 * (((n) + 2) / 3) + 1)+#define KEEPALIVE_QUOTE_MAX (sizeof("attest=;sig=;ak=") + \+ BASE64_SIZE(TPM_ATTEST_MAX) + \+ BASE64_SIZE(TPM_SIGNATURE_MAX) + \+ BASE64_SIZE(TPM_PUBLIC_MAX))++/* attest=<TPMS_ATTEST>;sig=<TPMT_SIGNATURE>;ak=<TPMT_PUBLIC>, in base64. */+static noinline_for_stack int+keepalive_quote_format(const struct tpm_attestation *att,+ const struct tpm_key *ak, char *out, size_t cap)+{+ char attest[BASE64_SIZE(TPM_ATTEST_MAX)];+ char sig[BASE64_SIZE(TPM_SIGNATURE_MAX)];+ char public[BASE64_SIZE(TPM_PUBLIC_MAX)];+ int ret;++ ret = base64_encode(att->attest, att->attest_len, attest,+ sizeof(attest));+ if (!ret)+ ret = base64_encode(att->signature, att->signature_len, sig,+ sizeof(sig));+ if (!ret)+ ret = base64_encode(ak->public, ak->public_len, public,+ sizeof(public));+ if (!ret)+ ret = strsprintf(out, cap, "attest=%s;sig=%s;ak=%s", attest,+ sig, public);+ return min(ret, 0);+}++/*+ * The attestation key quotes the SHA-256 of the body over no PCR, which+ * tells a keepalive quote from one of attest. The key is created for+ * this quote and flushed after it.+ */+static noinline_for_stack int+keepalive_quote(const char *body, size_t len, char *quote, size_t cap)+{+ struct tpm_key ak = { .handle = 0 };+ struct tpm_attestation att = {};+ __u8 digest[CRYPTO_SHA256_LEN];+ struct tpm *tpm = NULL;+ int ret;++ ret = sha256_buffer(body, len, digest);+ if (ret)+ return ret;+ ret = tpm_open(&tpm);+ if (ret)+ return -ENXIO;+ ret = tpm_ak_create(tpm, &ak);+ if (!ret)+ ret = tpm_quote(tpm, &ak, digest, sizeof(digest), 0, &att);+ if (!ret)+ ret = keepalive_quote_format(&att, &ak, quote, cap);+ tpm_key_flush(tpm, &ak);+ tpm_close(tpm);+ return ret;+}++/*+ * One OTLP log: the body as a string and its quote as the one attribute.+ * Without a quote nothing is sent: the backend has no use for a+ * keepalive it cannot check.+ */+static int send_keepalive(const struct otel_opts *opts, const char *verdict,+ const char *body, size_t len)+{+ char quote[KEEPALIVE_QUOTE_MAX];+ const char *severity_text;+ int severity, ret;++ ret = keepalive_quote(body, len, quote, sizeof(quote));+ if (ret) {+ pr_err("status: quote the keepalive: %s; nothing is sent",+ strerror(-ret));+ return ret;+ }+ severity = status_otel_severity(verdict, &severity_text);+ ret = otel_send_log_string(opts, "shirudo.keepalive",+ "shirudo.keepalive", severity,+ severity_text, body, len, "shirudo.quote",+ quote);+ if (ret)+ pr_err("status: send the keepalive: %s", strerror(-ret));+ return ret;+}++/* Prints the body, or with opts quotes it and sends it there. */+static noinline_for_stack int+status_keepalive(const struct conditions_input *cin,+ const struct chain_status *cst,+ const struct tamper_counts *tamper, int tamper_rc,+ const char *config_root_hex, const struct otel_opts *opts)+{+ char body[KEEPALIVE_BODY_MAX];+ size_t len;++ if (keepalive_body(cin, cst, tamper, tamper_rc, config_root_hex, body,+ &len))return 1;+ if (!opts) {+ printf("%s\n", body);+ return 0;}- printf("%s\n", body);- return 0;+ return send_keepalive(opts, status_verdict(cin), body, len) ? 1 : 0;}#define STATUS_SUBJECT_MAX 256@@ -1037,7 +1143,6 @@ static void print_keyring_serials(const struct status_keyring *k)int cmd_status(int argc, const char **argv){- bool json = false;bool json_stdout = false, otel = false, keepalive = false;bool include_system = false, include_eventlog = false;bool show_full = false, check = false;@@ -1072,7 +1177,6 @@ int cmd_status(int argc, const char **argv)int chain_rc = 0, ev_rc = -ENOENT;int match = -1; /* -1 unknown, 0 mismatch, 1 match */int n_ups, i, fd, ret = 0;- const char *otel_status = NULL;bool otel_endpoint_configured = false;char unmeasured_names[UNMEASURED_NAMES] = "";char xdp_tampered_names[UNMEASURED_NAMES] = "";@@ -1126,7 +1230,6 @@ int cmd_status(int argc, const char **argv)usage();return 2;}- json = json_stdout || otel;if (otel) {int err = config_load(&otel_cfg);@@ -1291,10 +1394,15 @@ int cmd_status(int argc, const char **argv)cin.xdp_coverage_rc = xdp_coverage_rc;keyring_cond_input(&cin, &bpf, &dmv);- if (keepalive) {- ret = print_keepalive(&cin, &cst, &tamper, tamper_rc,- config_state ? NULL : config_root_hex);- } else if (json) {+ if (keepalive || (otel && otel_endpoint_configured))+ ret = status_keepalive(&cin, &cst, &tamper, tamper_rc,+ config_state ? NULL : config_root_hex,+ otel ? &otel_opts : NULL);+ if (otel && !otel_endpoint_configured && config_state &&+ config_state != -ENODEV)+ pr_warn("status: no keepalive is sent: with the config activation %s, no export endpoint is known, since a config image is used only when its activation record vouches for it; OTEL_EXPORTER_OTLP_ENDPOINT in /etc/shirudo/map-export.env still names one",+ config_state == -EINPROGRESS ? "pending" : "unverifiable");+ if (json_stdout) {struct json_emit e;/*@@ -1332,9 +1440,7 @@ int cmd_status(int argc, const char **argv)struct condition conds[CONDITIONS_MAX];size_t nc, ci;- otel_status = status_verdict(&cin);- json_kv_string(&e, "status",- otel_status);+ json_kv_string(&e, "status", status_verdict(&cin));status_reason(&cin, reason, sizeof(reason));if (reason[0])json_kv_string(&e, "reason", reason);@@ -1517,40 +1623,9 @@ int cmd_status(int argc, const char **argv)strerror(-e.err));ret = 1;} else {- if (otel && otel_endpoint_configured) {- __s64 refused = tamper_rc == 0 ?- (__s64)tamper.total : -1;- const char *severity_text;- int severity_number;- int err;-- severity_number =- status_otel_severity(otel_status,- &severity_text);- err = otel_send_log_json(&otel_opts,- "shirudo.keepalive",- "shirudo.keepalive",- severity_number,- severity_text,- otel_status,- shirudo_version_id,- refused, json_buf,- strlen(json_buf));- if (err) {- pr_err("status: OTEL export failed: %s",- strerror(-err));- ret = 1;- }- }- if (otel && !otel_endpoint_configured && config_state &&- config_state != -ENODEV)- pr_warn("status: no keepalive is sent: with the config activation %s, no export endpoint is known, since a config image is used only when its activation record vouches for it; OTEL_EXPORTER_OTLP_ENDPOINT in /etc/shirudo/map-export.env still names one",- config_state == -EINPROGRESS ?- "pending" : "unverifiable");- if (json_stdout)- printf("%s\n", json_buf);+ printf("%s\n", json_buf);}- } else {+ } else if (!keepalive && !otel) {struct condition conds[CONDITIONS_MAX];struct upatch_table_row *rows = NULL;bool keyrings_open, tpm_open;diff --git a/infra/aws/packer/scripts/configure-shirudo-initrd.sh b/infra/aws/packer/scripts/configure-shirudo-initrd.shindex 72e136be..7024fa82 100755--- a/infra/aws/packer/scripts/configure-shirudo-initrd.sh+++ b/infra/aws/packer/scripts/configure-shirudo-initrd.sh@@ -82,7 +82,7 @@ donesudo tee /etc/systemd/system/shirudo-keepalive.service.d/runtime.conf >/dev/null <<'EOF'[Service]ExecStart=-ExecStart=/run/shirudo/runtime/usr/bin/shirudo status --otel --include-system+ExecStart=/run/shirudo/runtime/usr/bin/shirudo status --otelEOFsudo tee /etc/systemd/system/shirudo-map-export.service.d/runtime.conf >/dev/null <<'EOF'[Service]diff --git a/systemd/shirudo-keepalive.service.in b/systemd/shirudo-keepalive.service.inindex e4a257ca..75d54b91 100644--- a/systemd/shirudo-keepalive.service.in+++ b/systemd/shirudo-keepalive.service.in@@ -11,4 +11,4 @@ SyslogIdentifier=shirudoLimitMEMLOCK=infinityTimeoutStartSec=2minEnvironmentFile=-/etc/shirudo/map-export.env-ExecStart=@bindir@/shirudo status --otel --include-system+ExecStart=@bindir@/shirudo status --oteldiff --git a/systemd/shirudo-keepalive.timer b/systemd/shirudo-keepalive.timerindex 63b3f883..fc7a8226 100644--- a/systemd/shirudo-keepalive.timer+++ b/systemd/shirudo-keepalive.timer@@ -6,7 +6,7 @@ Description=shirudo: periodically export target status keepalive[Timer]OnBootSec=5s-OnUnitInactiveSec=5s+OnUnitInactiveSec=60sAccuracySec=1sUnit=shirudo-keepalive.servicediff --git a/testing/functional/otel/t8003-systemd-map-export.sh b/testing/functional/otel/t8003-systemd-map-export.shindex 43146fda..73bcfe10 100755--- a/testing/functional/otel/t8003-systemd-map-export.sh+++ b/testing/functional/otel/t8003-systemd-map-export.sh@@ -38,18 +38,18 @@ test_expect_success 'map export timer waits five seconds between runs' '../systemd/shirudo-map-export.timer'-test_expect_success 'keepalive service exports status with TPM and system data' '+test_expect_success 'keepalive service sends the quoted keepalive' 'grep -q "^After=shirudo.service$" \../systemd/shirudo-keepalive.service.in &&grep -q "^EnvironmentFile=-/etc/shirudo/map-export.env$" \../systemd/shirudo-keepalive.service.in &&- grep -q "^ExecStart=@bindir@/shirudo status --otel --include-system$" \+ grep -q "^ExecStart=@bindir@/shirudo status --otel$" \../systemd/shirudo-keepalive.service.in'-test_expect_success 'keepalive timer waits five seconds between runs' '+test_expect_success 'keepalive timer waits a minute between runs' 'grep -q "^OnBootSec=5s$" ../systemd/shirudo-keepalive.timer &&- grep -q "^OnUnitInactiveSec=5s$" \+ grep -q "^OnUnitInactiveSec=60s$" \../systemd/shirudo-keepalive.timer &&grep -q "^Unit=shirudo-keepalive.service$" \../systemd/shirudo-keepalive.timer &&@@ -71,7 +71,7 @@ test_expect_success 'target install resolves and stages exporter units' ') &&grep -q "^ExecStart=/opt/shirudo/bin/shirudo upatch map --all$" \"$GENERATED" &&- grep -q "^ExecStart=/opt/shirudo/bin/shirudo status --otel --include-system$" \+ grep -q "^ExecStart=/opt/shirudo/bin/shirudo status --otel$" \"$GENERATED_KEEPALIVE" &&grep -q "systemd/shirudo-map-export.service" "$WORK/target.plan" &&grep -q "systemd/shirudo-map-export.timer" "$WORK/target.plan" &&diff --git a/testing/functional/otel/t8004-status-otel.sh b/testing/functional/otel/t8004-status-otel.shindex 9c86eb22..4675780c 100644--- a/testing/functional/otel/t8004-status-otel.sh+++ b/testing/functional/otel/t8004-status-otel.sh@@ -8,51 +8,54 @@ cd "$(dirname "$0")/../.."S=../shirudoH=helper/test-otel-map-test_expect_success 'status --otel sends a structured keepalive log' '- work=$(mktemp -d)+# No TPM answers here: the keepalive cannot be quoted.+export SHIRUDO_TPM_TCTI=device:/nonexistent/tpm++# A sink on an ephemeral port; its pid is in $work/sink.pid.+sink() {+ rm -f "$work/port"python3 helper/otel-mock.py success "$work/port" "$work/body" \"$work/meta" &- server=$!- trap "kill $server 2>/dev/null || true; wait $server 2>/dev/null || true; rm -rf $work" EXIT+ echo "$!" >"$work/sink.pid"i=0while test ! -s "$work/port" && test "$i" -lt 100; dosleep .02i=$((i + 1))done+ test -s "$work/port"+}++test_expect_success 'status --keepalive prints the body with its keys in order' '+ work=$(mktemp -d) &&+ "$S" status --keepalive >"$work/body" 2>"$work/stderr" &&+ python3 - "$work/body" <<"PY" &&+import json, sys++KEYS = ["schema", "boot_id", "version_id", "config_root", "kernel_release",+ "image_id", "image_version", "image_root", "verdict", "cond",+ "flags", "tamper", "tree_id", "generation", "base_seq", "last_seq",+ "base_root", "projection_root", "mask", "set_sha256", "count",+ "not_ok"]+text = open(sys.argv[1]).read()+assert text.endswith("}\n") and text.count("\n") == 1, text+pairs = json.loads(text, object_pairs_hook=list)+assert [k for k, _ in pairs] == KEYS, pairs+assert dict(pairs)["schema"] == "shirudo.keepalive/1"+PY+ rm -rf "$work"+'++test_expect_success 'status --otel without a TPM sends nothing and fails' '+ work=$(mktemp -d) &&+ sink &&port=$(cat "$work/port") &&- OTEL_EXPORTER_OTLP_LOGS_ENDPOINT="http://127.0.0.1:$port/v1/logs" \+ ! OTEL_EXPORTER_OTLP_LOGS_ENDPOINT="http://127.0.0.1:$port/v1/logs" \"$S" status --otel >"$work/stdout" 2>"$work/stderr" &&- wait "$server" &&test ! -s "$work/stdout" &&- python3 - "$work/body" "$work/meta" <<"PY"-import json-import sys--doc = json.load(open(sys.argv[1]))-meta = json.load(open(sys.argv[2]))-record = doc["resourceLogs"][0]["scopeLogs"][0]["logRecords"][0]-values = {- item["key"]: item["value"]- for item in record["body"]["kvlistValue"]["values"]-}-assert meta["path"] == "/v1/logs"-assert record["eventName"] == "shirudo.keepalive"-assert {"schema", "status", "conditions", "tpm"} <= values.keys()-assert values["tpm"]["kvlistValue"]-status = values["status"]["stringValue"]-severity = {- "ok": (9, "INFO"),- "degraded": (13, "WARN"),- "init-pending": (13, "WARN"),- "reboot-pending": (13, "WARN"),- "lsm-off": (17, "ERROR"),- "tampered": (17, "ERROR"),-}[status]-assert (record["severityNumber"], record["severityText"]) == severity-attrs = {item["key"]: item["value"] for item in record["attributes"]}-assert "shirudo.status" in attrs-assert "shirudo.version_id" in attrs-PY+ grep -q "nothing is sent" "$work/stderr" &&+ test ! -e "$work/body" &&+ kill "$(cat "$work/sink.pid")" &&+ rm -rf "$work"'test_expect_success 'keepalive status severities and structured body are deterministic' '@@ -125,22 +128,15 @@ PYrm -rf "$work"'-test_expect_success 'status --json --otel keeps JSON output available' '- work=$(mktemp -d)- python3 helper/otel-mock.py success "$work/port" "$work/body" \- "$work/meta" &- server=$!- trap "kill $server 2>/dev/null || true; wait $server 2>/dev/null || true; rm -rf $work" EXIT- i=0- while test ! -s "$work/port" && test "$i" -lt 100; do- sleep .02- i=$((i + 1))- done+test_expect_success 'status --json --otel prints the report when the keepalive fails' '+ work=$(mktemp -d) &&+ sink &&port=$(cat "$work/port") &&- OTEL_EXPORTER_OTLP_LOGS_ENDPOINT="http://127.0.0.1:$port/v1/logs" \+ ! OTEL_EXPORTER_OTLP_LOGS_ENDPOINT="http://127.0.0.1:$port/v1/logs" \"$S" status --json --otel >"$work/stdout" 2>"$work/stderr" &&- wait "$server" &&- python3 - "$work/stdout" <<"PY"+ test ! -e "$work/body" &&+ kill "$(cat "$work/sink.pid")" &&+ python3 - "$work/stdout" <<"PY" &&import jsonimport sys@@ -150,6 +146,7 @@ assert "status" in docassert "tpm" in docassert "tamper_attempts" in docPY+ rm -rf "$work"'test_expect_success 'status --otel without an endpoint does not send' 'diff --git a/testing/functional/otel/t8005-tls-policy.sh b/testing/functional/otel/t8005-tls-policy.shindex bae4c0fc..9022a908 100755--- a/testing/functional/otel/t8005-tls-policy.sh+++ b/testing/functional/otel/t8005-tls-policy.sh@@ -4,7 +4,8 @@## t8005 -- outbound TLS policy: every libcurl client shirudo opens requires# TLS 1.3 and a hybrid ML-KEM key exchange, nothing classical. Drives the-# OTLP log exporter (`shirudo status --otel`) against local servers: a+# OTLP log exporter, as the keepalive of `shirudo status --otel` uses it,+# through `test-otel-map send-keepalive` against local servers: a# TLS 1.2-only HTTPS server, which must be refused before any request# reaches it; an `openssl s_server` limited to X25519, which must also be# refused; and an `openssl s_server` with handshake tracing, which must@@ -14,11 +15,11 @@cd "$(dirname "$0")/../..". ./test-lib.sh-S=${SHIRUDO:-../shirudo}+H=helper/test-otel-mapcommand -v openssl >/dev/null 2>&1 || test_skip_all "no openssl"command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"-[ -x "$S" ] || test_skip_all "shirudo not built"+[ -x "$H" ] || test_skip_all "test-otel-map not built"WORK=$(mktemp -d)# s_server has usually exited on its own by now; under set -e a failed@@ -31,6 +32,7 @@ cleanup() {rm -rf "$WORK"}trap cleanup EXIT HUP INT TERM+printf '{"schema":"shirudo.keepalive/1"}' >"$WORK/body"openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \-subj /CN=localhost -addext 'subjectAltName=IP:127.0.0.1,DNS:localhost' \@@ -79,10 +81,10 @@ sys.exit(0 if s.connect_ex(("127.0.0.1", int(sys.argv[1]))) == 0 else 1)' "$1" 2# The exporter is the TLS client under test; the test certificate is its# trust anchor so the policy, not certificate verification, decides.export_status() {- OTEL_EXPORTER_OTLP_LOGS_ENDPOINT="https://127.0.0.1:$1/v1/logs" \OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE="$WORK/cert.pem" \OTEL_EXPORTER_OTLP_LOGS_TIMEOUT=3000 \- timeout 60 "$S" status --otel >/dev/null 2>"$WORK/client.err"+ timeout 60 "$H" send-keepalive "https://127.0.0.1:$1/v1/logs" ok \+ "$WORK/body" quote >/dev/null 2>"$WORK/client.err"}port12=$(free_port)@@ -93,7 +95,6 @@ wait_for_port "$port12" || test_skip_all "TLS 1.2 test server did not start"test_expect_success 'a TLS 1.2-only collector is refused before any request is sent' '! export_status "$port12" &&- grep -q "OTEL export failed" "$WORK/client.err" &&! test -e "$WORK/seen"'@@ -111,7 +112,6 @@ if openssl list -tls1_3 -tls-groups 2>/dev/null | grep -qi 'X25519MLKEM768'; thetest_expect_success 'a TLS 1.3 server offering only classical X25519 is refused' '! export_status "$portx" &&- grep -q "OTEL export failed" "$WORK/client.err" &&! grep -q "ServerHello, Length" "$WORK/trace-x25519.log"'diff --git a/testing/functional/otel/t8106-status-otel-quote.sh b/testing/functional/otel/t8106-status-otel-quote.shnew file mode 100755index 00000000..10429c5e--- /dev/null+++ b/testing/functional/otel/t8106-status-otel-quote.sh@@ -0,0 +1,92 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t8106 -- status --otel on a target sends one OTLP log: the keepalive+# body as a string, the TPM quote of it as the one attribute and the+# severity of its verdict.++cd "$(dirname "$0")/../.."+. ./integration-lib.sh+target_guard+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"+"$SHIRUDO_BIN" image update "$SHIRUDO_TEST_KEY_FIXTURES/config-otel" \+ >/dev/null 2>&1 || test_skip_all "cannot activate the config-otel image"+export SHIRUDO_TEST_OTEL_PORT=5444+W=$(mktemp -d) || exit 1+TIMER_WAS_ACTIVE=0+systemctl is-active --quiet shirudo-keepalive.timer 2>/dev/null &&+ TIMER_WAS_ACTIVE=1++# Under the library's errexit a failing step would end the cleanup.+cleanup() {+ [ -s "$W/sink.pid" ] && kill "$(cat "$W/sink.pid")" 2>/dev/null || true+ if [ "$TIMER_WAS_ACTIVE" = 1 ]; then+ systemctl start shirudo-keepalive.timer >/dev/null 2>&1 || true+ fi+ rm -rf "$W"+}+trap cleanup EXIT+# The timer's own keepalive would reach the sink first.+systemctl stop shirudo-keepalive.timer >/dev/null 2>&1 || true+systemctl stop shirudo-keepalive.service >/dev/null 2>&1 || true++# status --otel against a sink, which keeps the request in $W/$1.json.+send_keepalive() {+ rm -f "$W/port"+ python3 helper/otel-mock.py success "$W/port" "$W/$1.json" \+ "$W/$1.meta" &+ echo "$!" >"$W/sink.pid"+ i=0+ while test ! -s "$W/port" && test "$i" -lt 100; do+ sleep .05+ i=$((i + 1))+ done+ "$SHIRUDO_BIN" status --otel >"$W/$1.stdout" || return 1+ wait "$(cat "$W/sink.pid")" || return 1+ rm -f "$W/sink.pid"+}++test_expect_success 'status --otel sends one record with a string body and its quote' '+ send_keepalive one &&+ test ! -s "$W/one.stdout" &&+ python3 - "$W/one.json" "$W/one.meta" <<"PY"+import base64, json, re, sys++KEYS = ["schema", "boot_id", "version_id", "config_root", "kernel_release",+ "image_id", "image_version", "image_root", "verdict", "cond",+ "flags", "tamper", "tree_id", "generation", "base_seq", "last_seq",+ "base_root", "projection_root", "mask", "set_sha256", "count",+ "not_ok"]+SEVERITY = {"ok": (9, "INFO"), "degraded": (13, "WARN"),+ "init-pending": (13, "WARN"), "reboot-pending": (13, "WARN"),+ "tampered": (17, "ERROR"), "lsm-off": (17, "ERROR")}++meta = json.load(open(sys.argv[2]))+assert meta["attempts"] == 1 and meta["path"] == "/v1/logs", meta+rl = json.load(open(sys.argv[1]))["resourceLogs"]+assert len(rl) == 1 and len(rl[0]["scopeLogs"]) == 1+scope = rl[0]["scopeLogs"][0]+assert scope["scope"]["name"] == "shirudo.keepalive", scope["scope"]+assert len(scope["logRecords"]) == 1+record = scope["logRecords"][0]+assert record["eventName"] == "shirudo.keepalive"+assert list(record["body"]) == ["stringValue"], record["body"]+pairs = json.loads(record["body"]["stringValue"], object_pairs_hook=list)+assert [k for k, _ in pairs] == KEYS, pairs+body = dict(pairs)+assert body["schema"] == "shirudo.keepalive/1"+assert (record["severityNumber"], record["severityText"]) == \+ SEVERITY[body["verdict"]], (record, body["verdict"])+assert [a["key"] for a in record["attributes"]] == ["shirudo.quote"]+quote = record["attributes"][0]["value"]["stringValue"]+b64 = "([A-Za-z0-9+/]+={0,2})"+m = re.fullmatch("attest=%s;sig=%s;ak=%s" % (b64, b64, b64), quote)+assert m, quote+for field in m.groups():+ assert base64.b64encode(base64.b64decode(field, validate=True)) == \+ field.encode(), field+PY+'++test_donediff --git a/testing/functional/tpm/t4104-keepalive-quote.sh b/testing/functional/tpm/t4104-keepalive-quote.shnew file mode 100644index 00000000..668f1f65--- /dev/null+++ b/testing/functional/tpm/t4104-keepalive-quote.sh@@ -0,0 +1,149 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t4104 -- the quote a keepalive carries, as shirudo-quote-check reads+# it: the attestation key of shirudo attest quotes the SHA-256 of the+# body, signs as that key under the endorsement hierarchy, and orders+# its quotes by the TPM clock; another body does not match it.++cd "$(dirname "$0")/../.."+. ./integration-lib.sh+target_guard+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"+QUOTE_CHECK=helper/shirudo-quote-check+[ -x "$QUOTE_CHECK" ] || test_skip_all "shirudo-quote-check is not built"+"$SHIRUDO_BIN" image update "$SHIRUDO_TEST_KEY_FIXTURES/config-otel" \+ >/dev/null 2>&1 || test_skip_all "cannot activate the config-otel image"+export SHIRUDO_TEST_OTEL_PORT=5444+NONCE=0102030405060708090a0b0c0d0e0f10+W=$(mktemp -d) || exit 1+TIMER_WAS_ACTIVE=0+systemctl is-active --quiet shirudo-keepalive.timer 2>/dev/null &&+ TIMER_WAS_ACTIVE=1++# Under the library's errexit a failing step would end the cleanup.+cleanup() {+ [ -s "$W/sink.pid" ] && kill "$(cat "$W/sink.pid")" 2>/dev/null || true+ if [ "$TIMER_WAS_ACTIVE" = 1 ]; then+ systemctl start shirudo-keepalive.timer >/dev/null 2>&1 || true+ fi+ rm -rf "$W"+}+trap cleanup EXIT+# The timer's own keepalive would reach the sink first.+systemctl stop shirudo-keepalive.timer >/dev/null 2>&1 || true+systemctl stop shirudo-keepalive.service >/dev/null 2>&1 || true++# Splits a received record into its body, $W/$1.body, and the row of+# shirudo-quote-check for it, $W/$1.row; with a third argument the row+# names the hash of that file instead of the body's.+cat >"$W/row.py" <<'PY'+import hashlib, json, sys++record = json.load(open(sys.argv[1]))["resourceLogs"][0]["scopeLogs"][0][+ "logRecords"][0]+body = record["body"]["stringValue"].encode()+open(sys.argv[2], "wb").write(body)+fields = dict(f.split("=", 1) for f in+ record["attributes"][0]["value"]["stringValue"].split(";"))+hashed = open(sys.argv[4], "rb").read() if len(sys.argv) > 4 else body+row = [fields["attest"], fields["sig"], fields["ak"],+ hashlib.sha256(hashed).hexdigest()]+open(sys.argv[3], "w").write("\t".join(row) + "\n")+PY++# The quoted data and the signer of a TPMS_ATTEST against the body and+# the attestation key of a row.+cat >"$W/attest.py" <<'PY'+import base64, hashlib, struct, sys++attest_b64, _, ak_b64, _ = open(sys.argv[1]).read().rstrip("\n").split("\t")+body = open(sys.argv[2], "rb").read()+attest = base64.b64decode(attest_b64)+ak_name = b"\x00\x0b" + hashlib.sha256(base64.b64decode(ak_b64)).digest()+qualified = b"\x00\x0b" + hashlib.sha256(+ struct.pack(">I", 0x4000000B) + ak_name).digest()+magic, kind = struct.unpack(">IH", attest[:6])+assert (magic, kind) == (0xFF544347, 0x8018), (hex(magic), hex(kind))+off = 6+size, = struct.unpack(">H", attest[off:off + 2])+signer = attest[off + 2:off + 2 + size]+off += 2 + size+size, = struct.unpack(">H", attest[off:off + 2])+extra = attest[off + 2:off + 2 + size]+assert signer == qualified, (signer.hex(), qualified.hex())+assert extra == hashlib.sha256(body).digest(), extra.hex()+print(ak_name.hex())+PY++# status --otel against a sink, which keeps the request in $W/$1.json.+send_keepalive() {+ rm -f "$W/port"+ python3 helper/otel-mock.py success "$W/port" "$W/$1.json" \+ "$W/$1.meta" &+ echo "$!" >"$W/sink.pid"+ i=0+ while test ! -s "$W/port" && test "$i" -lt 100; do+ sleep .05+ i=$((i + 1))+ done+ "$SHIRUDO_BIN" status --otel >/dev/null || return 1+ wait "$(cat "$W/sink.pid")" || return 1+ rm -f "$W/sink.pid" &&+ python3 "$W/row.py" "$W/$1.json" "$W/$1.body" "$W/$1.row"+}++# A key of the checker's line for row $1.+checked() {+ python3 -c '+import json, sys+print(json.loads(open(sys.argv[1]).read())[sys.argv[2]])+' "$W/$1.out" "$2"+}++test_expect_success 'the checker accepts a keepalive quote of its body' '+ send_keepalive one &&+ "$QUOTE_CHECK" <"$W/one.row" >"$W/one.out" &&+ [ "$(checked one ok)" = 1 ] &&+ python3 "$W/attest.py" "$W/one.row" "$W/one.body" >"$W/one.name" &&+ [ "$(checked one ak_name)" = "$(cat "$W/one.name")" ]+'++test_expect_success 'the keepalive key is the attestation key of shirudo attest' '+ "$SHIRUDO_BIN" attest --nonce="$NONCE" --output="$W/evidence.json" &&+ python3 -c "+import json, sys+print(json.load(open(sys.argv[1]))[\"ak\"][\"name\"])+" "$W/evidence.json" >"$W/attest.name" &&+ [ "$(cat "$W/attest.name")" = "$(checked one ak_name)" ]+'++test_expect_success 'a later keepalive has a later TPM clock' '+ send_keepalive two &&+ "$QUOTE_CHECK" <"$W/two.row" >"$W/two.out" &&+ [ "$(checked two ok)" = 1 ] &&+ [ "$(checked two ak_name)" = "$(checked one ak_name)" ] &&+ python3 -c "+import json, sys+one, two = (json.load(open(p)) for p in sys.argv[1:3])+assert (two[\"reset_count\"], two[\"clock\"]) > \+ (one[\"reset_count\"], one[\"clock\"]), (one, two)+" "$W/one.out" "$W/two.out"+'++test_expect_success 'a body altered by one byte does not match the quote' '+ python3 -c "+import sys+body = bytearray(open(sys.argv[1], \"rb\").read())+body[-2] ^= 1+open(sys.argv[2], \"wb\").write(body)+" "$W/one.body" "$W/altered.body" &&+ python3 "$W/row.py" "$W/one.json" "$W/one.body" "$W/altered.row" \+ "$W/altered.body" &&+ "$QUOTE_CHECK" <"$W/altered.row" >"$W/altered.out" &&+ [ "$(checked altered ok)" = 0 ] &&+ [ "$(checked altered reason)" = body_mismatch ]+'++test_donediff --git a/testing/vm/build-bundle.sh b/testing/vm/build-bundle.shindex e256f6e1..78c902b6 100755--- a/testing/vm/build-bundle.sh+++ b/testing/vm/build-bundle.sh@@ -322,6 +322,7 @@ jobs=$(nproc)log "building host shirudo payload and test helpers"make -C "$REPO_ROOT" -j"$jobs" allmake -C "$REPO_ROOT" -j"$jobs" shirudo-build+make -C "$REPO_ROOT" -j"$jobs" quote-checkmake -C "$REPO_ROOT/testing" -j"$jobs" test-helpersTMP_DIR="$(mktemp -d "${BUNDLE_DIR}.tmp.XXXXXX")"@@ -370,6 +371,9 @@ testing/end2end/policy-exectesting/helper/otel-mock.pytesting/helper/test-oci-registry.pyEOF+# The backend's quote checker, a static PIE, checks the quotes of t4104.+install -m 0755 "$REPO_ROOT/tools/quote-check/shirudo-quote-check" \+ "$TMP_DIR/test-helpers/testing/helper/shirudo-quote-check"# A second TPM for t6125: the host's emulator and the libraries of its own.if swtpm="$(command -v swtpm)"; then