eBPF-based security platform
testing: Check the TPM writer and NV index guard
KP Singh4631997fa38c
diff --git a/Makefile.shirudo b/Makefile.shirudoindex 048abaf6..abbac3fc 100644--- a/Makefile.shirudo+++ b/Makefile.shirudo@@ -628,6 +628,7 @@ TEST_HELPERS := $(VERITY_TEST_HELPERS) \testing/helper/test-upatch-link-lockdown \testing/helper/test-exec-churn \testing/upatch/kernel-obs/exec/exec-paths+TEST_HELPERS += testing/helper/test-nv-writerTEST_HELPERS += testing/helper/test-keyring-sealTEST_HELPERS += testing/helper/test-tpm-preopeneddiff --git a/kernel/0002-tpm-Let-LSMs-inspect-userspace-commands.patch b/kernel/0002-tpm-Let-LSMs-inspect-userspace-commands.patchnew file mode 100644index 00000000..8f1f273c--- /dev/null+++ b/kernel/0002-tpm-Let-LSMs-inspect-userspace-commands.patch@@ -0,0 +1,139 @@+From b0cbdcfd2176e8e1056334085b6da92bc0dd0dc2 Mon Sep 17 00:00:00 2001+From: KP Singh <[email protected]>+Date: Wed, 28 Oct 2026 16:26:25 +0100+Subject: [PATCH] tpm: Let LSMs inspect userspace commands++Shirudo keeps the key that authorizes its TPM NV writes inside the TPM.+Another process can recreate that key and ask the TPM to sign. An LSM+therefore needs the target index of an NV_Extend command to decide+whether the caller may change Shirudo's register. A check made when the+TPM device is opened would miss inherited descriptors.++Call a new tpm_command hook after copying the command from userspace and+validating its header. Pass the device file, copied command, and the+header's declared length while the buffer is locked. The hook runs+before both direct transmission and nonblocking queueing. The declared+length keeps any trailing write bytes out of the policy decision.++Link: https://github.com/shirudo-dev/shirudo/pull/57+Signed-off-by: KP Singh <[email protected]>+---+ drivers/char/tpm/tpm-dev-common.c | 13 +++++++++++--+ include/linux/lsm_hook_defs.h | 2 +++ include/linux/security.h | 8 +++++++++ security/security.c | 18 +++++++++++++++++++ 4 files changed, 39 insertions(+), 2 deletions(-)++diff --git a/drivers/char/tpm/tpm-dev-common.c b/drivers/char/tpm/tpm-dev-common.c+index 6569212dc6b8..15b72b4a0885 100644+--- a/drivers/char/tpm/tpm-dev-common.c++++ b/drivers/char/tpm/tpm-dev-common.c+@@ -13,6 +13,7 @@+ * Device file system interface to the TPM+ */+ #include <linux/poll.h>++#include <linux/security.h>+ #include <linux/slab.h>+ #include <linux/uaccess.h>+ #include <linux/workqueue.h>+@@ -174,6 +175,7 @@ ssize_t tpm_common_write(struct file *file, const char __user *buf,+ size_t size, loff_t *off)+ {+ struct file_priv *priv = file->private_data;++ struct tpm_header *header;+ int ret = 0;++ if (size > TPM_BUFSIZE)+@@ -196,12 +198,19 @@ ssize_t tpm_common_write(struct file *file, const char __user *buf,+ goto out;+ }++- if (size < 6 ||+- size < be32_to_cpu(*((__be32 *)(priv->data_buffer + 2)))) {++ header = (struct tpm_header *)priv->data_buffer;++ if (size < sizeof(*header) ||++ be32_to_cpu(header->length) < sizeof(*header) ||++ size < be32_to_cpu(header->length)) {+ ret = -EINVAL;+ goto out;+ }+++ ret = security_tpm_command(file, priv->data_buffer,++ be32_to_cpu(header->length));++ if (ret)++ goto out;+++ priv->response_length = 0;+ priv->response_read = false;+ *off = 0;+diff --git a/include/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h+index 87d9d06710cb..90209bf5cf6f 100644+--- a/include/linux/lsm_hook_defs.h++++ b/include/linux/lsm_hook_defs.h+@@ -189,6 +189,8 @@ LSM_HOOK(int, 0, inode_setintegrity, const struct inode *inode,+ LSM_HOOK(int, 0, kernfs_init_security, struct kernfs_node *kn_dir,+ struct kernfs_node *kn)+ LSM_HOOK(int, 0, file_permission, struct file *file, int mask)++LSM_HOOK(int, 0, tpm_command, struct file *file,++ const u8 *command, size_t command_len)+ LSM_HOOK(int, 0, file_alloc_security, struct file *file)+ LSM_HOOK(void, LSM_RET_VOID, file_release, struct file *file)+ LSM_HOOK(void, LSM_RET_VOID, file_free_security, struct file *file)+diff --git a/include/linux/security.h b/include/linux/security.h+index 40831fab5470..f017412d5adb 100644+--- a/include/linux/security.h++++ b/include/linux/security.h+@@ -475,6 +475,8 @@ int security_inode_setintegrity(const struct inode *inode,+ int security_kernfs_init_security(struct kernfs_node *kn_dir,+ struct kernfs_node *kn);+ int security_file_permission(struct file *file, int mask);++int security_tpm_command(struct file *file, const u8 *command,++ size_t command_len);+ int security_file_alloc(struct file *file);+ void security_file_release(struct file *file);+ void security_file_free(struct file *file);+@@ -1152,6 +1154,12 @@ static inline int security_file_permission(struct file *file, int mask)+ return 0;+ }+++static inline int security_tpm_command(struct file *file,++ const u8 *command, size_t command_len)++{++ return 0;++}+++ static inline int security_file_alloc(struct file *file)+ {+ return 0;+diff --git a/security/security.c b/security/security.c+index f6583d507395..86636c894ebe 100644+--- a/security/security.c++++ b/security/security.c+@@ -2414,6 +2414,24 @@ int security_file_permission(struct file *file, int mask)+ return call_int_hook(file_permission, file, mask);+ }+++/**++ * security_tpm_command() - Check a userspace TPM command++ * @file: TPM device file++ * @command: TPM command copied from userspace++ * @command_len: length declared in the validated command header++ *++ * Check a command before the TPM driver queues or sends it. The command++ * remains in the device buffer until this call returns.++ *++ * Return: Returns 0 if permission is granted.++ */++int security_tpm_command(struct file *file, const u8 *command,++ size_t command_len)++{++ return call_int_hook(tpm_command, file, command, command_len);++}++EXPORT_SYMBOL_GPL(security_tpm_command);+++ /**+ * security_file_alloc() - Allocate and init a file's LSM blob+ * @file: the file+--+2.53.0+diff --git a/testing/fixtures/nv-writer-fault.bpf.c b/testing/fixtures/nv-writer-fault.bpf.cdeleted file mode 100644index 44d98f80..00000000--- a/testing/fixtures/nv-writer-fault.bpf.c+++ /dev/null@@ -1,72 +0,0 @@-// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause-/* Copyright (c) 2026 Authors of shirudo */--#include "vmlinux.h"-#include <bpf/bpf_helpers.h>-#include <bpf/bpf_tracing.h>-#include <bpf/bpf_core_read.h>--#include "nv-writer-fault.h"--#define EIO 5-#define EBADMSG 74--struct {- __uint(type, BPF_MAP_TYPE_ARRAY);- __uint(max_entries, 1);- __type(key, __u32);- __type(value, struct nv_writer_fault);-} fault SEC(".maps");--static __always_inline struct nv_writer_fault *current_fault(void)-{- struct nv_writer_fault *state;- __u32 zero = 0;-- state = bpf_map_lookup_elem(&fault, &zero);- if (!state || state->pid != bpf_get_current_pid_tgid() >> 32)- return NULL;- return state;-}--SEC("lsm/key_alloc")-int BPF_PROG(fail_writer_import, struct key *key, const struct cred *cred,- unsigned long flags, int ret)-{- char description[sizeof("shirudo.nv-writer") + 1] = {};- struct nv_writer_fault *state;-- if (ret)- return ret;- state = current_fault();- if (!state)- return 0;- if (bpf_probe_read_kernel_str(description, sizeof(description),- BPF_CORE_READ(key, description)) !=- sizeof("shirudo.nv-writer") ||- __builtin_memcmp(description, "shirudo.nv-writer", sizeof("shirudo.nv-writer")))- return 0;- state->imports++;- if (!state->fail_import)- return 0;- state->failures++;- return -EBADMSG;-}--SEC("lsm/bpf")-int BPF_PROG(fail_writer_map, int cmd, union bpf_attr *attr,- unsigned int size, bool kernel, int ret)-{- struct nv_writer_fault *state;-- if (ret)- return ret;- state = current_fault();- if (!state || !state->imports || kernel || !state->command ||- state->command != (__u32)cmd)- return 0;- state->failures++;- return -EIO;-}--char _license[] SEC("license") = "Dual BSD/GPL";diff --git a/testing/fixtures/nv-writer-fault.h b/testing/fixtures/nv-writer-fault.hdeleted file mode 100644index e81648f8..00000000--- a/testing/fixtures/nv-writer-fault.h+++ /dev/null@@ -1,14 +0,0 @@-/* SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause */-/* Copyright (c) 2026 Authors of shirudo */-#ifndef SHIRUDO_TEST_NV_WRITER_FAULT_H-#define SHIRUDO_TEST_NV_WRITER_FAULT_H--struct nv_writer_fault {- __u32 pid;- __u32 command;- __u32 fail_import;- __u32 imports;- __u32 failures;-};--#endif /* SHIRUDO_TEST_NV_WRITER_FAULT_H */diff --git a/testing/helper/test-nv-writer-cleanup.c b/testing/helper/test-nv-writer-cleanup.cdeleted file mode 100644index 2d6ac9d2..00000000--- a/testing/helper/test-nv-writer-cleanup.c+++ /dev/null@@ -1,257 +0,0 @@-// SPDX-License-Identifier: BSD-2-Clause-/* Copyright (c) 2026 Authors of shirudo */--#include <linux/keyctl.h>--#include "../../builtin-init.c"-#include "../fixtures/nv-writer-fault.h"--const __u8 *__wrap_shirudo_image_runtime_root(void);--/* The injected failure precedes runtime mounting and guard attachment. */-const __u8 *__wrap_shirudo_image_runtime_root(void)-{- static const __u8 root[32] = { 1 };-- return root;-}--struct ring_snapshot {- key_serial_t keys[256];- long bytes;-};--static int serial_order(const void *a, const void *b)-{- key_serial_t right = *(const key_serial_t *)b;- key_serial_t left = *(const key_serial_t *)a;-- return (left > right) - (left < right);-}--static int snapshot(key_serial_t ring, struct ring_snapshot *out)-{- out->bytes = syscall(__NR_keyctl, KEYCTL_READ, ring, out->keys,- sizeof(out->keys), 0);- if (out->bytes < 0)- return -errno;- if ((size_t)out->bytes > sizeof(out->keys) ||- out->bytes % sizeof(out->keys[0]))- return -EOVERFLOW;- qsort(out->keys, out->bytes / sizeof(out->keys[0]),- sizeof(out->keys[0]), serial_order);- return 0;-}--static int unchanged(key_serial_t ring, const struct ring_snapshot *before)-{- struct ring_snapshot after = {};- int rc;-- rc = snapshot(ring, &after);- if (rc)- return rc;- if (before->bytes != after.bytes ||- memcmp(before->keys, after.keys, before->bytes)) {- fprintf(stderr, "keyring %d changed: before %ld bytes, after %ld bytes\n",- ring, before->bytes, after.bytes);- return -EUCLEAN;- }- return 0;-}--static int contains(key_serial_t parent, key_serial_t ring)-{- struct ring_snapshot state = {};- size_t i;- int rc;-- rc = snapshot(parent, &state);- if (rc)- return rc;- for (i = 0; i < (size_t)state.bytes / sizeof(state.keys[0]); i++)- if (state.keys[i] == ring)- return 0;- return -ENOKEY;-}--static int enroll(const char *path)-{- __u8 *der = NULL;- size_t len = 0;- int rc;-- rc = keys_read_der(path, &der, &len);- if (rc)- return rc;- rc = keyring_bpf_add_cert(der, len);- if (rc >= 0)- rc = keyring_bpf_seal();- /* init_lsm records the one config key boot keys leave there. */- if (!rc)- rc = shirudo_keyring_dm_verity_add_cert(der, len);- if (rc >= 0)- rc = shirudo_keyring_dm_verity_seal();- xfree(der, len);- return rc;-}--static int exercise(const char *mode, const char *object)-{- struct bpf_link *import_link = NULL, *map_link = NULL;- struct ring_snapshot user = {}, session = {};- __u8 public[SHIRUDO_TPM_NV_RSA_BYTES] = {};- __u8 signature[SHIRUDO_TPM_NV_RSA_BYTES];- key_serial_t ring = -1, writer = -1;- struct nv_writer_fault state = {};- struct bpf_object *obj = NULL;- struct bpf_program *program;- int rc, result, fd = -1;- __u8 digest[32] = {};- __u32 zero = 0;-- rc = snapshot(KEY_SPEC_USER_KEYRING, &user);- if (!rc)- rc = snapshot(KEY_SPEC_SESSION_KEYRING, &session);- if (rc)- return rc;- if (object) {- state.pid = getpid();- state.fail_import = !strcmp(mode, "import");- if (!strcmp(mode, "update"))- state.command = BPF_MAP_UPDATE_ELEM;- else if (!strcmp(mode, "freeze"))- state.command = BPF_MAP_FREEZE;- obj = bpf_object__open_file(object, NULL);- rc = libbpf_get_error(obj);- if (rc)- return rc;- rc = bpf_object__load(obj);- if (rc)- goto out;- fd = bpf_object__find_map_fd_by_name(obj, "fault");- if (fd < 0 || bpf_map_update_elem(fd, &zero, &state, BPF_ANY)) {- rc = fd < 0 ? fd : -errno;- goto out;- }- program = bpf_object__find_program_by_name(obj, "fail_writer_import");- if (!program) {- rc = -ENOENT;- goto out;- }- import_link = bpf_program__attach_lsm(program);- rc = libbpf_get_error(import_link);- if (rc)- goto out;- program = bpf_object__find_program_by_name(obj, "fail_writer_map");- if (!program) {- rc = -ENOENT;- goto out;- }- map_link = bpf_program__attach_lsm(program);- rc = libbpf_get_error(map_link);- if (rc)- goto out;- }- if (state.command) {- result = init_lsm();- rc = result == -EIO ? 0 : -EPROTO;- if (rc)- fprintf(stderr, "init_lsm returned %d, expected -EIO\n", result);- } else {- result = nv_writer_create(&ring, &writer, public);- if (!strcmp(mode, "success")) {- rc = result;- if (!rc)- rc = contains(KEY_SPEC_USER_KEYRING, ring);- if (!rc)- rc = contains(KEY_SPEC_SESSION_KEYRING, ring);- if (!rc)- rc = nv_writer_sign_key(writer, digest, signature);- nv_writer_destroy(ring);- } else {- rc = result == -EBADMSG && !ring && !writer ? 0 : -EPROTO;- if (rc)- fprintf(stderr, "import returned %d, ring %d, writer %d\n",- result, ring, writer);- }- }- if (fd >= 0) {- if (bpf_map_lookup_elem(fd, &zero, &state)) {- rc = -errno;- goto out;- }- if (state.imports != 1 || state.failures != 1) {- fprintf(stderr, "fault did not fire exactly once: imports %u, failures %u\n",- state.imports, state.failures);- rc = -EPROTO;- }- }- result = unchanged(KEY_SPEC_USER_KEYRING, &user);- if (result)- rc = result;- result = unchanged(KEY_SPEC_SESSION_KEYRING, &session);- if (result)- rc = result;- if (state.command && (!access(SHIRUDO_IDENTITY_PIN, F_OK) ||- !access(SHIRUDO_LSM_LINK_PIN, F_OK)))- rc = -EUCLEAN;-out:- bpf_link__destroy(map_link);- bpf_link__destroy(import_link);- bpf_object__close(obj);- return rc;-}--int main(int argc, char **argv)-{- const char *vm = getenv("SHIRUDO_TEST_REGISTER_VM");- key_serial_t sentinel;- int rc, cleanup;- long ret;-- log_init();- if (!vm || strcmp(vm, "1") || getuid() || argc < 2 ||- !access(SHIRUDO_LSM_LINK_PIN, F_OK)) {- fprintf(stderr, "requires an opted-in, uninitialized disposable VM\n");- return 2;- }- if (argc == 3 && !strcmp(argv[1], "enroll")) {- rc = enroll(argv[2]);- goto done;- }- if (!((argc == 2 && (!strcmp(argv[1], "no-pkcs8") ||- !strcmp(argv[1], "success"))) ||- (argc == 3 && (!strcmp(argv[1], "import") ||- !strcmp(argv[1], "update") ||- !strcmp(argv[1], "freeze"))))) {- fprintf(stderr, "usage: %s enroll CERT | success | no-pkcs8 | {import,update,freeze} BPF_OBJECT\n",- argv[0]);- return 2;- }- ret = syscall(__NR_keyctl, KEYCTL_JOIN_SESSION_KEYRING, NULL, 0, 0, 0);- if (ret < 0) {- rc = -errno;- goto done;- }- ret = syscall(__NR_add_key, "keyring", "shirudo.nv-test.keep", NULL, 0,- KEY_SPEC_SESSION_KEYRING);- if (ret < 0) {- rc = -errno;- goto done;- }- sentinel = (key_serial_t)ret;- ret = syscall(__NR_keyctl, KEYCTL_LINK, sentinel, KEY_SPEC_USER_KEYRING, 0, 0);- if (ret < 0) {- rc = -errno;- goto done;- }- rc = exercise(argv[1], argc == 3 ? argv[2] : NULL);- cleanup = keyring_unlink_key(KEY_SPEC_USER_KEYRING, sentinel);- if (cleanup)- rc = cleanup;-done:- if (rc)- fprintf(stderr, "NV writer cleanup test: %s\n", strerror(-rc));- return rc ? 1 : 0;-}diff --git a/testing/helper/test-nv-writer.c b/testing/helper/test-nv-writer.cindex 48f5f9d7..81961a7e 100644--- a/testing/helper/test-nv-writer.c+++ b/testing/helper/test-nv-writer.c@@ -2,107 +2,236 @@/* Copyright (c) 2026 Authors of shirudo */#include <errno.h>-#include <linux/keyctl.h>+#include <fcntl.h>#include <stdio.h>#include <string.h>-#include <sys/syscall.h>+#include <sys/wait.h>#include <unistd.h>#include <bpf/bpf.h>-#include "identity.h"+#include "tpm_internal.h"#include "eventlog.h"-#include "nv_writer.h"+#include "identity.h"#include "paths.h"-int main(int argc, char **argv)+static int public_matches_init(void){- __u8 data[SHIRUDO_TPM_NV_RSA_BYTES] = {};- __u8 signature[SHIRUDO_TPM_NV_RSA_BYTES];- struct keyctl_pkey_params params = {};struct bpf_obj_get_opts opts = {.sz = sizeof(opts),.file_flags = BPF_F_RDONLY,};+ struct shirudo_eventlog_init rec;struct shirudo_identity id = {};- const char *operation;- key_serial_t target;__u32 zero = 0;- int fd, cmd;- long ret;+ int fd, rc;- if (argc != 2)- return 2;fd = bpf_obj_get_opts(SHIRUDO_IDENTITY_PIN, &opts);if (fd < 0) {perror("open read-only identity");- return 2;+ return 1;}- ret = bpf_map_lookup_elem(fd, &zero, &id);+ rc = bpf_map_lookup_elem(fd, &zero, &id);close(fd);- if (ret || id.nv_writer_ring <= 0 ||- id.nv_writer_key <= 0) {- fprintf(stderr, "cannot read NV writer identity\n");- return 2;+ if (rc || eventlog_boot_init(&rec) ||+ memcmp(id.nv_writer_public, rec.writer_public,+ sizeof(id.nv_writer_public))) {+ fprintf(stderr, "writer modulus differs between identity and init record\n");+ return 1;}- if (!strcmp(argv[1], "public")) {- struct shirudo_eventlog_init rec;+ return 0;+}++static int sign_once(ESYS_CONTEXT *esys, ESYS_TR key)+{+ TPMT_TK_HASHCHECK validation = {+ .tag = TPM2_ST_HASHCHECK,+ .hierarchy = TPM2_RH_NULL,+ };+ TPMT_SIG_SCHEME scheme = { .scheme = TPM2_ALG_ECDSA };+ TPMT_SIGNATURE *signature = NULL;+ TPM2B_DIGEST digest = { .size = 32 };+ TSS2_RC rc;- if (eventlog_boot_init(&rec) ||- memcmp(id.nv_writer_public, rec.writer_public, sizeof(data))) {- fprintf(stderr, "writer modulus differs between identity and init record\n");- return 1;- }+ scheme.details.ecdsa.hashAlg = TPM2_ALG_SHA256;+ memset(digest.buffer, 0x5a, digest.size);+ rc = Esys_Sign(esys, key, ESYS_TR_PASSWORD, ESYS_TR_NONE,+ ESYS_TR_NONE, &digest, &scheme, &validation, &signature);+ if (rc == TSS2_RC_SUCCESS && signature) {+ Esys_Free(signature);return 0;}- if (!strcmp(argv[1], "sign")) {- params.key_id = id.nv_writer_key;- params.in_len = 32;- params.out_len = sizeof(signature);- ret = syscall(__NR_keyctl, KEYCTL_PKEY_SIGN, ¶ms,- "enc=pkcs1 hash=sha256", data, signature);- if (ret == -1 && (errno == EACCES || errno == ENOKEY))- return 0;- fprintf(stderr, "writer signing was not denied: %ld/%d\n", ret, errno);- return 1;- }- if (!strcmp(argv[1], "sign-shared")) {- int rc;+ Esys_Free(signature);+ fprintf(stderr, "unrelated TPM2_Sign failed: rc=0x%08x\n", (__u32)rc);+ return 1;+}- rc = nv_writer_sign_key(id.nv_writer_key, data, signature);- if (rc == -EACCES || rc == -ENOKEY)- return 0;- fprintf(stderr, "shared writer signing was not denied: %d\n", rc);- return 1;+static int sign_check(const char *device, bool inherited)+{+ TPM2B_SENSITIVE_CREATE sensitive = {};+ TPML_PCR_SELECTION creation_pcr = {};+ TPM2B_PUBLIC in_public = {};+ TPM2B_PUBLIC *out_public = NULL;+ TSS2_TCTI_CONTEXT *tcti = NULL;+ TPM2B_DATA outside = {};+ ESYS_CONTEXT *esys = NULL;+ ESYS_TR key = ESYS_TR_NONE;+ TSS2_RC trc;+ int status, rc = 1;+ pid_t pid;++ trc = Tss2_TctiLdr_Initialize(device, &tcti);+ if (trc)+ goto tpm_error;+ trc = Esys_Initialize(&esys, tcti, NULL);+ if (trc)+ goto tpm_error;+ in_public.publicArea.type = TPM2_ALG_ECC;+ in_public.publicArea.nameAlg = TPM2_ALG_SHA256;+ in_public.publicArea.objectAttributes =+ TPMA_OBJECT_FIXEDTPM | TPMA_OBJECT_FIXEDPARENT |+ TPMA_OBJECT_SENSITIVEDATAORIGIN | TPMA_OBJECT_USERWITHAUTH |+ TPMA_OBJECT_SIGN_ENCRYPT;+ in_public.publicArea.parameters.eccDetail.symmetric.algorithm =+ TPM2_ALG_NULL;+ in_public.publicArea.parameters.eccDetail.scheme.scheme =+ TPM2_ALG_ECDSA;+ in_public.publicArea.parameters.eccDetail.scheme.details.ecdsa.hashAlg =+ TPM2_ALG_SHA256;+ in_public.publicArea.parameters.eccDetail.curveID = TPM2_ECC_NIST_P256;+ in_public.publicArea.parameters.eccDetail.kdf.scheme = TPM2_ALG_NULL;+ trc = Esys_CreatePrimary(esys, ESYS_TR_RH_NULL, ESYS_TR_PASSWORD,+ ESYS_TR_NONE, ESYS_TR_NONE, &sensitive,+ &in_public, &outside, &creation_pcr, &key,+ &out_public, NULL, NULL, NULL);+ if (trc)+ goto tpm_error;+ if (!inherited) {+ rc = sign_once(esys, key);+ goto out;}- operation = argv[1];- target = id.nv_writer_key;- if (!strncmp(operation, "ring-", 5)) {- target = id.nv_writer_ring;- operation += 5;+ pid = fork();+ if (pid < 0) {+ perror("fork");+ goto out;}- if (!strcmp(operation, "private-read"))- cmd = KEYCTL_READ;- else if (!strcmp(operation, "update"))- cmd = KEYCTL_UPDATE;- else if (!strcmp(operation, "clear"))- cmd = KEYCTL_CLEAR;- else if (!strcmp(operation, "revoke"))- cmd = KEYCTL_REVOKE;- else if (!strcmp(operation, "invalidate"))- cmd = KEYCTL_INVALIDATE;- else if (!strcmp(operation, "setperm"))- cmd = KEYCTL_SETPERM;- else- return 2;+ if (!pid) {+ rc = sign_once(esys, key);+ fflush(stderr);+ _exit(rc);+ }+ if (waitpid(pid, &status, 0) != pid) {+ perror("waitpid");+ goto out;+ }+ if (!WIFEXITED(status) || WEXITSTATUS(status))+ goto out;+ rc = 0;+ goto out;+tpm_error:+ fprintf(stderr, "prepare TPM signing request on %s: rc=0x%08x\n",+ device, (__u32)trc);+out:+ Esys_Free(out_public);+ if (key != ESYS_TR_NONE)+ Esys_FlushContext(esys, key);+ Esys_Finalize(&esys);+ Tss2_TctiLdr_Finalize(&tcti);+ return rc;+}++enum extend_probe {+ EXTEND_TARGET,+ EXTEND_OTHER,+ EXTEND_SHORT,+};++static int write_extend(int fd, const char *device, enum extend_probe probe)+{+ __u8 command[18] = { 0x80, 0x01 };+ __u32 index = SHIRUDO_NV_INDEX;+ size_t size = sizeof(command);+ ssize_t written;+ int saved_errno;++ if (probe == EXTEND_OTHER)+ index++;+ if (probe == EXTEND_SHORT)+ size = 10;+ tpm_put32(command + 2, (__u32)size);+ tpm_put32(command + 6, SHIRUDO_TPM_CC_NV_EXTEND);+ tpm_put32(command + 10, index);+ tpm_put32(command + 14, index);errno = 0;- ret = syscall(__NR_keyctl, cmd, target,- cmd == KEYCTL_SETPERM ? 0x00030000L : (long)data,- sizeof(data), 0);- explicit_bzero(data, sizeof(data));- if (ret == -1 && (errno == EACCES || errno == ENOKEY))+ written = write(fd, command, size);+ saved_errno = errno;+ if (probe == EXTEND_OTHER && written == (ssize_t)size)+ return 0;+ if (probe != EXTEND_OTHER && written == -1 &&+ saved_errno == EACCES)return 0;- fprintf(stderr, "writer operation %s was not refused: %ld/%d\n",- argv[1], ret, errno);+ fprintf(stderr, "%s NV_Extend 0x%08x: wrote %zd/%zu, errno=%d\n",+ device, index, written, size, saved_errno);return 1;}++static int raw_extend_check(const char *device, enum extend_probe probe,+ bool nonblock, bool inherited)+{+ int flags = O_RDWR | O_CLOEXEC;+ int status, rc;+ pid_t pid;+ int fd;++ if (strcmp(device, "/dev/tpmrm0") && strcmp(device, "/dev/tpm0"))+ return 2;+ if (nonblock)+ flags |= O_NONBLOCK;+ fd = open(device, flags);+ if (fd < 0) {+ perror(device);+ return 1;+ }+ if (!inherited) {+ rc = write_extend(fd, device, probe);+ close(fd);+ return rc;+ }+ pid = fork();+ if (pid < 0) {+ perror("fork");+ close(fd);+ return 1;+ }+ if (!pid) {+ rc = write_extend(fd, device, probe);+ _exit(rc);+ }+ rc = waitpid(pid, &status, 0) == pid &&+ WIFEXITED(status) && WEXITSTATUS(status) == 0 ? 0 : 1;+ close(fd);+ return rc;+}++int main(int argc, char **argv)+{+ if (argc == 2 && !strcmp(argv[1], "public"))+ return public_matches_init();+ if (argc != 3)+ return 2;+ if (!strcmp(argv[1], "sign-allowed"))+ return sign_check(argv[2], false);+ if (!strcmp(argv[1], "sign-allowed-inherited"))+ return sign_check(argv[2], true);+ if (!strcmp(argv[1], "raw-extend"))+ return raw_extend_check(argv[2], EXTEND_TARGET, false, false);+ if (!strcmp(argv[1], "raw-extend-nonblock"))+ return raw_extend_check(argv[2], EXTEND_TARGET, true, false);+ if (!strcmp(argv[1], "raw-extend-inherited"))+ return raw_extend_check(argv[2], EXTEND_TARGET, false, true);+ if (!strcmp(argv[1], "raw-extend-other"))+ return raw_extend_check(argv[2], EXTEND_OTHER, true, false);+ if (!strcmp(argv[1], "raw-extend-short"))+ return raw_extend_check(argv[2], EXTEND_SHORT, false, false);+ return 2;+}diff --git a/testing/helper/test-tpm-preopened.c b/testing/helper/test-tpm-preopened.cindex 57fc2166..da34823a 100644--- a/testing/helper/test-tpm-preopened.c+++ b/testing/helper/test-tpm-preopened.c@@ -1,6 +1,7 @@// SPDX-License-Identifier: BSD-2-Clause/* Copyright (c) 2026 Authors of shirudo */+#include <errno.h>#include <stdio.h>#include <string.h>#include <sys/wait.h>@@ -29,6 +30,7 @@ static int unauthorized_extend(struct shirudo_tpm *tpm)__u8 before[32], after[32];ESYS_TR nv = ESYS_TR_NONE;TSS2_RC trc;+ int saved_errno;int rc = 1;if (eventlog_boot_init(&rec)) {@@ -60,11 +62,13 @@ static int unauthorized_extend(struct shirudo_tpm *tpm)if (tpm_failed(Esys_PolicyOR(tpm->esys, session, ESYS_TR_NONE, ESYS_TR_NONE,ESYS_TR_NONE, &branches), "PolicyOR"))goto out;+ errno = 0;trc = Esys_NV_Extend(tpm->esys, nv, nv, session, ESYS_TR_NONE,ESYS_TR_NONE, &event);- if (trc != (TPM2_RC_POLICY_FAIL | TPM2_RC_S | TPM2_RC_1)) {- fprintf(stderr, "unsigned NV_Extend: expected policy failure, got 0x%08x\n",- (__u32)trc);+ saved_errno = errno;+ if (trc != TSS2_TCTI_RC_IO_ERROR || saved_errno != EACCES) {+ fprintf(stderr, "unsigned NV_Extend: expected LSM denial, got 0x%08x/%d\n",+ (__u32)trc, saved_errno);goto out;}if (tpm_nv_read(tpm, SHIRUDO_NV_INDEX, after))@@ -81,7 +85,7 @@ out:if (nv != ESYS_TR_NONE && tpm_failed(Esys_TR_Close(tpm->esys, &nv), "TR_Close"))rc = 1;if (!rc)- puts("inherited-TPM: unsigned NV_Extend rejected by TPM; value unchanged");+ puts("inherited-TPM: unsigned NV_Extend rejected by LSM; value unchanged");return rc;}diff --git a/testing/tamperproof/t1131-pr-set-mm-identity.py b/testing/tamperproof/t1131-pr-set-mm-identity.pyindex 374517de..cb5213f3 100644--- a/testing/tamperproof/t1131-pr-set-mm-identity.py+++ b/testing/tamperproof/t1131-pr-set-mm-identity.py@@ -75,13 +75,13 @@ class ShirudoIdentity(ctypes.Structure):("n_keys", ctypes.c_uint32),("key_serials", ctypes.c_int32 * 16),("runtime_root", ctypes.c_uint8 * 32),- ("nv_writer_ring", ctypes.c_int32),- ("nv_writer_key", ctypes.c_int32),+ ("nv_writer_seed", ctypes.c_uint8 * 32),("nv_writer_public", ctypes.c_uint8 * 384),("ak_name", ctypes.c_uint8 * 34),("ak_name_len", ctypes.c_uint32),("dm_verity_ring", ctypes.c_int32),- ("dm_verity_key", ctypes.c_int32)]+ ("dm_verity_key", ctypes.c_int32),+ ("nv_index", ctypes.c_uint32)]def assert_frozen_runtime():@@ -114,6 +114,7 @@ def assert_frozen_runtime():value = ShirudoIdentity.from_buffer_copy(buffer.raw)assert info.value_size == ctypes.sizeof(ShirudoIdentity), info.value_sizeassert any(value.runtime_root), "runtime hash missing"+ assert value.nv_index, "NV index missing"executable = os.path.realpath(SHIRUDO)runtime = os.path.realpath(RUNTIME)assert os.path.commonpath((executable, runtime)) == runtime, executablediff --git a/testing/tpm/t0034-register.sh b/testing/tpm/t0034-register.shindex 87c665ac..0110af18 100644--- a/testing/tpm/t0034-register.sh+++ b/testing/tpm/t0034-register.sh@@ -2,7 +2,7 @@# SPDX-License-Identifier: BSD-2-Clause# Copyright (c) 2026 Authors of shirudo#-# t0034 -- register lifecycle with a real kernel writer in a pre-init VM.+# t0034 -- register lifecycle with a TPM-held writer in a pre-init VM.cd "$(dirname "$0")/..". ./test-lib.sh@@ -11,7 +11,7 @@ R=./helper/test-registerSIM=$(pwd)/helper/tpmsim-cmdS=./helper/test-register-cli. ./tpm/register-lib.sh-[ "$(id -u)" = 0 ] && [ -x "$SIM" ] && [ -x "$R" ] && [ -x "$S" ] || {+[ "$(id -u)" = 0 ] && [ -x "$SIM" ] && [ -x "$R" ] && [ -x "$S" ] && [ -x ./helper/test-nv-cphash ] && [ -x ./helper/test-nv-writer ] || {echo "register VM requires root and the built TPM helpers" >&2exit 1}@@ -42,6 +42,18 @@ ENTER=$(py "import hashlib; print(hashlib.sha256(b\"enter-initrd\").hexdigest())LEAVE=$(py "import hashlib; print(hashlib.sha256(b\"leave-initrd\").hexdigest())")PHASE=$(sha "$Z$ENTER")+test_expect_success 'an unrestricted TPM signing request succeeds before the guard' '+ ./helper/test-nv-writer sign-allowed "$SHIRUDO_TPM_TCTI"+'++test_expect_success 'TPM signatures bind the nonce and exact NV command' '+ ./helper/test-nv-cphash >"$WORK/cphash.log" &&+ grep -qx "PolicySigned: replay and corruption rejected; value unchanged" \+ "$WORK/cphash.log" &&+ grep -qx "cpHash: authorized A; rejected B unchanged; extended A; scratch index removed" \+ "$WORK/cphash.log"+'+test_expect_success 'attest names a register that is not bound yet' '! $S attest --nonce=00 >/dev/null 2>"$WORK/attest-unbound.err" &&grep -qx "attest: register 0x01818E00 is not bound this boot (tpm_error); run shirudo init first" \@@ -74,7 +86,7 @@ test_expect_success 'init binds the register to PCRs 9 and 11 from the initrd anecho "$init" >"$WORK/init" && echo "$name" >"$WORK/name"'-test_expect_success 'predict names the register from the binding values and kernel writer' '+test_expect_success 'predict names the register from the binding values and TPM writer' '$S attest predict --cert="$WORK/keys/cert.der" --bind-pcr=9=$Z \--bind-pcr=11=$PHASE --writer-public="$WRITER" >"$WORK/predict" &&grep -qx "register_name: $(cat "$WORK/name")" "$WORK/predict" &&diff --git a/testing/tpm/t1127-nv-writer.sh b/testing/tpm/t1127-nv-writer.shindex aee26736..3ccf1bf7 100644--- a/testing/tpm/t1127-nv-writer.sh+++ b/testing/tpm/t1127-nv-writer.sh@@ -9,12 +9,16 @@ target_guardtest_skip_all "test-nv-writer not built"[ -x helper/test-tpm-preopened ] ||test_skip_all "test-tpm-preopened not built"+[ -x helper/test-register ] ||+ test_skip_all "test-register not built"[ -x helper/test-nv-cphash ] ||test_skip_all "test-nv-cphash not built"-FIXTURES=${SHIRUDO_TEST_FIXTURES_DIR:?target fixture directory is not set}+[ -n "${SHIRUDO_TEST_FIXTURES_DIR:-}" ] ||+ test_skip_all "target fixture directory is not set"+NAME=shirudo-test-lifecycle-LOAD="$FIXTURES/$NAME.upatch"-UNLOAD="$FIXTURES/$NAME.unload.upatch"+LOAD="$SHIRUDO_TEST_FIXTURES_DIR/$NAME.upatch"+UNLOAD="$SHIRUDO_TEST_FIXTURES_DIR/$NAME.unload.upatch"PIN="/run/shirudo/bpffs/upatches/$NAME/link"[ -s "$LOAD" ] && [ -s "$UNLOAD" ] ||test_skip_all "missing lifecycle fixtures"@@ -22,7 +26,7 @@ PIN="/run/shirudo/bpffs/upatches/$NAME/link"echo "NV writer test requires an unloaded lifecycle fixture" >&2exit 1}-W=$(mktemp -d)+W=$(mktemp -d) || exit 1cleanup() {result=$?@@ -40,8 +44,11 @@ trap 'exit 1' HUP INT TERMwriter_chain() {"$SHIRUDO_BIN" status --json >"$W/status.json" &&python3 - "$W/status.json" <<'PY'-import json, sys-tpm = json.load(open(sys.argv[1]))["tpm"]+import json+import sys++with open(sys.argv[1], encoding="utf-8") as stream:+ tpm = json.load(stream)["tpm"]chain = tpm["chain"]assert len(chain) == 64assert len(bytes.fromhex(chain)) == 32@@ -50,22 +57,44 @@ print(chain)PY}-test_expect_success 'the writer public area is available in the init record' '+test_expect_success 'the TPM writer public key matches the init record' './helper/test-nv-writer public'-test_expect_success 'root cannot read the kernel-held private writer key' '- ./helper/test-nv-writer private-read+test_expect_success 'unrelated TPM signing works on both device nodes' '+ ./helper/test-nv-writer sign-allowed device:/dev/tpmrm0 &&+ ./helper/test-nv-writer sign-allowed device:/dev/tpm0 &&+ ./helper/test-nv-writer sign-allowed-inherited device:/dev/tpmrm0+'++test_expect_success 'untrusted root cannot extend the Shirudo register' '+ ./helper/test-nv-writer raw-extend /dev/tpmrm0 &&+ ./helper/test-nv-writer raw-extend /dev/tpm0+'++test_expect_success 'nonblocking and inherited writes get the same denial' '+ ./helper/test-nv-writer raw-extend-nonblock /dev/tpmrm0 &&+ ./helper/test-nv-writer raw-extend-nonblock /dev/tpm0 &&+ ./helper/test-nv-writer raw-extend-inherited /dev/tpmrm0'-test_expect_success 'root cannot sign while the trusted NV writer remains live' '+test_expect_success 'a short NV_Extend cannot bypass the guard' '+ ./helper/test-nv-writer raw-extend-short /dev/tpmrm0 &&+ ./helper/test-nv-writer raw-extend-short /dev/tpm0+'++test_expect_success 'an unrelated NV index passes the LSM check' '+ ./helper/test-nv-writer raw-extend-other /dev/tpmrm0 &&+ ./helper/test-nv-writer raw-extend-other /dev/tpm0+'++test_expect_success 'trusted loads still measure around a denied extension' 'before=$(writer_chain) &&"$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck &&[ -e "$PIN" ] &&loaded=$(writer_chain) &&[ "$loaded" != "$before" ] &&- ./helper/test-nv-writer sign &&- ./helper/test-nv-writer sign-shared &&+ ./helper/test-nv-writer raw-extend /dev/tpmrm0 &&[ "$(writer_chain)" = "$loaded" ] &&"$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck &&[ ! -e "$PIN" ] &&@@ -73,45 +102,28 @@ test_expect_success 'root cannot sign while the trusted NV writer remains live'[ "$after" != "$loaded" ]'-test_expect_success 'root cannot update, revoke or invalidate the NV signing key' '- ./helper/test-nv-writer update &&- ./helper/test-nv-writer revoke &&- ./helper/test-nv-writer invalidate-'--test_expect_success 'root cannot change the NV signing key permissions' '- ./helper/test-nv-writer setperm-'--test_expect_success 'root cannot clear, revoke, invalidate or change the writer keyring' '- ./helper/test-nv-writer ring-clear &&- ./helper/test-nv-writer ring-revoke &&- ./helper/test-nv-writer ring-invalidate &&- ./helper/test-nv-writer ring-setperm-'--test_expect_success 'the TPM rejects an unsigned production-register extension over an inherited connection' '+test_expect_success 'an inherited TPM connection cannot extend the register' './helper/test-tpm-preopened >"$W/preopened.log" &&- grep -qx "inherited-TPM: unsigned NV_Extend rejected by TPM; value unchanged" \+ grep -qx "inherited-TPM: unsigned NV_Extend rejected by LSM; value unchanged" \"$W/preopened.log"'-test_expect_success 'trusted status still reads the TPM after denied key access' '- "$SHIRUDO_BIN" status --json >"$W/status.json" &&- grep -q "\"chain_matches_eventlog\":true" "$W/status.json"-'--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\"])") &&+test_expect_success 'TPM policy binds the nonce and exact command on a scratch index' '+ before=$(writer_chain) &&./helper/test-nv-cphash >"$W/cphash.log" &&- grep -qx "PolicySigned: replay and corruption rejected; value unchanged" "$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" ]+ [ "$(writer_chain)" = "$before" ]+'++test_expect_success 'untrusted clients can still extend an unused PCR' '+ before=$(./helper/test-register pcr 23) &&+ event=$(python3 -c "print(\"a5\" * 32)") &&+ ./helper/test-register pcr-extend 23 "$event" | grep -qx "rc=0" &&+ want=$(python3 -c "import hashlib; print(hashlib.sha256(bytes.fromhex(\"$before$event\")).hexdigest())") &&+ [ "$(./helper/test-register pcr 23)" = "$want" ]'test_donediff --git a/testing/tpm/t1128-nv-writer-cleanup.sh b/testing/tpm/t1128-nv-writer-cleanup.shdeleted file mode 100644index a545d796..00000000--- a/testing/tpm/t1128-nv-writer-cleanup.sh+++ /dev/null@@ -1,69 +0,0 @@-#!/bin/sh-# SPDX-License-Identifier: BSD-2-Clause-# Copyright (c) 2026 Authors of shirudo--cd "$(dirname "$0")/.."-. ./test-lib.sh--[ "${SHIRUDO_TEST_REGISTER_VM:-0}" = 1 ] ||- test_skip_all "requires an uninitialized disposable VM"-[ "$(id -u)" = 0 ] && [ ! -e /run/shirudo/bpffs/identity ] &&- [ ! -e /run/shirudo/bpffs/lsm_link ] || {- echo "NV cleanup tests require root before shirudo init" >&2- exit 1-}-R=./helper/test-nv-writer-cleanup-F=./fixtures/nv-writer-fault.bpf.o-[ -x "$R" ] || { echo "missing $R" >&2; exit 1; }--if [ "${SHIRUDO_TEST_NO_PKCS8:-0}" = 1 ]; then- config="/boot/config-$(uname -r)"- grep -qx '# CONFIG_PKCS8_PRIVATE_KEY_PARSER is not set' "$config" || {- echo "parser-disabled test requires the booted kernel config at $config" >&2- exit 1- }- test_expect_success 'PKCS#8 rejection leaves both keyrings unchanged on repeated attempts' '- for attempt in 1 2 3; do- "$R" no-pkcs8 || exit 1- done- '- test_done-fi--: "${SHIRUDO_TEST_NV_CERT:?path to a test DER certificate is required}"-[ -s "$F" ] || { echo "missing $F" >&2; exit 1; }-mkdir -p /run/shirudo/bpffs-if mountpoint -q /run/shirudo/bpffs; then- echo "NV cleanup tests require an unused private bpffs" >&2- exit 1-fi-mount -t bpf -o nosuid,nodev,noexec bpf /run/shirudo/bpffs-cleanup() {- status=$?- trap - EXIT- umount /run/shirudo/bpffs || status=1- exit "$status"-}-trap cleanup EXIT-trap 'exit 1' HUP INT TERM-"$R" enroll "$SHIRUDO_TEST_NV_CERT"--test_expect_success 'successful creation retains both links and can sign until explicit cleanup' '- "$R" success-'--test_expect_success 'private-key import failure leaves both keyrings unchanged on repeated attempts' '- for attempt in 1 2 3; do- "$R" import "$F" || exit 1- done-'--test_expect_success 'identity-map update failure rolls back the successfully created writer' '- "$R" update "$F"-'--test_expect_success 'identity-map freeze failure rolls back the successfully created writer' '- "$R" freeze "$F"-'--test_done