Skip to content

eBPF-based security platform

nv-writer: provision and guard the boot signing key

Leonard Cohnen60c363c3feab
diff --git a/Documentation/architecture.rst b/Documentation/architecture.rst
index 2068b278..8a128509 100644
--- a/Documentation/architecture.rst
+++ b/Documentation/architecture.rst
@@ -135,7 +135,8 @@ root and ``tools/shirudo-build`` on ``PATH``. Without the helper,
The target holds the certificate, the sealed keyring, the private bpffs
mount, 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 private key and never signs.
+``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.
Delivery is pull-based. The operator publishes a package to an OCI
registry; the target pulls it on a timer or by hand, verifies the
@@ -318,6 +319,8 @@ otherwise detach everything. Named refusal points increment counters in
a frozen map pinned beside the identity map
(``bpf/lib/shirudo_tamper.h``); ``shirudo status`` reads it back. Device, parent-mount and process checks do not yet have counters. A refusal
at an earlier image check therefore need not increment a shared counter.
+Search denials on NV keys are not counted: traversal probes use the
+same permission as signing and invalidation.
Filesystem seal. Initialization labels existing state under
``/var/lib/shirudo/`` with ``security.bpf.shirudo``. The fixed 64-byte label
@@ -436,6 +439,14 @@ it never retries the previous boot's PCR extension. The
`config-images <config-images.rst>`__ guide describes this flow and the
deferred TPM writer limitation.
+The boot-scoped NV writer is separate from the operator's artifact key.
+Trusted initialization imports it into a sealed kernel keyring and freezes
+its public key and key IDs into the identity map. The mandatory key guard
+permits signing only from tasks with authenticated runtime authority.
+The key survives switch-root and TPM resets within that
+kernel boot. `The TPM design <tpm.rst#write-policy>`__ describes its
+key custody and trust assumptions.
+
7) Target state
---------------
diff --git a/Documentation/requirements.rst b/Documentation/requirements.rst
index 53604c22..65a34594 100644
--- a/Documentation/requirements.rst
+++ b/Documentation/requirements.rst
@@ -96,6 +96,11 @@ fixture.
* - ``CONFIG_CRYPTO_SHA256``
- ``excl_prog_hash``, ``payload_sha256``, the measurement register
and the eventlog digests.
+ * - ``CONFIG_PKCS8_PRIVATE_KEY_PARSER=y``, ``CONFIG_CRYPTO_RSA=y``
+ - Import and RSASSA-PKCS1-v1_5/SHA-256 signing with the
+ kernel-held RSA-3072 NV writer key. The TPM must also support
+ RSA-3072 public-key loading and RSASSA/SHA-256 verification;
+ there is no RSA-2048 or alternative-algorithm fallback.
* - ``CONFIG_TCG_TPM`` plus a TPM driver (``CONFIG_TCG_TIS``,
``CONFIG_TCG_CRB``, or the platform's virtual TPM)
- The measurement register and the attestation key. A TPM 2.0 is
@@ -299,6 +304,11 @@ since the libguestfs appliance resolves names through DNS alone.
* - TPM attestation
- ECDSA P-256 (the attestation key); TPMs sign with nothing
post-quantum today, so the evidence is classical.
+ * - NV write authorization
+ - RSA-3072 RSASSA-PKCS1-v1_5 with SHA-256 through
+ ``PolicySigned``. The kernel holds the private key and shirudo
+ holds the public key in the frozen identity map to provision the TPM with
+ for each session.
* - TLS (registries, OTLP and S3 export)
- TLS 1.3 only with hybrid ML-KEM key exchange only
(X25519MLKEM768, SecP256r1MLKEM768), on every libcurl client in
diff --git a/Documentation/tpm.rst b/Documentation/tpm.rst
index 29945d6f..ac0dbea8 100644
--- a/Documentation/tpm.rst
+++ b/Documentation/tpm.rst
@@ -71,6 +71,13 @@ The write policy is ``PolicyOR(written, init)`` with two branches:
``leave-initrd``, so a register bound from the initrd can be bound by
nothing 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.
+
The index's TPM name is the SHA-256 of its public area (handle, name
algorithm, attributes, policy digest, size), prefixed with the
algorithm identifier ``000b``. Because ``TPMA_NV_WRITTEN`` is part of
diff --git a/Makefile.shirudo b/Makefile.shirudo
index 6741547c..a42e1385 100644
--- a/Makefile.shirudo
+++ b/Makefile.shirudo
@@ -172,6 +172,7 @@ UTIL_SRCS := \
util/keyring.c \
util/keys.c \
util/identity.c \
+ util/nv_writer.c \
util/tamper.c \
util/initrd.c \
util/paths.c \
@@ -360,9 +361,9 @@ build/target/%.o: %.c Makefile.shirudo $(CONFIG_MK)
# and UAPI kernel headers from vendor/libbpf, and shirudo's own BPF
# library headers from bpf/lib.
bpf/%.bpf.o: bpf/%.c $(VMLINUX_H) $(BPF_LIBBPF_HEADERS) \
- $(wildcard bpf/*.h bpf/lib/*.h)
+ $(wildcard bpf/*.h bpf/lib/*.h) include/shirudo/tpm.h
@printf ' CLANG $@\n'
- $(Q)$(CLANG_BPF) -Ibpf/lib -I$(dir $(VMLINUX_H)) -I$(LIBBPF_VENDOR) \
+ $(Q)$(CLANG_BPF) -Iinclude -Ibpf/lib -I$(dir $(VMLINUX_H)) -I$(LIBBPF_VENDOR) \
-I$(BPF_UAPI_INCLUDE) \
-c $< -o $@
diff --git a/bpf/admission.h b/bpf/admission.h
index 5e2c24d1..373c9bdd 100644
--- a/bpf/admission.h
+++ b/bpf/admission.h
@@ -270,6 +270,31 @@ static __always_inline int shirudo_bpffs_guard(__u32 target_dev,
return -EPERM;
}
+/*
+ * NV-key search can sign or invalidate even when possessed. Do not count
+ * search denials: ordinary keyring traversal probes use that permission.
+ */
+static __always_inline int handle_nv_sig_key(const struct shirudo_sb_id *id,
+ enum key_need_perm need)
+{
+ if (need == KEY_NEED_VIEW || shirudo_task_is_self(id))
+ return 0;
+ if (need == KEY_NEED_SEARCH)
+ return -EACCES;
+ return shirudo_tamper_deny(SHIRUDO_TAMPER_KEYRING, -EACCES);
+}
+
+static __always_inline int handle_nv_keyring(const struct shirudo_sb_id *id,
+ enum key_need_perm need)
+{
+ if (need == KEY_NEED_VIEW || need == KEY_NEED_READ ||
+ shirudo_task_is_self(id))
+ return 0;
+ if (need == KEY_NEED_SEARCH)
+ return -EACCES;
+ return shirudo_tamper_deny(SHIRUDO_TAMPER_KEYRING, -EACCES);
+}
+
/*
* The trust anchor in the kernel's keyrings: the keyring init froze
* and the keys it holds. Root owns the bpf keyring with write and
@@ -293,6 +318,16 @@ int BPF_PROG(shirudo_lsm_key_permission, key_ref_t key_ref,
if (ret)
return ret;
+ id = bpf_map_lookup_elem(&shirudo_bpffs_sb, &zero);
+ if (!id)
+ return 0;
+ key = (struct key *)((unsigned long)key_ref & ~1UL);
+ serial = BPF_CORE_READ(key, serial);
+ if (serial == id->nv_writer_key)
+ return handle_nv_sig_key(id, need);
+ if (serial == id->nv_writer_ring)
+ return handle_nv_keyring(id, need);
+
switch (need) {
case KEY_NEED_WRITE:
case KEY_NEED_SEARCH:
@@ -302,12 +337,9 @@ int BPF_PROG(shirudo_lsm_key_permission, key_ref_t key_ref,
default:
return 0;
}
- id = bpf_map_lookup_elem(&shirudo_bpffs_sb, &zero);
- if (!id || id->keyring_serial == 0)
+ if (id->keyring_serial == 0)
return 0;
possessed = (unsigned long)key_ref & 1;
- key = (struct key *)((unsigned long)key_ref & ~1UL);
- serial = BPF_CORE_READ(key, serial);
if (serial != id->keyring_serial) {
for (i = 0; i < SHIRUDO_IDENTITY_KEYS_MAX; i++)
if (i < id->n_keys && id->key_serials[i] == serial)
diff --git a/bpf/lib/shirudo_identity.h b/bpf/lib/shirudo_identity.h
index cb256455..fb1e6ca6 100644
--- a/bpf/lib/shirudo_identity.h
+++ b/bpf/lib/shirudo_identity.h
@@ -4,6 +4,8 @@
#ifndef SHIRUDO_BPF_IDENTITY_H
#define SHIRUDO_BPF_IDENTITY_H
+#include <shirudo/tpm.h>
+
/* Frozen ABI shared with struct shirudo_identity in util/identity.h. */
#define SHIRUDO_IDENTITY_KEYS_MAX 16
@@ -15,6 +17,9 @@ struct shirudo_sb_id {
__u32 n_keys;
__s32 key_serials[SHIRUDO_IDENTITY_KEYS_MAX];
__u8 runtime_root[32];
+ __s32 nv_writer_ring;
+ __s32 nv_writer_key;
+ __u8 nv_writer_public[SHIRUDO_TPM_NV_RSA_BYTES];
};
struct {
diff --git a/builtin-init.c b/builtin-init.c
index abc96899..3f041a0c 100644
--- a/builtin-init.c
+++ b/builtin-init.c
@@ -50,6 +50,7 @@
#include "util/loader.h"
#include "util/log.h"
#include "util/malloc.h"
+#include "util/nv_writer.h"
#include "util/paths.h"
#include "util/preflight.h"
#include "util/seal.h"
@@ -586,6 +587,14 @@ static int init_lsm(void)
struct stat st;
if (access(shirudo_gate_guards[SHIRUDO_GUARD_BPF].pin, F_OK) == 0) {
+ err = identity_read(&id);
+ if (err || id.nv_writer_ring <= 0 ||
+ id.nv_writer_key <= 0 ||
+ access(SHIRUDO_KEY_PERMISSION_LINK_PIN, F_OK)) {
+ pr_err("init: NV writer protection missing; reboot "
+ "with the updated initrd");
+ return err ? err : -EACCES;
+ }
pr_info("bpf2 already attached (%s exists)",
shirudo_gate_guards[SHIRUDO_GUARD_BPF].pin);
return 0;
@@ -669,6 +678,13 @@ static int init_lsm(void)
}
id.n_keys = (__u32)keys.n;
memcpy(id.key_serials, keys.serials, keys.n * sizeof(keys.serials[0]));
+ err = nv_writer_create(&id.nv_writer_ring, &id.nv_writer_key, id.nv_writer_public);
+ if (err) {
+ pr_err("init: create RSA-3072 NV writer: %s "
+ "(requires kernel PKCS#8 private-key and RSA support)",
+ strerror(-err));
+ goto out;
+ }
m_sb = bpf_object__find_map_by_name(obj, "shirudo_bpffs_sb");
if (!m_sb) {
@@ -756,7 +772,6 @@ static int init_lsm(void)
pr_err("attach lsm/key_permission: %s", strerror(-err));
goto out;
}
-
/*
* With the other bpffs guards, so the mount is immutable before
* enforcement goes live.
diff --git a/contrib/build-kernel-package.sh b/contrib/build-kernel-package.sh
index a60745ca..b3d490e4 100755
--- a/contrib/build-kernel-package.sh
+++ b/contrib/build-kernel-package.sh
@@ -383,6 +383,7 @@ CONFIG_KEYS=y
CONFIG_ASYMMETRIC_KEY_TYPE=y
CONFIG_ASYMMETRIC_PUBLIC_KEY_SUBTYPE=y
CONFIG_X509_CERTIFICATE_PARSER=y
+CONFIG_PKCS8_PRIVATE_KEY_PARSER=y
CONFIG_PKCS7_MESSAGE_PARSER=y
CONFIG_SYSTEM_DATA_VERIFICATION=y
CONFIG_SYSTEM_TRUSTED_KEYS=""
@@ -563,6 +564,8 @@ require_config CONFIG_SECCOMP y
require_config CONFIG_SECCOMP_FILTER y
require_config CONFIG_CROSS_MEMORY_ATTACH y
require_config CONFIG_SYSTEM_DATA_VERIFICATION y
+require_config CONFIG_PKCS8_PRIVATE_KEY_PARSER y
+require_config CONFIG_CRYPTO_RSA y
require_config CONFIG_UPROBES y
require_config CONFIG_SECCOMP y
require_config CONFIG_SECCOMP_FILTER y
diff --git a/testing/helper/test-seal-seccomp.py b/testing/helper/test-seal-seccomp.py
index 7083c31b..303e770d 100644
--- a/testing/helper/test-seal-seccomp.py
+++ b/testing/helper/test-seal-seccomp.py
@@ -23,6 +23,7 @@ with tempfile.TemporaryDirectory(prefix="shirudo-seal-seccomp-") as directory:
command += ["-target", "bpf", "-O2", "-g", "-Wall", "-Wextra", "-Werror",
"-Wno-missing-declarations", "-Wno-unused-parameter",
"-Wdeclaration-after-statement", "-I" + str(work),
+ "-I" + str(root / "include"),
"-I" + str(root / "bpf/lib"),
"-I" + str(root / "vendor/libbpf"),
"-I" + str(root / "vendor/libbpf/include/uapi"),
diff --git a/testing/t0015-test-vm-cli.sh b/testing/t0015-test-vm-cli.sh
index 8600b7cd..a2dc0200 100755
--- a/testing/t0015-test-vm-cli.sh
+++ b/testing/t0015-test-vm-cli.sh
@@ -495,6 +495,14 @@ test_expect_success 'the VM kernel is not built on an unsupported architecture'
"$WORK/riscv64-kernel.out"
'
+test_expect_success 'the kernel builder requires the NV writer parser and RSA support' '
+ for symbol in PKCS8_PRIVATE_KEY_PARSER CRYPTO_RSA; do
+ grep -qx "CONFIG_$symbol=y" ../contrib/build-kernel-package.sh &&
+ grep -qx "require_config CONFIG_$symbol y" ../contrib/build-kernel-package.sh ||
+ exit 1
+ done
+'
+
test_expect_success 'all kernel and VM builds use the slim profile' '
! grep -Eq "^(kernel-small|vm-small|test-vm-small-bundle):" ../testing/Makefile &&
! grep -q "KERNEL_PROFILE" ../testing/Makefile ../contrib/build-kernel-package.sh &&
diff --git a/testing/t0053-mode-objects.sh b/testing/t0053-mode-objects.sh
index 96ad41cf..aaa4b436 100755
--- a/testing/t0053-mode-objects.sh
+++ b/testing/t0053-mode-objects.sh
@@ -33,4 +33,45 @@ assert "bpf_real_data_inode" in inventory["seal"]["extern"]
PYTEST
'
+test_expect_success 'the PR_SET_MM fixture matches the native identity map ABI' '
+ python3 - <<"PYTEST"
+import ast
+import ctypes
+import os
+from pathlib import Path
+import shlex
+import subprocess
+import tempfile
+
+root = Path.cwd().parent
+path = root / "testing/tamperproof/t1131-pr-set-mm-identity.py"
+definition = next(node for node in ast.parse(path.read_text()).body
+ if isinstance(node, ast.ClassDef) and node.name == "ShirudoIdentity")
+namespace = {"ctypes": ctypes}
+exec(compile(ast.Module(body=[definition], type_ignores=[]), str(path), "exec"), namespace)
+identity = namespace["ShirudoIdentity"]
+fields = [name for name, field_type in identity._fields_]
+source = "\n".join([
+ "#include <stddef.h>",
+ "#include <stdio.h>",
+ "#include \"util/identity.h\"",
+ "int main(void)",
+ "{",
+ "\tprintf(\"%zu\\n\", sizeof(struct shirudo_identity));",
+ *[f"\tprintf(\"%zu\\n\", offsetof(struct shirudo_identity, {name}));" for name in fields],
+ "\treturn 0;",
+ "}",
+])
+with tempfile.TemporaryDirectory(prefix="shirudo-identity-abi-") as directory:
+ binary = Path(directory) / "identity-layout"
+ command = shlex.split(os.environ.get("CC", "cc"))
+ command += ["-std=gnu11", "-I" + str(root), "-I" + str(root / "include"),
+ "-x", "c", "-", "-o", str(binary)]
+ subprocess.run(command, input=source, text=True, check=True)
+ actual = [int(value) for value in subprocess.check_output([binary], text=True).split()]
+expected = [ctypes.sizeof(identity)] + [getattr(identity, name).offset for name in fields]
+assert actual == expected, (actual, expected)
+PYTEST
+'
+
test_done
diff --git a/testing/tamperproof/t1131-pr-set-mm-identity.py b/testing/tamperproof/t1131-pr-set-mm-identity.py
index 78718e39..e84a684b 100644
--- a/testing/tamperproof/t1131-pr-set-mm-identity.py
+++ b/testing/tamperproof/t1131-pr-set-mm-identity.py
@@ -74,7 +74,10 @@ class ShirudoIdentity(ctypes.Structure):
("keyring_type", ctypes.c_uint32),
("n_keys", ctypes.c_uint32),
("key_serials", ctypes.c_int32 * 16),
- ("runtime_root", ctypes.c_uint8 * 32)]
+ ("runtime_root", ctypes.c_uint8 * 32),
+ ("nv_writer_ring", ctypes.c_int32),
+ ("nv_writer_key", ctypes.c_int32),
+ ("nv_writer_public", ctypes.c_uint8 * 384)]
def assert_frozen_runtime():
diff --git a/util/identity.h b/util/identity.h
index 56909254..bdd1d7e5 100644
--- a/util/identity.h
+++ b/util/identity.h
@@ -9,6 +9,7 @@
#define SHIRUDO_UTIL_IDENTITY_H
#include <shirudo/misc.h>
+#include <shirudo/tpm.h>
/* The keyring kinds the kernel names in a verdict (enum bpf_sig_keyring). */
#define SHIRUDO_SIG_KEYRING_BPF 5
@@ -25,6 +26,9 @@ struct shirudo_identity {
__u32 n_keys;
__s32 key_serials[SHIRUDO_IDENTITY_KEYS_MAX];
__u8 runtime_root[32];
+ __s32 nv_writer_ring;
+ __s32 nv_writer_key;
+ __u8 nv_writer_public[SHIRUDO_TPM_NV_RSA_BYTES];
};
#define SHIRUDO_TASK_TRUSTED 1
@@ -61,7 +65,7 @@ _Static_assert(sizeof(struct shirudo_device_authority) == 48,
"device authority ABI");
_Static_assert(sizeof(struct shirudo_task_authority) == 8,
"task authority ABI");
-_Static_assert(sizeof(struct shirudo_identity) == 116,
+_Static_assert(sizeof(struct shirudo_identity) == 508,
"frozen identity ABI");
/*
diff --git a/util/nv_writer.c b/util/nv_writer.c
new file mode 100644
index 00000000..76f76569
--- /dev/null
+++ b/util/nv_writer.c
@@ -0,0 +1,179 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/* Copyright (c) 2026 Authors of shirudo */
+
+#include <errno.h>
+#include <linux/keyctl.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/random.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+#include <openssl/core_names.h>
+#include <openssl/evp.h>
+#include <openssl/rsa.h>
+#include <openssl/x509.h>
+
+#include <shirudo/string.h>
+
+#include "crypto.h"
+#include "identity.h"
+#include "log.h"
+#include "malloc.h"
+#include "nv_writer.h"
+
+#define KEY_USR_VIEW 0x00010000
+#define KEY_USR_READ 0x00020000
+#define KEY_USR_WRITE 0x00040000
+#define KEY_USR_SEARCH 0x00080000
+#define KEY_USR_SETATTR 0x00200000
+#define KEY_POS_VIEW 0x01000000
+#define KEY_POS_READ 0x02000000
+#define KEY_POS_WRITE 0x04000000
+#define KEY_POS_SEARCH 0x08000000
+#define KEY_POS_LINK 0x10000000
+#define KEY_POS_SETATTR 0x20000000
+
+#define NV_RING_READ (KEY_POS_VIEW | KEY_POS_READ | KEY_POS_SEARCH | \
+ KEY_USR_VIEW | KEY_USR_READ | KEY_USR_SEARCH)
+#define NV_RING_WRITE (NV_RING_READ | KEY_POS_WRITE | KEY_POS_LINK | KEY_POS_SETATTR | \
+ KEY_USR_WRITE | KEY_USR_SETATTR)
+
+#define NV_WRITER_SIGN_INFO "enc=pkcs1 hash=sha256"
+
+int nv_writer_create(key_serial_t *ring, key_serial_t *writer,
+ __u8 public[SHIRUDO_TPM_NV_RSA_BYTES])
+{
+ PKCS8_PRIV_KEY_INFO *info = NULL;
+ EVP_PKEY_CTX *ctx = NULL;
+ int len = 0, rc = -EIO;
+ char description[64];
+ EVP_PKEY *key = NULL;
+ __u8 *der = NULL, *p;
+ BIGNUM *n = NULL;
+ ssize_t got;
+ __u64 nonce;
+ long ret;
+
+ ctx = EVP_PKEY_CTX_new_from_name(NULL, "RSA", NULL);
+ if (!ctx || EVP_PKEY_keygen_init(ctx) <= 0 ||
+ EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 3072) <= 0 ||
+ EVP_PKEY_keygen(ctx, &key) <= 0 ||
+ EVP_PKEY_get_bn_param(key, OSSL_PKEY_PARAM_RSA_N, &n) <= 0 ||
+ BN_bn2binpad(n, public, SHIRUDO_TPM_NV_RSA_BYTES) != SHIRUDO_TPM_NV_RSA_BYTES) {
+ openssl_complain("generate RSA-3072 NV writer");
+ goto out;
+ }
+ info = EVP_PKEY2PKCS8(key);
+ if (!info)
+ goto out;
+ len = i2d_PKCS8_PRIV_KEY_INFO(info, NULL);
+ if (len <= 0)
+ goto out;
+ der = xmalloc(len);
+ if (!der) {
+ rc = -ENOMEM;
+ goto out;
+ }
+ p = der;
+ if (i2d_PKCS8_PRIV_KEY_INFO(info, &p) != len)
+ goto out;
+ do {
+ got = getrandom(&nonce, sizeof(nonce), 0);
+ } while (got < 0 && errno == EINTR);
+ if (got != sizeof(nonce)) {
+ rc = got < 0 ? -errno : -EIO;
+ goto out;
+ }
+ rc = strsprintf(description, sizeof(description), "shirudo.nv-writer.%016llx", nonce);
+ if (rc < 0)
+ goto out;
+ ret = syscall(__NR_add_key, "keyring", description, NULL, 0,
+ KEY_SPEC_SESSION_KEYRING);
+ if (ret < 0)
+ goto key_error;
+ *ring = (key_serial_t)ret;
+ if (syscall(__NR_keyctl, KEYCTL_SETPERM, *ring, NV_RING_WRITE, 0, 0) < 0 ||
+ syscall(__NR_keyctl, KEYCTL_LINK, *ring, KEY_SPEC_USER_KEYRING, 0, 0) < 0)
+ goto key_error;
+ ret = syscall(__NR_add_key, "asymmetric", "shirudo.nv-writer",
+ der, (size_t)len, *ring);
+ if (ret < 0)
+ goto key_error;
+ *writer = (key_serial_t)ret;
+ if (syscall(__NR_keyctl, KEYCTL_SETPERM, *writer,
+ KEY_USR_VIEW | KEY_USR_SEARCH, 0, 0) < 0 ||
+ syscall(__NR_keyctl, KEYCTL_RESTRICT_KEYRING, *ring, 0, 0, 0) < 0 ||
+ syscall(__NR_keyctl, KEYCTL_SETPERM, *ring, NV_RING_READ, 0, 0) < 0)
+ goto key_error;
+ rc = 0;
+ goto out;
+key_error:
+ rc = -errno;
+out:
+ xfree(der, len > 0 ? (size_t)len : 0);
+ PKCS8_PRIV_KEY_INFO_free(info);
+ BN_free(n);
+ EVP_PKEY_free(key);
+ EVP_PKEY_CTX_free(ctx);
+ return rc;
+}
+
+int nv_writer_read(__u8 public[SHIRUDO_TPM_NV_RSA_BYTES])
+{
+ struct shirudo_identity id = {};
+ int rc;
+
+ rc = identity_read(&id);
+ if (rc)
+ goto fail;
+ if (id.nv_writer_ring <= 0 || id.nv_writer_key <= 0) {
+ rc = -EKEYREJECTED;
+ goto fail;
+ }
+ memcpy(public, id.nv_writer_public, sizeof(id.nv_writer_public));
+ return 0;
+fail:
+ pr_err("nv writer: public key lookup failed: %s", strerror(-rc));
+ return rc;
+}
+
+int nv_writer_sign_key(key_serial_t key,
+ const __u8 digest[SHIRUDO_TPM_DIGEST_LEN],
+ __u8 signature[SHIRUDO_TPM_NV_RSA_BYTES])
+{
+ struct keyctl_pkey_params params = {
+ .key_id = key,
+ .in_len = SHIRUDO_TPM_DIGEST_LEN,
+ .out_len = SHIRUDO_TPM_NV_RSA_BYTES,
+ };
+ long ret;
+ int rc;
+
+ ret = syscall(__NR_keyctl, KEYCTL_PKEY_SIGN, &params,
+ NV_WRITER_SIGN_INFO, digest, signature);
+ if (ret == SHIRUDO_TPM_NV_RSA_BYTES)
+ return 0;
+ rc = ret < 0 ? -errno : -EPROTO;
+ pr_err("nv writer: kernel signing failed: %s", strerror(-rc));
+ return rc;
+}
+
+int nv_writer_sign(const __u8 digest[SHIRUDO_TPM_DIGEST_LEN],
+ __u8 signature[SHIRUDO_TPM_NV_RSA_BYTES])
+{
+ struct shirudo_identity id = {};
+ int rc;
+
+ rc = identity_read(&id);
+ if (rc)
+ goto fail;
+ if (id.nv_writer_key <= 0) {
+ rc = -EKEYREJECTED;
+ goto fail;
+ }
+ return nv_writer_sign_key(id.nv_writer_key, digest, signature);
+fail:
+ pr_err("nv writer: kernel signing failed: %s", strerror(-rc));
+ return rc;
+}
diff --git a/util/nv_writer.h b/util/nv_writer.h
new file mode 100644
index 00000000..ede2980e
--- /dev/null
+++ b/util/nv_writer.h
@@ -0,0 +1,18 @@
+/* SPDX-License-Identifier: BSD-2-Clause */
+/* Copyright (c) 2026 Authors of shirudo */
+#ifndef SHIRUDO_NV_WRITER_H
+#define SHIRUDO_NV_WRITER_H
+
+#include "keyring.h"
+#include "tpm_wire.h"
+
+int nv_writer_create(key_serial_t *ring, key_serial_t *writer,
+ __u8 public[SHIRUDO_TPM_NV_RSA_BYTES]);
+int nv_writer_read(__u8 public[SHIRUDO_TPM_NV_RSA_BYTES]);
+int nv_writer_sign(const __u8 digest[SHIRUDO_TPM_DIGEST_LEN],
+ __u8 signature[SHIRUDO_TPM_NV_RSA_BYTES]);
+int nv_writer_sign_key(key_serial_t key,
+ const __u8 digest[SHIRUDO_TPM_DIGEST_LEN],
+ __u8 signature[SHIRUDO_TPM_NV_RSA_BYTES]);
+
+#endif /* SHIRUDO_NV_WRITER_H */