eBPF-based security platform
tpm: require writer authorization for every NV extension
Leonard Cohnen69bab4866fd2
diff --git a/Documentation/architecture.rst b/Documentation/architecture.rstindex 8a128509..82f0229f 100644--- a/Documentation/architecture.rst+++ b/Documentation/architecture.rst@@ -136,7 +136,7 @@ The target holds the certificate, the sealed keyring, the private bpffsmount, the installed upatches, the eventlog and the TPM register. It runs``init``, ``upatch load``, ``upatch unload`` and the install side of``bpm``. The target never sees the operator's private key. Its separate-boot-scoped RSA key is held in the kernel for local register authorization.+boot-scoped RSA key authorizes only local TPM register extensions.Delivery is pull-based. The operator publishes a package to an OCIregistry; the target pulls it on a timer or by hand, verifies the@@ -445,7 +445,7 @@ its public key and key IDs into the identity map. The mandatory key guardpermits signing only from tasks with authenticated runtime authority.The key survives switch-root and TPM resets within thatkernel boot. `The TPM design <tpm.rst#write-policy>`__ describes its-key custody and trust assumptions.+provisioning, command-bound signatures and process-integrity assumptions.7) Target state---------------@@ -495,9 +495,11 @@ Measurement register. The measurement lives in a TPM 2.0 NV index(default ``0x01818E00``) built the way systemd builds its NvPCRs: anextend-only index (``TPM2_NT_EXTEND``) whose contents clear at everyTPM reset (``TPMA_NV_CLEAR_STCLEAR``) and whose write policy is-``PolicyOR(PolicyNvWritten(YES), PolicyNvWritten(NO) || PolicyPCR(PCRs-9, 11))``, computed from the values PCRs 9 and 11 hold when ``init``-binds the register. ``init`` runs from the initrd, after systemd has+bound to PCRs 9 and 11 and the boot writer's public key.+Both the first and subsequent writes require command-bound authorization;+the complete policy is specified in `the TPM design <tpm.rst#write-policy>`__.+``init`` runs from the initrd,+after systemd hasmeasured ``enter-initrd`` into PCR 11 and before ``leave-initrd``moves it, performs the first write through the PCR branch and thenextends PCR 9 with the record ``nvpcr-init:shirudo:0x1818e00:<name>``@@ -510,9 +512,11 @@ under a weaker policy has a name other than the one ``init`` recordedand anchored. The record carries both PCR values and whether theinitrd was running, so a verifier pins the ``enter-initrd`` value andrefuses a binding made from the root file system.-Reads need no authorisation; defining and undefining the index needs-the owner hierarchy, whose password, when set, comes from-``tpm.owner_auth`` in ``/etc/shirudo/shirudo.conf``. Every+Reads and certification use the index's empty authorization; no writer+secret is needed. Defining and undefining the index need the owner+hierarchy. Its authorization is empty by default; when set, the+password comes from ``tpm.owner_auth`` in+``/etc/shirudo/shirudo.conf``. Everystate-changing command reads the register first and refuses with``tampered`` when ``--expect-chain`` disagrees or the index is not theone ``init`` recorded. There is no TPM opt-out; an unmeasured targetdiff --git a/Documentation/config-images.rst b/Documentation/config-images.rstindex 631bb2b1..826505de 100644--- a/Documentation/config-images.rst+++ b/Documentation/config-images.rst@@ -330,7 +330,8 @@ it does not persist per-effect phases or predicted PCR before/after values.Direct TPM-command measurement spoofing remains separate work. Genuineoperations are measured and their history is replayed, but a PCR alonedoes not prove activation against an attacker able to issue measurement-commands. This limitation also affects the existing upatch NV register.+commands. The separate upatch NV register requires a guarded boot-writer+signature; that authorization does not cover config PCR extensions.No IMA integration is added, and signatures do not prevent rollback.Attestation includes the config PCR even if ``--pcrs`` omits it. Thediff --git a/Documentation/operations.rst b/Documentation/operations.rstindex 74b4ff38..d81ab9cb 100644--- a/Documentation/operations.rst+++ b/Documentation/operations.rst@@ -197,6 +197,17 @@ incorrect authenticated root stop initialization rather than choosing ahost-root fallback. Installing a target package alone does not provision theimages or start enforcement.+The authenticated NV-writer upgrade also requires updating the operator+verifier: the write policy and certified index Name change, and old+public-write-policy evidence is rejected. Install the updated+target profile and rebuild the initrd before rebooting. No secret file+needs migration or backup: the RSA writer is generated afresh at kernel+boot and stored in a protected asymmetric key. The kernel needs its+PKCS#8 private-key parser and RSA implementation; the TPM must verify+RSA-3072 RSASSA/SHA-256. The writer's public key lives in the frozen+identity map; there is no separate mutable binding-attempt record.++4) Kernel updates-----------------diff --git a/Documentation/threat-model.rst b/Documentation/threat-model.rstindex 34f1d1ee..e03b70da 100644--- a/Documentation/threat-model.rst+++ b/Documentation/threat-model.rst@@ -245,6 +245,25 @@ T5 Silent state changerecords for one reset, so the history a register holds cannot berestarted by rebinding it.+ Both policy branches require a command-bound signature from the+ kernel-held boot writer, guarded by ``lsm/key_permission`` using+ the committed runtime task mark. The `TPM design <tpm.rst#write-policy>`__+ specifies provisioning and authorization. Under the process-integrity+ assumptions below, this prevents an attacker from appending an expected+ positive event without doing the operation, even with a fabricated+ exported eventlog. The private key never lives in the eventlog, a+ regular file or a readable BPF map.+ Trusted initialization, TPM identity and approved boot measurements+ remain prerequisites. The NV Name commits to the writer's public+ key, not proof of its custody. Trusted initialization briefly handles the private key and scrubs+ it after import; later process+ memory disclosures do not expose reusable writer authority.+ Injected code can still request signatures. Kernel memory+ disclosure, privileged kernel tracing and hibernation exposure+ remain outside the key API's protection. RSA authorization is+ classical. Existing process-security and executable-integrity+ assumptions, including residual risks 2 and 5, still apply.+T6 The boot windowEnforcement is BPF and does not survive a reboot by itself.``shirudo-initrd.service`` runs ``init`` from the initrd, after the@@ -412,17 +431,19 @@ Each of these is known, documented and bounded; none is silent.or grant authority to host files. The separate `mount-moveinvestigation <https://github.com/shirudo-dev/shirudo/issues/12>`__ records the evidence.-4. TPM measurement writers are not yet bound to completed Shirudo+4. Config PCR writers are not yet bound to completed Shirudooperations. A caller with direct TPM-command access can append to the- written NV register or the config PCR. Garbage makes replay fail and+ config PCR. Garbage makes replay fail andcan deny service. A public digest of a valid operation can insteadrecord a claim that the operation happened when it did not. A freshnonce, a genuine TPM quote and replay of an externally supplied log donot prove who appended the digest or that the operation completed.The separate measurement-spoofing investigation is not fixed by imagemode. Static PCRs prevent runtime reset, not unauthorized extends.- Restricting measurement writers and handling operation/measurement- ordering remain separate work; no IMA integration is added.+ The upatch NV register requires the guarded boot writer, but owner+ undefinition and PCR interference can still deny service. Restricting+ config PCR writers and handling operation/measurement ordering remain+ separate work; no IMA integration is added.5. Authenticated boot must verify the expected runtime root. dm-verityverifies runtime files but still trusts the UKI, kernel and trusted processdiff --git a/Documentation/tpm.rst b/Documentation/tpm.rstindex c7c23fe2..c1e82549 100644--- a/Documentation/tpm.rst+++ b/Documentation/tpm.rst@@ -13,7 +13,8 @@ target without believing anything the target says about itself. Thisdocument describes both as implemented, how they relate to systemd'sNvPCRs, which the register is modelled on, and what they do not yetdo. The code is authoritative: ``util/chain.c`` (register and event-digests), ``util/tpm.c`` (libtss2 calls), ``util/tpm_wire.c`` (policy+digests), ``util/nv_writer.c`` (kernel-held writer),+``util/tpm.c`` (libtss2 calls), ``util/tpm_wire.c`` (policydigests, names and the TPM wire structures, used by both sides),``util/eventlog.c``, ``util/attest.c`` and ``builtin-attest.c``.`threat-model <threat-model.rst>`__ states what the design defends@@ -42,10 +43,12 @@ are ``0x0E060048``:``TPMA_NV_POLICYWRITE``The only way to write is a policy session that satisfies the- index's write policy below; there is no password.+ index's write policy below. Neither owner-write nor auth-write+ supplies an alternative write route.``TPMA_NV_OWNERREAD`` and ``TPMA_NV_AUTHREAD``- Reads need no authorisation.+ Reads and certification use an empty password. Owner-authorized+ reads are also supported.``TPMA_NV_NO_DA`` and ``TPMA_NV_ORDERLY``Failed authorisations do not count towards dictionary-attack@@ -56,12 +59,11 @@ are ``0x0E060048``:Write policy~~~~~~~~~~~~-The write policy is ``PolicyOR(written, init)`` with two branches:+The write policy is ``PolicyOR(written, init)``, followed by+``PolicySigned`` and ``PolicyCommandCode(NV_Extend)``. Its branches:-* ``written`` is ``PolicyNvWritten(YES)``: once the index has been- written this boot, anyone with access to the TPM may extend it,- exactly as anyone may extend a PCR. Appending history is not the- threat; rewriting it is.+* ``written`` is ``PolicyNvWritten(YES)``: later writes cannot+ initialize a recreated, unwritten index.* ``init`` is ``PolicyNvWritten(NO)`` followed by ``PolicyPCR`` overPCRs 9 and 11 at the values they hold when ``init`` binds the@@ -71,12 +73,53 @@ The write policy is ``PolicyOR(written, init)`` with two branches:``leave-initrd``, so a register bound from the initrd can be bound bynothing that runs after it.-Trusted initialization also provisions a boot-scoped RSA-3072 writer-in a sealed kernel keyring and scrubs its temporary private-key copies.-The frozen identity records its public key and key IDs. The key guard-permits signing only from tasks with authenticated runtime authority;-this relies on trusted bootstrap and process integrity, not the public-file label. The writer survives switch-root and TPM resets in that boot.+Both branches require an RSA-3072 RSASSA-PKCS1-v1_5 signature with+SHA-256 from this boot's kernel-held NV writer key. The signature+covers the live session's nonempty TPM nonce, a zero expiration,+the SHA-256 command hash and the fixed reference+``shirudo-nv-writer-v1``. The command hash covers ``NV_Extend``, both+handle Names and the marshalled event. The first write uses the+unwritten Name; subsequent writes use the written Name. The TPM+checks that exact command hash when executing the extend. A caller+with a pre-opened or passed TPM descriptor cannot authorize a new+extend without the guarded signing operation. Public appends would permit fabricated positive events:+measuring an expected load is not proof that the load happened.++Startup hardening locks all current and future process mappings before+command dispatch. Trusted initialization generates the key, imports+PKCS#8 into a kernel ``asymmetric`` key and scrubs its temporary copies;+the mapping locks remain active until process exit. Bootstrap creates+the signer in its lasting keyring with owner view/search permissions,+then restricts and seals the ring. Bootstrap is trusted: production+runs in the measured initrd before untrusted workloads. The public key,+private-key ID and keyring ID are frozen in the identity map before attachment.+There is no additional state key or mutable binding-attempt marker.+The keyring is already available to later invocations;+``lsm/key_permission`` must be attached and pinned before initialization+completes and untrusted workloads run.+The mandatory guard checks committed runtime task authority, never a+public label or mutable executable pointer. Search is refused even for+possessed NV keys: that permission authorizes signing or invalidation.+These denials are not counted because ordinary keyring traversal also+requests search. The asymmetric key has no private-payload read operation.++The key survives switch-root and a TPM reset during the same kernel+boot. Later+one-shot invocations hold only the public key and request signatures+through ``KEYCTL_PKEY_SIGN``. Sessions and external public-key handles+are flushed after use. Expiration zero does not impose a time limit:+an outstanding signature remains bound to its live session and exact+command until that session is destroyed.++The authenticated runtime and process guards protect the code that can+request signatures. The static target does not load host libraries or+OpenSSL provider configuration, and runtime exec rejects traced callers.+Code that compromises an authorized task can still use the signing+operation without extracting the private key.+Kernel memory disclosure, privileged kernel tracing,+hibernation images and compromise during key generation remain outside+the protection of the key API. RSA authorization is classical, unlike+the operator's ML-DSA-87 artifact signatures.The index's TPM name is the SHA-256 of its public area (handle, namealgorithm, attributes, policy digest, size), prefixed with the@@ -96,18 +139,22 @@ it binds the register after it has re-applied the installed set, inthis order:1. Read PCRs 9 and 11; the values are ``pcr_before`` and- ``phase_before``. Compute both policy branches, the policy digest- and the two names from them.+ ``phase_before``. Read the writer's public key from the frozen+ identity map and reconstruct its fixed TPMT_PUBLIC template, with+ exponent 65537. Compute both policy branches, the policy digest+ and the two NV Names.-2. If the index exists from an earlier boot, is unwritten and carries- the expected unwritten name, keep it. Otherwise define it under- the computed policy, undefining a stale index first. Defining and+2. Define the index, replacing a prior written or mismatching index.+ Defining andundefining need the owner hierarchy; when the TPM has an ownerpassword, ``tpm.owner_auth`` in ``/etc/shirudo/shirudo.conf``supplies it. The name the TPM reports is compared with the onecomputed in software; a mismatch is ``EPROTO``, not a retry.+ The index receives no secret writer authorization; its policy names+ the public signing key. Provisioning still uses the existing owner+ authorization over the trusted local TPM channel.-3. Extend the index with the init event through the ``init`` branch.+3. Extend the index with the init event through the signed ``init`` branch.The session walks the branch on the TPM and its digest is read backwith ``PolicyGetDigest`` and compared with the software policy, soa drift between ``util/tpm_wire.c`` and the TPM fails with a clear@@ -124,8 +171,9 @@ this order:5. Append the ``init`` record to the eventlog (section 3) with bothPCR values, whether the initrd was running, the written name, theanchor and its digest, the register value, the TPM's reset- count and ``nv_writer_public``: the 384-byte big-endian RSA modulus- in 768 hex digits, without a TPM header. The exponent is fixed at 65537.+ count and ``nv_writer_public``: the writer's public key, encoded as+ the 384-byte, big-endian RSA modulus in 768 hex digits, without a TPM+ header. The exponent is fixed at 65537 and is not stored.The phase measurements are ``systemd-pcrphase-initrd.service``'s,which systemd runs only for a measured UKI boot; without them PCR 11@@ -144,8 +192,8 @@ means this register period already has its binding. A re-run ofit and adds no event; finds it gone, unwritten or renamed, it refuseswith ``tampered`` and binds nothing before the next TPM reset, becausea second binding would restart the history the record vouches for.-An absent or unreadable writer identity refuses as well. Reuse and-extension check the live policy, reset count and frozen writer identity.+An absent or unreadable writer identity refuses as well. A re-run+with a complete binding reuses the same writer.Without a record for the current count, whether the boot is new orthe TPM was reset without a reboot, the index is bound; one foundwritten by someone else first is undefined and bound again, with a@@ -155,7 +203,7 @@ Extending later~~~~~~~~~~~~~~~Every load, unload and tree operation extends the register through-the ``written`` branch, with the policy recomputed from the+the authenticated ``written`` branch, with the policy recomputed from the``pcr_before`` on this boot's init record, and only after checkingthat the live index carries the recorded name. No register this bootis ``tpm_error``; a live index whose name is not the recorded one is@@ -177,10 +225,19 @@ TPM accessThe TCTI is ``SHIRUDO_TPM_TCTI`` in the environment, else ``tpm.tcti``in ``shirudo.conf``, else ``device:/dev/tpmrm0``, the kernel resource-manager. Redirecting it on a target changes nothing for the operator:-the evidence is signed by the key the operator pinned, and a-substitute TPM fails verification. libtss2's own logging is silenced-unless ``TSS2_LOG`` is set.+manager. Initialization requires the trusted local TPM channel+described above. Register writes send command-bound signatures, not+the writer's private key. A substitute TPM cannot forge evidence signed by the+operator's pinned attestation key. The selected transport+implementation remains part of shirudo's trusted process code.++Migration requires an updated target and initrd, a+trusted reboot, and the updated operator verifier. The new policy+changes the NV Name; old public-write-policy evidence is+rejected, not accepted through a compatibility branch. The Name+commits to the writer's public key and policy reference. It does not+prove private-key custody: verification still requires trusted TPM+identity and approved boot measurements covering initialization.2) Events---------@@ -239,8 +296,7 @@ extension, written with ``fsync`` and sealed like everything under``payload_sha256`` pairs), ``pcr`` (9), ``pcr_before``,``phase_pcr`` (11), ``phase_before``, ``bound_in`` (``initrd`` or``root``), ``nv_name`` (the written name), ``anchor``,- ``anchor_digest``, ``chain`` (the register after the event) and- ``nv_writer_public`` (the boot writer's RSA modulus).+ ``anchor_digest`` and ``chain`` (the register after the event).``upatch_load`` and ``upatch_unload````upatch`` with ``name`` and ``payload_sha256``; an unload a@@ -441,10 +497,11 @@ checks, in order:index of its own under a policy over PCRs it extends and resets atwill; the name a register bound to that record's ``pcr_before`` and``phase_before`` must have, computed in software from the handle,- the attributes with ``TPMA_NV_WRITTEN``, the policy and the size,- equals both the certified name and the recorded one. Every- ``--expect-bind-pcr`` value equals the recorded one for that PCR, so- the operator pins the ``enter-initrd`` phase value from the UKI, and+ the attributes with ``TPMA_NV_WRITTEN``, the policy including the+ fixed RSA-3072 template, ``nv_writer_public`` public key and reference,+ and the size, equals both the certified name and the recorded one.+ Every ``--expect-bind-pcr`` value equals the recorded one for that PCR,+ so the operator pins the ``enter-initrd`` phase value from the UKI, and``--require-initrd`` fails unless the record says the binding wasmade while the initrd ran; the record is the target's word, so``--expect-bind-pcr=11`` is what proves it.@@ -482,12 +539,12 @@ not shirudo evidence exits 2.--event=tree:<seq>=<operation_digest>...]`` prints ``set_digest``,``init_event``, ``register_at_boot`` and, with events,``register_after_events``, from the same functions the target uses.-With ``--bind-pcr=9=<hex> --bind-pcr=11=<hex> --writer-public=<hex>``-it also prints+With ``--bind-pcr=9=<hex> --bind-pcr=11=<hex>+--writer-public=<384-byte public-key hex>`` it also prints``register_name``, the anchor string and ``pcr9_after_anchor``, so the-name and PCR 9 can be pinned from values the operator knows. The writer-input is the 768-digit ``nv_writer_public`` from the boot's init record;-it is required together with both binding PCRs.+name and PCR 9 can be pinned from values the operator knows. A fresh+boot's writer public key is an additional input; it cannot be predicted+from artifacts and PCR binding values alone.``shirudo attest challenge --evidence=<path> --out=<path>[--ek-ca=<bundle>]`` is described in section 4; it prints its checks,@@ -504,14 +561,21 @@ systemd v259 and reworked in v262. Shared with it:* the index type and attributes, in particular ``TPM2_NT_EXTEND`` and``TPMA_NV_CLEAR_STCLEAR``, so the register is a per-boot PCR in NV;-* the write policy shape, ``PolicyOR`` of a ``PolicyNvWritten(YES)``- branch open to every TPM user and an initialisation branch that only+* the two-branch policy shape, ``PolicyOR`` of a ``PolicyNvWritten(YES)``+ branch and an initialisation branch that onlya particular boot state satisfies;* the index name as the anchor, certified by ``TPM2_NV_Certify``, andthe ``nvpcr-init:<name>:0x<handle>:<tpm name>`` event string.Different from it, and why it matters:+* **Authenticated writers.** Unlike systemd's public-append NvPCRs,+ shirudo requires ``PolicySigned`` and ``NV_Extend`` command+ restriction after the OR. Its runtime events assert successful+ operations, not merely a history that cannot be erased. Native+ systemd registration must preserve that authorization; adopting a+ public-append policy would reintroduce false positive measurements.+* **The initialisation branch.** systemd v262 binds it with``PolicyAuthorize`` to the UKI's PCR signing key (policy reference``initrd``) and satisfies it with the signed ``PolicyPCR`` for PCR 11@@ -542,7 +606,8 @@ Different from it, and why it matters:Registering the register as a systemd NvPCR, so that its name followsthe UKI signing key and systemd anchors it before the separator whileshirudo only extends it, is the deferred step that would remove the-remaining differences; until then the two coexist without interfering.+boot-integration differences; it must retain authenticated writers.+Until then the two coexist without interfering.7) Limits---------@@ -554,8 +619,8 @@ context and the deferred mitigations the plan.* **The binding values come from the record unless pinned.**``verify`` recomputes the index name from the ``pcr_before`` and``phase_before`` the init record claims; ``--expect-bind-pcr`` makes- them values the operator knows, and ``predict --bind-pcr`` turns- those into the expected name and PCR 9. Root with the owner+ them values the operator knows, and ``predict --bind-pcr`` with the+ writer public key turns those into the expected name and PCR 9. Root with the ownerauthorisation (empty on most TPMs) can still undefine the writtenindex at runtime; from then on every extension and ``init`` itselfrefuse ``tampered`` until the next TPM reset, a denial of service and@@ -622,6 +687,29 @@ parsers, the key derivations, the endorsement policy and thecredential blob against known vectors and an independentimplementation, without a TPM.+Post-init integration tests run only against a real kernel in the KVM+guest with swtpm attached through ``/dev/tpmrm0``+(``make -C testing test-tgt``). There is no software signing fixture:+the guest uses the production kernel-held writer and installed+``shirudo`` binary. ``testing/tpm/t1127-nv-writer.sh`` runs the command-binding+tests below and checks that the production register is unchanged.+``make -C testing test-tgt`` also exercises the+production initrd and switch-root path in ``testing/t1122-initrd.sh``.++``testing/helper/test-nv-cphash`` creates a separate kernel-held key with+the production provisioning function and signs through ``keyctl``.+It reuses the production TPM connection, NV lifecycle, kernel signing+and signed-policy helpers; only the invalid inputs and assertions are+test-specific. Production still selects its signing key from the+frozen identity.+It tests nonce and command binding directly through ESYS on a scratch+NV index in the guest. Replayed and corrupted signatures must fail+without changing NV. ``PolicySigned`` accepts an authorization for+event A; extending event B must fail without changing the value. A+fresh session then extends A and the test checks the exact result,+removes the scratch index and unlinks its temporary keyring.+No linker wrapping, software private-key files or production+fault-injection hooks are used.Configuration image measurements================================@@ -654,5 +742,6 @@ Without an expected config root, successful replay is reported asconsistency without operator approval. Neither this replay nor a staticPCR proves that only the trusted updater issued the TPM command: directmeasurement writers can record a selection without the corresponding-operation. Restricting writers remains separate work for both the config-PCR and the existing NV register; no IMA integration is added.+operation. Restricting writers remains separate work for the config PCR;+the upatch NV register requires the guarded writer described above.+No IMA integration is added.diff --git a/Makefile.shirudo b/Makefile.shirudoindex ac81b4ba..b83603d4 100644--- a/Makefile.shirudo+++ b/Makefile.shirudo@@ -605,6 +605,7 @@ TEST_HELPERS := $(VERITY_TEST_HELPERS) \testing/helper/test-tpm-wire \testing/helper/test-register \testing/helper/test-register-cli \+ testing/helper/test-nv-cphash \testing/helper/test-eventlog \testing/helper/test-keys \testing/helper/test-seal \@@ -699,6 +700,10 @@ testing/helper/tpmsim-cmd: testing/helper/tpmsim-cmd.c@printf ' CC $@\n'$(Q)$(CC) $(CFLAGS_BASE) -Iinclude $(TPMSIM_CFLAGS) -o $@ $< $(TPMSIM_LIBS) -lcrypto+testing/helper/test-nv-cphash: testing/helper/test-nv-cphash.c util/keyring.o $(REGISTER_OBJS)+ @printf ' CC $@\n'+ $(Q)$(CC) $(CFLAGS) -o $@ $^ $(REGISTER_LIBS)+testing/helper/test-config: testing/helper/test-config.c util/config.o util/io.o util/seal.o util/log.o util/hex.o \util/image_config.o util/string.o util/malloc.o@printf ' CC $@\n'diff --git a/contrib/build-test-vm-bundle.sh b/contrib/build-test-vm-bundle.shindex 78748d8e..b1087722 100755--- a/contrib/build-test-vm-bundle.sh+++ b/contrib/build-test-vm-bundle.sh@@ -328,6 +328,7 @@ testing/helper/test-config-attesttesting/helper/test-config-updatetesting/helper/tpmsim-cmdtesting/helper/test-tpm-wire+testing/helper/test-nv-cphashtesting/helper/test-configtesting/helper/test-bpf-loadtesting/helper/test-bpf-cmddiff --git a/testing/helper/test-nv-cphash.c b/testing/helper/test-nv-cphash.cnew file mode 100644index 00000000..f1e9393c--- /dev/null+++ b/testing/helper/test-nv-cphash.c@@ -0,0 +1,220 @@+// SPDX-License-Identifier: BSD-2-Clause+/* Copyright (c) 2026 Authors of shirudo */++#include <stdbool.h>+#include <linux/keyctl.h>+#include <stdio.h>+#include <string.h>++#include "tpm_internal.h"+#include "crypto.h"+#include "nv_writer.h"++#define TEST_NV_INDEX 0x01818E01u++enum signature_fault {+ SIGNATURE_VALID,+ SIGNATURE_REPLAY,+ SIGNATURE_CORRUPT,+};++static int tpm_failed(TSS2_RC rc, const char *operation)+{+ if (rc == TSS2_RC_SUCCESS)+ return 0;+ fprintf(stderr, "%s: rc=0x%08x\n", operation, (__u32)rc);+ return 1;+}++static int flush(ESYS_CONTEXT *esys, ESYS_TR *session)+{+ ESYS_TR handle = *session;++ if (handle == ESYS_TR_NONE)+ return 0;+ *session = ESYS_TR_NONE;+ return tpm_failed(Esys_FlushContext(esys, handle), "FlushContext");+}++static int read_value(ESYS_CONTEXT *esys, ESYS_TR nv, __u8 out[32])+{+ TPM2B_MAX_NV_BUFFER *data = NULL;+ int rc = 1;++ if (tpm_failed(Esys_NV_Read(esys, nv, nv, ESYS_TR_PASSWORD,+ ESYS_TR_NONE, ESYS_TR_NONE, 32, 0, &data),+ "NV_Read"))+ goto out;+ if (!data || data->size != 32) {+ fprintf(stderr, "NV_Read: expected a 32-byte value\n");+ goto out;+ }+ memcpy(out, data->buffer, 32);+ rc = 0;+out:+ Esys_Free(data);+ return rc;+}++static int authorize(struct shirudo_tpm *t, ESYS_TR writer, ESYS_TR nv,+ key_serial_t key, const __u8 event[32], const __u8 policy[32],+ ESYS_TR *session, __u8 saved[SHIRUDO_TPM_NV_RSA_BYTES],+ enum signature_fault fault)+{+ struct tpm_writer_authorization authorization = {};+ __u8 signature[SHIRUDO_TPM_NV_RSA_BYTES];+ TPM2B_NAME *name = NULL;+ TSS2_RC trc;+ int rc = 1;++ if (tpm_policy_session_start(t, session) ||+ tpm_failed(Esys_TRSess_SetAttributes(t->esys, *session,+ TPMA_SESSION_CONTINUESESSION,+ TPMA_SESSION_CONTINUESESSION),+ "TRSess_SetAttributes") ||+ tpm_failed(Esys_TR_GetName(t->esys, nv, &name), "TR_GetName"))+ goto out;+ if (!name || name->size != SHIRUDO_TPM_NAME_LEN) {+ fprintf(stderr, "NV index has an invalid Name\n");+ goto out;+ }+ if (tpm_writer_prepare(t, *session, name->name, event, &authorization))+ goto out;+ if (fault == SIGNATURE_REPLAY) {+ memcpy(signature, saved, sizeof(signature));+ } else {+ if (nv_writer_sign_key(key, authorization.digest, signature))+ goto out;+ if (fault == SIGNATURE_CORRUPT)+ signature[0] ^= 1;+ }+ trc = tpm_writer_authorize(t, writer, *session, &authorization, signature);+ if (fault != SIGNATURE_VALID) {+ if (trc != (TPM2_RC_SIGNATURE | TPM2_RC_P | TPM2_RC_5)) {+ fprintf(stderr, "PolicySigned: expected bad signature, got 0x%08x\n",+ (__u32)trc);+ goto out;+ }+ rc = 0;+ goto out;+ }+ if (tpm_failed(trc, "PolicySigned") || tpm_policy_session_finish(t, *session, policy))+ goto out;+ memcpy(saved, signature, sizeof(signature));+ rc = 0;+out:+ Esys_Free(name);+ return rc;+}++int main(void)+{+ TPM2B_MAX_NV_BUFFER event_a = { .size = 32, .buffer = {1} };+ TPM2B_MAX_NV_BUFFER event_b = { .size = 32, .buffer = {2} };+ __u8 signature[SHIRUDO_TPM_NV_RSA_BYTES] = {};+ __u8 writer_public[SHIRUDO_TPM_NV_RSA_BYTES];+ __u8 before[32], after[32], expected[32], fold[64];+ TPM2B_MAX_NV_BUFFER seed = { .size = 32 };+ ESYS_TR session = ESYS_TR_NONE;+ ESYS_TR writer = ESYS_TR_NONE;+ struct shirudo_tpm *t = NULL;+ ESYS_CONTEXT *esys = NULL;+ key_serial_t ring = 0, key = 0;+ ESYS_TR nv = ESYS_TR_NONE;+ __u8 policy[32], zero[32] = {};+ bool defined = false;+ int rc = 1, err;+ TSS2_RC trc;++ if (tpm_open(&t))+ goto out;+ esys = t->esys;+ err = nv_writer_create(&ring, &key, writer_public);+ if (err) {+ fprintf(stderr, "create kernel NV writer: %s\n", strerror(-err));+ goto out;+ }+ if (tpm_policy_signed(zero, writer_public, policy)) {+ fprintf(stderr, "cannot construct the scratch NV writer policy\n");+ goto out;+ }+ tpm_policy_command_code(policy, SHIRUDO_TPM_CC_NV_EXTEND, policy);+ if (tpm_writer_load(t, writer_public, &writer) ||+ tpm_nv_define(t, TEST_NV_INDEX, policy, NULL, 0))+ goto out;+ defined = true;+ if (tpm_failed(Esys_TR_FromTPMPublic(esys, TEST_NV_INDEX, ESYS_TR_NONE,+ ESYS_TR_NONE, ESYS_TR_NONE, &nv),+ "TR_FromTPMPublic") ||+ authorize(t, writer, nv, key, seed.buffer, policy,+ &session, signature, SIGNATURE_VALID) ||+ tpm_failed(Esys_NV_Extend(esys, nv, nv, session, ESYS_TR_NONE,+ ESYS_TR_NONE, &seed), "NV_Extend(seed)") ||+ flush(esys, &session) ||+ tpm_failed(Esys_TR_Close(esys, &nv), "TR_Close(NV)") ||+ tpm_failed(Esys_TR_FromTPMPublic(esys, TEST_NV_INDEX, ESYS_TR_NONE,+ ESYS_TR_NONE, ESYS_TR_NONE, &nv),+ "TR_FromTPMPublic") ||+ read_value(esys, nv, before) ||+ authorize(t, writer, nv, key, event_a.buffer, policy,+ &session, signature, SIGNATURE_VALID))+ goto out;+ trc = Esys_NV_Extend(esys, nv, nv, session, ESYS_TR_NONE, ESYS_TR_NONE, &event_b);+ if (trc != (TPM2_RC_POLICY_FAIL | TPM2_RC_S | TPM2_RC_1)) {+ fprintf(stderr, "NV_Extend(B): expected session-1 policy failure, got 0x%08x\n",+ (__u32)trc);+ goto out;+ }+ if (flush(esys, &session) || read_value(esys, nv, after))+ goto out;+ if (memcmp(before, after, 32)) {+ fprintf(stderr, "rejected NV_Extend changed the scratch value\n");+ goto out;+ }+ if (authorize(t, writer, nv, key, event_a.buffer, policy,+ &session, signature, SIGNATURE_REPLAY) ||+ flush(esys, &session) ||+ authorize(t, writer, nv, key, event_a.buffer, policy,+ &session, signature, SIGNATURE_CORRUPT) ||+ flush(esys, &session) || read_value(esys, nv, after))+ goto out;+ if (memcmp(before, after, 32)) {+ fprintf(stderr, "replayed or corrupt signature changed the scratch value\n");+ goto out;+ }+ if (authorize(t, writer, nv, key, event_a.buffer, policy,+ &session, signature, SIGNATURE_VALID) ||+ tpm_failed(Esys_NV_Extend(esys, nv, nv, session, ESYS_TR_NONE,+ ESYS_TR_NONE, &event_a), "NV_Extend(A)") ||+ flush(esys, &session) || read_value(esys, nv, after))+ goto out;+ memcpy(fold, before, 32);+ memcpy(fold + 32, event_a.buffer, 32);+ if (sha256_buffer(fold, sizeof(fold), expected) || memcmp(after, expected, 32)) {+ fprintf(stderr, "authorized NV_Extend did not produce SHA256(before || A)\n");+ goto out;+ }+ rc = 0;+out:+ if (esys) {+ if (flush(esys, &session))+ rc = 1;+ if (defined && tpm_nv_undefine(t, TEST_NV_INDEX, NULL, 0))+ rc = 1;+ if (flush(esys, &writer))+ rc = 1;+ }+ tpm_close(t);+ if (ring > 0) {+ err = keyring_unlink_key(KEY_SPEC_USER_KEYRING, ring);+ if (err) {+ fprintf(stderr, "unlink scratch writer keyring: %s\n", strerror(-err));+ rc = 1;+ }+ }+ if (!rc) {+ puts("PolicySigned: replay and corruption rejected; value unchanged");+ puts("cpHash: authorized A; rejected B unchanged; extended A; scratch index removed");+ }+ return rc;+}diff --git a/testing/run-target-tests.sh b/testing/run-target-tests.shindex 6ecf0ffc..e6539d93 100755--- a/testing/run-target-tests.sh+++ b/testing/run-target-tests.sh@@ -57,6 +57,7 @@ for t in \otel/t1115-map-export-all.sh \otel/t1116-otel-backend.sh \otel/t1117-otel-serialized-metric.sh \+ tpm/t1127-nv-writer.sh \tamperproof/t1110-lsm-deny.sh \tamperproof/t1112-prog-load-keyring-gate.sh \tamperproof/t1113-mount-lockdown.sh \diff --git a/testing/tpm/t0033-tpm-wire.sh b/testing/tpm/t0033-tpm-wire.shindex c613ff9c..7b792410 100644--- a/testing/tpm/t0033-tpm-wire.sh+++ b/testing/tpm/t0033-tpm-wire.sh@@ -70,7 +70,7 @@ print(hashlib.sha256(digest + bytes.fromhex(\"0000016c00000136\")).hexdigest())[ "$(./$H or $a $b)" != "$want" ]'-test_expect_success 'register policy branches match independent vectors' '+test_expect_success 'register policy = OR(written, init) -> Signed -> NV_Extend' 'v9=$(py "print(\"cd\"*32)") && v11=$(py "print(\"ef\"*32)") &&out=$(./$H register-policy 0xa00 $v9 $v11 $MODULUS) &&want=$(py "@@ -82,6 +82,10 @@ unwritten = h(bytes(32) + bytes.fromhex(\"0000018f00\"))values = h(bytes.fromhex(\"cd\"*32 + \"ef\"*32))init = h(unwritten + bytes.fromhex(\"0000017f00000001000b03000a00\") + values)policy = h(bytes(32) + bytes.fromhex(\"00000171\") + written + init)+name = bytes.fromhex(\"000b\") + h(bytes.fromhex(\"$PUB\"))+policy = h(policy + bytes.fromhex(\"00000160\") + name)+policy = h(policy + b\"shirudo-nv-writer-v1\")+policy = h(policy + bytes.fromhex(\"0000016c00000136\"))print(written.hex())print(init.hex())print(policy.hex())diff --git a/testing/tpm/t1127-nv-writer.sh b/testing/tpm/t1127-nv-writer.shnew file mode 100644index 00000000..8725d8b4--- /dev/null+++ b/testing/tpm/t1127-nv-writer.sh@@ -0,0 +1,26 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++cd "$(dirname "$0")/.."+. ./integration-lib.sh+target_guard+[ -x helper/test-nv-cphash ] ||+ test_skip_all "test-nv-cphash not built"+W=$(mktemp -d)+trap 'rm -f "$W/status.json" "$W/cphash.log"; rmdir "$W"' EXIT HUP INT TERM++test_expect_success 'kernel signatures enforce nonce and command binding on the vTPM' '+ before=$("$SHIRUDO_BIN" status --json |+ python3 -c "import json,sys; print(json.load(sys.stdin)[\"tpm\"][\"chain\"])") &&+ ./helper/test-nv-cphash >"$W/cphash.log" &&+ grep -qx "PolicySigned: replay and corruption rejected; value unchanged" "$W/cphash.log" &&+ grep -qx "cpHash: authorized A; rejected B unchanged; extended A; scratch index removed" \+ "$W/cphash.log" &&+ "$SHIRUDO_BIN" status --json >"$W/status.json" &&+ after=$(python3 -c "import json,sys; print(json.load(open(sys.argv[1]))[\"tpm\"][\"chain\"])" \+ "$W/status.json") &&+ [ "$before" = "$after" ]+'++test_donediff --git a/util/tpm.c b/util/tpm.cindex 30e89bd3..b3b778e0 100644--- a/util/tpm.c+++ b/util/tpm.c@@ -19,6 +19,7 @@#include "image_config.h"#include "log.h"#include "malloc.h"+#include "nv_writer.h"#include "paths.h"#define EK_CERT_NV_RSA 0x01C00002u@@ -537,6 +538,41 @@ TSS2_RC tpm_writer_authorize(struct shirudo_tpm *t, ESYS_TR key, ESYS_TR sessionreturn rc;}+static int policy_writer_signed(struct shirudo_tpm *t, ESYS_TR session,+ __u32 index, const __u8 event[32])+{+ struct tpm_writer_authorization authorization = {};+ __u8 signature[SHIRUDO_TPM_NV_RSA_BYTES];+ ESYS_TR key = ESYS_TR_NONE;+ struct tpm_nv_info nv;+ TSS2_RC rc;+ int err;++ err = tpm_nv_info(t, index, &nv);+ if (err)+ return err;+ if (!nv.defined || nv.name_len != SHIRUDO_TPM_NAME_LEN) {+ pr_err("tpm: NV writer requires a defined register");+ return -ENODEV;+ }+ err = tpm_writer_prepare(t, session, nv.name, event, &authorization);+ if (err)+ return err;+ err = nv_writer_sign(authorization.digest, signature);+ if (err)+ return err;+ err = tpm_writer_load(t, t->writer_public, &key);+ if (err)+ return err;+ rc = tpm_writer_authorize(t, key, session, &authorization, signature);+ session_flush(t, key);+ if (rc != TSS2_RC_SUCCESS) {+ pr_err("tpm: NV writer PolicySigned: rc=0x%08x", (__u32)rc);+ return -EACCES;+ }+ return 0;+}+int tpm_policy_session_finish(struct shirudo_tpm *t, ESYS_TR session,const __u8 expected[SHIRUDO_TPM_DIGEST_LEN]){@@ -564,29 +600,32 @@ int tpm_policy_session_finish(struct shirudo_tpm *t, ESYS_TR session,/** Walk one branch of the register's write policy in a real session and- * close it with PolicyOR. The session digest is then compared with the- * policy computed in software, so a formula drift fails loudly here- * instead of as an unexplained TPM2_RC_POLICY_FAIL.+ * authorize the exact NV_Extend with the kernel-held writer after PolicyOR.+ * Compare the session digest with the software policy to detect drift.*/static int policy_session_register(struct shirudo_tpm *t, bool init,+ __u32 index, const __u8 event[32],__u32 pcr_mask,const __u8 branch_written[32],const __u8 branch_init[32],ESYS_TR *session){TPML_DIGEST branches = { .count = 2 };- TPM2B_DIGEST *digest = NULL;__u8 expected[32];TSS2_RC rc;int err;+ if (!t->writer_set) {+ pr_err("tpm: register policy requires the NV writer public key");+ return -EACCES;+ }err = tpm_policy_session_start(t, session);if (err)return err;rc = Esys_PolicyNvWritten(t->esys, *session, ESYS_TR_NONE, ESYS_TR_NONE,ESYS_TR_NONE, init ? TPM2_NO : TPM2_YES);if (rc == TSS2_RC_SUCCESS && init) {- TPM2B_DIGEST live = { .size = 0 };+ TPM2B_DIGEST live = {};TPML_PCR_SELECTION sel;pcr_selection(pcr_mask, &sel);@@ -601,6 +640,14 @@ static int policy_session_register(struct shirudo_tpm *t, bool init,rc = Esys_PolicyOR(t->esys, *session, ESYS_TR_NONE,ESYS_TR_NONE, ESYS_TR_NONE, &branches);}+ if (rc == TSS2_RC_SUCCESS) {+ err = policy_writer_signed(t, *session, index, event);+ if (err) {+ session_flush(t, *session);+ *session = ESYS_TR_NONE;+ return err;+ }+ }if (rc != TSS2_RC_SUCCESS) {if (rc_is(rc, TPM2_RC_VALUE) && init)pr_err("tpm: the anchoring PCR moved; the register "@@ -612,20 +659,16 @@ static int policy_session_register(struct shirudo_tpm *t, bool init,*session = ESYS_TR_NONE;return -EACCES;}- rc = Esys_PolicyGetDigest(t->esys, *session, ESYS_TR_NONE,- ESYS_TR_NONE, ESYS_TR_NONE, &digest);- tpm_policy_or(branch_written, branch_init, expected);- if (rc != TSS2_RC_SUCCESS || digest->size != 32 ||- memcmp(digest->buffer, expected, 32) != 0) {- pr_err("tpm: register policy digest does not match the "- "computed policy (rc=0x%08x)", (__u32)rc);- Esys_Free(digest);+ err = tpm_register_policy_final(branch_written, branch_init, t->writer_public, expected);+ if (err)+ pr_err("tpm: compute signed register policy: %s", strerror(-err));+ else+ err = tpm_policy_session_finish(t, *session, expected);+ if (err) {session_flush(t, *session);*session = ESYS_TR_NONE;- return -EPROTO;}- Esys_Free(digest);- return 0;+ return err;}static int nv_extend_session(struct shirudo_tpm *t, __u32 index,@@ -660,7 +703,7 @@ int tpm_nv_extend_first(struct shirudo_tpm *t, __u32 index,ESYS_TR session = ESYS_TR_NONE;int err;- err = policy_session_register(t, true, pcr_mask, branch_written,+ err = policy_session_register(t, true, index, event, pcr_mask, branch_written,branch_init, &session);if (err)return err;@@ -677,7 +720,7 @@ int tpm_nv_extend(struct shirudo_tpm *t, __u32 index,ESYS_TR session = ESYS_TR_NONE;int err;- err = policy_session_register(t, false, 0, branch_written,+ err = policy_session_register(t, false, index, event, 0, branch_written,branch_init, &session);if (err)return err;diff --git a/util/tpm.h b/util/tpm.hindex 477ee2b2..7527442a 100644--- a/util/tpm.h+++ b/util/tpm.h@@ -62,6 +62,8 @@ struct tpm_nv_info {* the first write of a boot the init branch, which TPM2_PolicyPCR* only satisfies while the anchoring PCR still holds the value the* policy was computed from, every later one the written branch.+ * Both branches require the kernel-held writer's command-bound+ * signature; extending requires nv_set_writer first.*/int tpm_nv_info(struct shirudo_tpm *t, __u32 index,struct tpm_nv_info *info);diff --git a/util/tpm_wire.c b/util/tpm_wire.cindex f60046f9..ceddd997 100644--- a/util/tpm_wire.c+++ b/util/tpm_wire.c@@ -255,8 +255,7 @@ int tpm_register_policy(__u32 pcr_mask,tpm_policy_nv_written(zero, false, unwritten);sha256_buffer(pcr_values, 32 * n_values, pcr_digest);tpm_policy_pcr(unwritten, pcr_mask, pcr_digest, branch_init);- tpm_policy_or(branch_written, branch_init, policy);- return 0;+ return tpm_register_policy_final(branch_written, branch_init, writer_public, policy);}void tpm_nv_name(__u32 index, __u32 attrs,diff --git a/util/tpm_wire.h b/util/tpm_wire.hindex 37735fbe..aaa6600f 100644--- a/util/tpm_wire.h+++ b/util/tpm_wire.h@@ -98,8 +98,9 @@ void tpm_policy_or(const __u8 a[SHIRUDO_TPM_DIGEST_LEN],/** The register's write policy from the values the binding PCRs held* at binding time, given in PCR order: PolicyOR(PolicyNvWritten(YES),- * PolicyNvWritten(NO) + PolicyPCR(mask, SHA-256(values))). The two- * branch digests are what a session has to present to PolicyOR.+ * PolicyNvWritten(NO) + PolicyPCR(mask, SHA-256(values))), followed by+ * PolicySigned and PolicyCommandCode(NV_Extend). The two branch+ * digests are what a session has to present to PolicyOR.*/int tpm_register_policy(__u32 pcr_mask,const __u8 *pcr_values, size_t n_values,